I am having trouble getting started on the following problem.
Write a method named printGPA that calculates a student's grade point average. The user will type a line of input containing the student's name, then a number of scores, followed by that many integer scores. Here are two example dialogues:
Enter a student record: Maria 5 72 91 84 89 78 Maria's grade is 82.8
Enter a student record: Jordan 4 86 71 62 90 Jordan's grade is 77.25
You need to send each input String to a Scanner object. Use next(), to get your student's name. Then, run a while loop: while(scanner.hasNextInt()). In the body, have an int variable that adds scanner.nextInt() to itself. Also have an int variable that counts the number of loop iterations. Lastly, divide your total score by your iteration counter to get your average.
Joined: Feb 17, 2013
Thanks for the initial push. I figured out that the first number in the string is the number of grades that will follow. How does it look?
No, that will not work. You have a serious logic error.
The advice was good, but it would have been better to say
1: Record the name
2: Add each value to a sum and count the values
3: Divide the total by the count
4: Display the result.
Never, never use == true or == false or anything similar. Not only are they poor style, but they are error‑prone too; you might write = by mistake. It is simply while (myScanner.hasNextInt())) …
Your reading from the keyboard ought to be in a method by itself, preferably in a different class. Actually you would need two methods.
It is also unfortunate that you have been told to take the details from the screen and print the average. Think how much more object‑oriented it would have been to create a Student object which has fields for name, results etc., and can calculate the average for itself.
Joined: Oct 13, 2005
I didn’t realise you had the count of marks in the input. (Sorry) In which case you don’t have a logic error in your code, but there is a logic error in the input. What happens for Campbell 6 11 14 32 20 9 3 0? Including the count of marks in the input can lead to errors. You could have counted the entries in Campbell 11 14 32 20 9 3 0 and worked out the correct average.
You are very close. Since System.in is an InputStream, the while loop will continue waiting for the user to enter more integers (scores). In fact, it will keep waiting until something other than an int is input. Here's a little workaround: use nextLine() to get the input String. Then send that String value to a new Scanner.
Joined: Oct 13, 2005
No, it should be 1.
Beware of Scanner#nextLine. It doesn’t do what lots of people think it does.