Categories

See More
Popular Forum

MBA (4887) B.Tech (1769) Engineering (1486) Class 12 (1030) Study Abroad (1004) Computer Science and Engineering (988) Business Management Studies (865) BBA (846) Diploma (746) CAT (651) B.Com (648) B.Sc (643) JEE Mains (618) Mechanical Engineering (574) Exam (525) India (462) Career (452) All Time Q&A (439) Mass Communication (427) BCA (417) Science (384) Computers & IT (Non-Engg) (383) Medicine & Health Sciences (381) Hotel Management (373) Civil Engineering (353) MCA (349) Tuteehub Top Questions (348) Distance (340) Colleges in India (334)
See More

Issues with loop skipping every other input in java

Course Queries Syllabus Queries
Max. 2000 characters
Replies

usr_profile.png
Brian Burl

User

( 6 months ago )

 

I'm trying to create this rather simple program for my java class. Everything is working, except for when I tried to have an input loop. I've never done that before, and it's ignoring every other input. Here is the problem prompt:

B. Ch. 4 – Average - Write a program that will read an unspecified number of integer grades and find the summary total and average. Print grades, total and average. The last record will be the trailer record of -1. Also output the final letter grade per syllabus grading scale.

And here is the code:

import java.util.Scanner;
public class Average
{
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        float counter = 0;
        float accum = 0;
        float addAccum = 0;
        float tempLoop = 0;
        System.out.println("Please Enter Grade, Enter -1 to Finish: ");

        while (tempLoop != -1)
        {
            addAccum = in.nextFloat();
            counter++;
            accum = addAccum + accum;
            tempLoop = in.nextFloat();
        }
        float avgGrade = accum / counter;
        if(avgGrade >= 90)
        {
            System.out.println("\nYour Grade is: " + "A");
        }else if(avgGrade >=80)
        {
            System.out.println("\nYour Grade is: " + "B");
        }else if(avgGrade >=70)
        {
            System.out.println("\nYour Grade is: " + "C");
        }else if(avgGrade >=60)
        {
            System.out.println("\nYour Grade is: " + "D");
        }else
        {
            System.out.println("\nYour Grade is: " + "F");
        }
        System.out.println("\nGrade Total: " + accum);
        System.out.println("\nCounter Num :" + counter); // for testing only
        System.out.println("\nAverage Grade: " + avgGrade);
    }
}

This is the console input/output:

Please Enter Grade, Enter -1 to 
								 								 
							usr_profile.png
							
Rahul Chaudhary

User

( 6 months ago )

You have in.nextFloat() twice in your while loop. Change your logic to look for -1 first and then process the input.

Something like :

  tempLoop = in.nextFloat();
  while(tempLoop != -1){

     sum += tempLoop;
     tempLoop = in.nextFloat();
  }

Hope this helps.

what's your interest