Java how to compute average scores using loops - java

I need to write a program in Java that computes the average score for 4 students. The student will put in their 4 scores, and once they are done they will input -1 to compute the average. Once this is done the program needs to move onto student 2 and so on. At the end it is supposed to display the highest average from the 4 student average test scores. Here is what it should look like when it is run:
Student 1
Enter your score: 100
Enter your score: 90
Enter your score: 80
Enter your score: 70
Enter your score: -1 * once the student enters -1 it should compute average
Average Score = 85.
Student 2
Enter your score: 90
ETC
ETC
The problem with my code is that the average is only correct for the first student. When I input -1 to get the average for the second student, the calculation is incorrect. We are only allowed to use loops. The only hints I was given were that we are supposed to write an outer loop that iterates 4 times, write an inner loop that loops as long as the student has scores to enter, inside the inner loop prompt the user to enter their last score or -1 to compute average. I don't want you guys to do the project for me but to just set me in the right direction. I feel like I am not using the right loop.
import java.util.Scanner;
public class TestScore
{
public static void main(String[]args)
{
double score = 0;
double totalScore = 0;
double count = 0;
double average = 0;
Scanner input = new Scanner(System.in);
System.out.println("Student 1");
System.out.printf("Enter Your Score: ");
score = input.nextDouble();
while (score != -1){
System.out.printf("Enter Your Score: ");
totalScore = totalScore + score;
score = input.nextDouble();
count++;
average = totalScore / count;
if (score == -1){
System.out.printf("Average Score = %.2f\n ",average);
count = 0;
score = 0;
totalScore = 0;
average = 0;
System.out.println("Student 2");
System.out.printf("Enter Your Score: ");
score = input.nextDouble ();
count++;
average = totalScore / count;
}
}
}
}

You haven't explicitly asked a question so I'll try and comply to the "set me in the right direction" part.
I'd suggest re-formatting the loop structure to a cleaner one, like this:
double total;
for(int student = 1; student <= 4; student++) {
System.out.printf("Student %d\n", student);
double sum = 0, count = 0;
while(true) {
System.out.printf("Enter your score: ");
double input = scanner.nextDouble();
if(input == -1) break;
sum += input;
count++;
}
total += sum;
System.out.printf("Average: %.2f\n", sum / count);
}
System.out.printf("Total: %.2f\n", total);
Hope that's enough to give you some pointers.
edit: forgot to take care of total

So, you wish to iteratively go through all the input and just remember the maximum one. Make an integer variable max and after each student, just change it if needed. (It's zero by default jn Java)
As for the calculation for each student, you shouldn't be checking for the failed " score != - 1" condition in each iteration. Instead, you should do the final calculations after the while loop. (average, possible update of the maximum, resetting the variables, etc. )
You also need the outer loop (in the stated code, these calculations are done for one student only) which you would control in a different manner.
Also, if you need to use only 4 grades, you might want to consider using the for loop.

You can try with this :D
public static void main (String[] args) throws java.lang.Exception
{
double average = 0;
double i = 0;
int student = 0;
boolean flag = true;
Scanner input = new Scanner(System.in);
while(flag)
{
System.out.printf("Student: ");
System.out.println(student);
System.out.print("Enter Your Score: ");
double score = input.nextDouble();
if(score!=-1){
average=average+score;
i=i+1;
}
if(score==-1){
System.out.printf("Average: ");
System.out.println(average/i);
//reset values
average = 0;
i = 0;
student=student+1;
}
if(score==-2){
//you need break the while in some moment.
flag = false;
}
}
}

Related

How to calculate sum in java?

I need to write a code where you insert 10 grades and get back the average of those ten grades. I know how to do it, except I don't know how to calculate the sum of all the grades. I found on this site this code:
public int sumAll(int... nums) { //var-args to let the caller pass an arbitrary number of int
int sum = 0; //start with 0
for(int n : nums) { //this won't execute if no argument is passed
sum += n; // this will repeat for all the arguments
}
return sum; //return the sum
}
so I wrote my code like this and it worked!:
import java.util.Scanner;
public class Loop7 {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
System.out.println("Please enter how many grades you want to insert : ");
int num1 = scan.nextInt();
int num;
double sum =0;
for(int i= 0; i<num1; i++)
{
System.out.println("Please enter a grade: ");
num = scan.nextInt();
sum += num;
}
System.out.println("the average is: "+(sum)/num1);
}
so my question is what sum+=num; mean? how does that line give me the sum? and why I had to write double sum= 0?
Over here I explain each of those lines to better help you understand this code.
public class Loop7 {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in); //this is what allows the user to input their data from the console screen
System.out.println("Please enter how many grades you want to insert : "); //this just outputs a message onto the console screen
int num1 = scan.nextInt(); //This is the total number of grades the user provides and is saved in the variable named num1
int num; //just a variable with nothing in it (null)
double sum =0; //this variable is to hold the total sum of all those grades
for(int i= 0; i<num1; i++) //loops as many times as num1 (if num1 is 3 then it loops 3 times)
{
System.out.println("Please enter a grade: "); //output message
num = scan.nextInt(); //every time the loop body executes it reads in a number and saves it in the variable num
sum += num; //num is then added onto sum (sum starts at 0 but when you add 3 sum is now 3 then next time when you add 1 sum is now 4 and so on)
}
System.out.println("the average is: "+(sum)/num1); //to get the average of a bunch of numbers you must add all of them together (which is what the loop is doing) and then you divide it by the number of items (which is what is being done here)
}
sum += num; Means that your sum which is declared 0 is added with num which you get from the console. So you simply make this: sum=sum+num; for the cycle. For example sum is 0, then you add 5 and it becomes sum=0+5, then you add 6 and it becomes sum = 5 + 6 and so on. And it is double because you are using division.
The reason you needed to write
double sum = 0.0;
is because you needed to initialize the sum first. Next the
sum += num;
means
sum = sum + num;
just in a more simple way.

Printing the two highest values from user input

I have an assignment where I have to write a code which lets the user decide an amount of int values to be written in, and then decides what these values should be. There has to be atleast 2 inputs from the user. The program will then compare the values from the input and then print out the two highest values. So far I managed to print out the highest value, but I'm not sure whats wrong with the way I've done it since the output just becomes 0 if I choose to print out 2 numbers and the highest one is entered in first. And I'm also not sure how to keep track of the second highest number either. Would appreciate some help.
import java.util.Scanner;
public class ToStoersteTall{
public static void main(String[] args){
System.out.println("How many numbers? (minimum 2)?:");
Scanner reader = new Scanner(System.in);
if (reader.hasNextInt()) {
int numbers = reader.nextInt();
if (numbers >= 2) {
System.out.println("Enter value #1");
if (reader.hasNextInt()) {
int num1 = reader.nextInt();
System.out.println("Enter value #2");
if (reader.hasNextInt()) {
int num2 = reader.nextInt();
int biggest = 0;
for (int i = 3; i <= tall; i++) {
System.out.println("Enter value #" + i);
int num3 = reader.nextInt();
biggest = num1;
if(biggest < num3){
biggest = num3;
}
}
System.out.println(biggest);
} else {
System.out.println("Please enter an integer");
}
} else {
System.out.println("Please enter an integer");
}
} else {
System.out.println("Please enter an integer equal or higher than 2.");
}
} else {
System.out.print("Vennligst oppgi et heltall større eller lik 2.");
}
}
}
I have an assignment where I have to write a code which lets the user decide an amount of int values to be written in, and then decides what these values should be. There has to be atleast 2 inputs from the user. The program will then compare the values from the input and then print out the two highest values. So far I managed to print out the highest value, but I'm not sure whats wrong with the way I've done it since the output just becomes 0 if I choose to print out 2 numbers and the highest one is entered in first. And I'm also not sure how to keep track of the second highest number either. Would appreciate some help.
A couple things:
good practice to close scanner (and IO-related resources in general)
reduced if-statement blocks bloat for easier readability
you specify 2 guaranteed numbers, so attempt to parse those before looping
can remove system.exit calls or replace system.exit and move bulk of code back into the larger if-else blocks as originally state in OP (but I refer back to the sake of readability)
added check for the first and second numbers input to make sure high1 is highest value, and high2 is second highest value.
keep order while looping and checking values (note: does not use array), if the number is a new high, replace high1 and move high1's value down to high2, or if the number is a second (new) high, replace high2. If values are equal, this logic is excluded and you may want to specify based on your own constraints
import java.io.IOException;
import java.util.Scanner;
public class ToStoersteTall {
public static void main(String[] args) throws IOException {
System.out.println("How many numbers? (minimum 2)?:");
Scanner reader = new Scanner(System.in);
int n = 0;
if (reader.hasNextInt()) {
n = reader.nextInt();
} else {
System.out.println("Vennligst oppgi et heltall større eller lik 2.");
System.exit(-1); // quits execution
}
if (n < 2) {
System.out.println("Please enter an integer equal or higher than 2.");
System.exit(-2);
}
// Since guaranteed 2 numbers, parse and assign now
int high1 = 0, high2 = 0;
System.out.println("Enter value # 1");
if (reader.hasNextInt())
high1 = reader.nextInt();
System.out.println("Enter value # 2");
if (reader.hasNextInt())
high2 = reader.nextInt();
// check to see if a switch to keep correct highest order, swap values if so
if (high1 < high2) {
int t = high2;
high2 = high1;
high1 = t;
}
// loop won't execute if only 2 numbers input, but will if 3 or more specified at start
for (int i = 2; i < n; ++i) {
System.out.println("Enter value #" + (i + 1));
if (reader.hasNextInt()) {
int t = reader.nextInt();
if (t > high1) {
high2 = high1; // throw away high2 value and replace with high1
high1 = t; // replace high1 value with new highest value
} else if (t > high2) {
high2 = t;
}
} else {
System.out.println("Please enter an interger");
}
}
reader.close();
System.out.println("The two highest numbers are: " + high1 + ", " + high2);
}
}
You're already keeping track of the biggest, so why not keep track of the second biggest? Another easy way of solving this problem is to keep all the numbers in a list, sort the list by number size, and grab the two highest entries.
I tried your code and used an array to solve the problem.
import java.util.Scanner;
public class Main {
static int secondHighest(int... nums) {
int high1 = Integer.MIN_VALUE;
int high2 = Integer.MIN_VALUE;
for (int num : nums) {
if (num > high1) {
high2 = high1;
high1 = num;
} else if (num > high2) {
high2 = num;
}
}
return high2;
}
public static void main(String[] args) {
System.out.println("How many numbers? (minimum 2)?:");
Scanner reader = new Scanner(System.in);
if (reader.hasNextInt()) {
int numbers = reader.nextInt();
int[] array = new int[numbers];
if (numbers >= 2) {
System.out.println("Enter value #1");
if (reader.hasNextInt()) {
int num1 = reader.nextInt();
array[0] = num1;
System.out.println("Enter value #2");
if (reader.hasNextInt()) {
int num2 = reader.nextInt();
array[1] = num2;
int biggest = 0;
for (int i = 3; i <= numbers; i++) {
System.out.println("Enter value #" + i);
int num3 = reader.nextInt();
array[i-1] = num3;
}
System.out.println("second largest number is" + secondHighest(array));
int largest = 0;
for(int i =0;i<array.length;i++) {
if(array[i] > largest) {
largest = array[i];
}
}
System.out.println("Largest number in array is : " +largest);
} else {
System.out.println("Please enter an integer");
}
} else {
System.out.println("Please enter an integer");
}
} else {
System.out.println("Please enter an integer equal or higher than 2.");
}
} else {
System.out.print("Vennligst oppgi et heltall større eller lik 2.");
}
}
}
Test
How many numbers? (minimum 2)?:
6
Enter value #1
3
Enter value #2
4
Enter value #3
5
Enter value #4
6
Enter value #5
7
Enter value #6
8
second largest number is7
Largest number in array is : 8
There is a logic error in your program. If numbers is 2, then the for loop never gets executed, and the value of biggest remains zero because it is never updated. Change your declaration of biggest to reflect the current maximum value found so far.
int biggest = num1 > num2 ? num1 : num2;
That way if the for loop never executes then biggest will be the maximum value of the first two numbers.
As for keeping track of the second highest value, you could introduce another variable secondBiggest, initialised in a similar manner to biggest, and then write logic to update this value in your for loop. However, in my opinion, it would be much easier to change your strategy to hold the entered values into an array, then when all inputs have been entered, calculate whichever values you desire from the array. This would lead to a much cleaner solution IMO.
(I have assumed that tall in the for loop is actually meant to be numbers...)
import java.util.Scanner;
public class Foo{
public static void main(String[] args){
System.out.println("How many numbers? (minimum 2)?:");
Scanner reader = new Scanner(System.in);
if(reader.hasNextInt()){
int numbers = reader.nextInt();
if(numbers >= 2){
int[] list = new int[numbers];
for(int i = 0; i < numbers; i++){
System.out.println("Enter value #" + (i + 1));
if(reader.hasNextInt())
list[i] = reader.nextInt();
}//for
int biggest = 0;
int secondBiggest = 0;
// find the values you want
for(int i = 0; i < numbers; i++){
if(list[i] > biggest){
secondBiggest = biggest;
biggest = list[i];
}//if
else if(list[i] > secondBiggest)
secondBiggest = list[i];
}//for
// print your results
System.out.println("The biggest integer is: " + biggest);
System.out.println("The second biggest integer is: " + secondBiggest);
}//if
}//if
}//main
}//class

Java finding the minimum value from Scanner input always resulting in zero

This is my first Java program. It is supposed to allow a user to enter int grades between 0 and 100. If the user enters a negative value, data entry ceases and statistics are displayed. I cannot incorporate static methods, math, or arrays.
I am having an issue with finding the minimum grade, minGrade. Regardless of what values are entered when the program is running, minGrade always results in zero. I have been tinkering with this for a while now to no avail.
The other issue I am having is that when I run the program, and I enter a bunch of int, but then enter some alphabet letters to test the error-checking, the program parses the user twice, instead of once.
"Please enter a numeric grade between 0 and 100, inclusive, and press Enter:"
The respective code is:
import java.util.Scanner;
public class Grades {
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the Course Code and and press Enter:");
String courseCode = keyboard.nextLine();
System.out.println("You entered: " + courseCode + "\n");
int grade = 0;
int numberOfGrades = 0;
int maxGrade = 0;
int minGrade =0;
double avgGrade = 0;
int sumGrades = 0;
int sentinel = 0;
do
{
**System.out.println("Please enter a numeric grade between 0 and 100, inclusive, and press Enter:");**
while(!keyboard.hasNextInt())
{
System.out.println("Please enter a numeric grade between 0 and 100, inclusive, and press Enter:");
keyboard.nextLine();
}
grade = keyboard.nextInt();
if((grade <=100) && (grade >= 0))
{
numberOfGrades++;
sumGrades += grade;
sentinel = 0;
if(maxGrade < grade)
maxGrade = grade;
**if(minGrade > grade)
minGrade= grade;**
}
else if(grade > 100)
{
System.out.println("The entered number was greater than 100. Please enter a number between 0 and 100 inclusive, "
+ "or input a negative number to exit Grade entry");
sentinel = 0;
}
else if(grade <0)
{
grade = 0;//maybe?
sentinel = -1;
}
}
while((grade >100) || (sentinel == 0));
avgGrade = (sumGrades/numberOfGrades);
System.out.println("You entered: " + "\ngrade: " + grade + "\n" + "sentinel: "+ sentinel +
"\nSum of Grades: " + sumGrades +"\nNumber of Grades: "+ numberOfGrades +"\nAverage Grades: " + avgGrade
+ "\nMaxium Grade: "+ maxGrade+"\nMinimum Grade: "+minGrade);
}
}
Any input on this, the form of my code for my first java program, or anything else would be greatly appreciated.
The last issue I am having is that the average grade always has a tenth place of zero. How can I get the tenth place to not be zero and the actual average amount?
Your problem with minGrade is that you initialize it to 0. This is already the min value, hence no other values will be less than this. (You in fact ensure this even more so by setting negative grades to 0.) Initialize it to the max value (100).
It looks like your "double prompt" issue is a common one with nextLine and nextInt. The solution seems to be using only nextLine and then parsing the return value of that for an Integer object. (And printing out your "invalid input" text on a NumberFormatException.
Finally, your avgGrade is always xx.0 as you are dividing two integers, which always gives an integer back. You need to cast one to a double to get a double back:
avgGrade = ((double)sumGrades/numberOfGrades);
minGrade will never be set to anything other than 0 because 0 will never be greater than the grade entered, so this check fails if(minGrade > grade). Try initializing minGrade to Integer.MAX_VALUE.

Java - Using for loop to average set of grades read in from keyboard

First time poster here. I'm aware of the negative stigma carried with asking for help on homework assignments, however I believe this would be an exception as this is an intro course and the professor stated specifically to use Google to find examples of for loops in Java (of which we have yet to even cover in class). I have absolutely no Java experience and would really appreciate any feedback:
Program asks user how many grades there are.
Program asks user for each grade (for loop needed and should sum grades within loop).
Take sum of all grades, compute average and store in a float variable grade.
Print grade value to console and append a number to a string such as "Grade Average is: " + grade
Example should read as:
Enter number of grades: 2
Enter grade: 90
Enter grade: 81
Grade Average is: 85.5
My code so far (not much here):
// This program computes the letter grades for number of grades given by user
import java.util.*;
public class GradeAverage
{
public static void main(String[] args)
{
int count;
float sum = 0;
float grade;
Scanner scan = new Scanner(System.in);
}
}
Edit:
// This program computes the letter grades for number of grades given by user
import java.util.*;
public class GradeAverage
{
public static void main(String[] args)
{
int count;
float sum = 0;
float grade;
Scanner scan = new Scanner(System.in);
System.out.print("Enter number of grades: ");
count = scan.nextInt();
for (int i = 0; i < count; ++i)
System.out.print("Enter grade " + (i + 1) + ": ");
grade = scan.nextFloat();
sum += grade;
System.out.println("The average of the grades is: " + sum/count);
}
}
This is what I have now, however a test displays incorrect results (example):
Enter number of grades: 2
Enter grade 1: Enter grade 2: 50 50
The average of the grades is: 25.0
Each grade needs to be entered on separate lines so the averaging is skewed as a result.
import java.util.Scanner;
public static void main(String[] args) {
int count = 0;
float sum = 0;
float grade = 0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter number of grades: ");
count = scan.nextInt();
for (int i = 0; i < count; i++) {
System.out.print("Enter grade no " + (i + 1) + " : ");
grade = scan.nextFloat();
sum += grade;
}
System.out.println("Sum = " + sum);
System.out.println("Average = " + sum / (float) count);
}
Break the big task into smaller tasks , like #user2864740 said , write the algorithm (not code) on a paper then start translating that to code
u reached the part where u created a scanner to read input , now read the input and ....figure out the rest .
To learn how to read user input read this.
To learn how to make an integer out of Strings ur scanning read this
the rest is basic math really , read your textbook , and good luck ;)
edit : at least come out with some algorithm then maybe we'll help with the code
I won't solve the homework for you, I will help you however:
How to use a for loop:
for (int i = #startValue#; #booleanCondition#; #runTheFollowingCodeAtEachIteration#)
{
//code
}
ex:
for(int i = 0; i<10; i++)
{
System.out.println(i);
}
will display:
0
1
2
3
4
5
6
7
8
9
Your homework:
Program asks how many grades there are:
Scan a value called NumberOfGrades (called count in your code) inputted by the user.
Program asks user for each grade + sums the grades:
Use a for loop, with a starting value of i, and a upper limit of NumberOfGrades. Scan each grade and add it to a value called GradeSum, which initially should be 0 before entering the for loop.
Print value to console... :
Divide GradeSum by NumberofGrades, and display it how you would like it to be displayed.
Tips:
-Use System.out.print("\nEnter grade: "); in your for loop before each scan.
To avoid directly answering your homework question (which both won't help you get it and is probably not allowed), let's start with "what is a for loop?"
A for loop is a fancy loop that does the following things for you:
Initializes one (or more) variables to initial values the first time the loop statement is executed
Each iteration, checks a boolean condition to determine if it should loop again. If the expression evaluates to true, iterate again. Otherwise, break the loop and continue with the code following the loop.
A statement that is run each time the loop finishes iterating.
For example, the following loop would print the numbers 1 .. 10.
for(int i = 1; i <= 10; i++){
System.out.println(i);
}
The first part of the loop statement int i = 1 is the initialization block. i is initialized to an int with value 1 when the for loop is executed for the first time.
The second part of the loop statement i <= 10 is the boolean condition to check to determine if another iteration is required. In this case, i <= 10 evaluates to true if i is less than or equal to 10, and false once i hits 11 (or any larger number).
Finally, the third part i++ is the statement run when the for loop finishes an iteration. i++ adds 1 to the current value of i, thus i will increase in value by 1 each iteration.

Why doesn't my "While Loop" print the computation of finding the average "score"?

I am writing a program that reads a sequence of positive integers input by the user. User will only enter one integer at a time.Then it will compute the average of those integers. The program will end when user enters 0. (0 is not counted in the average).The program will print out the average once the program ends.
Question: My code stops working when I gets to the while loop hence it doesn't compute the input by user, hence prints out nothing. Why doesn't my while loop compute the average from the user's inputs? Appreciate your guidance :)
import java.util.Scanner;
public class AverageOfIntegers {
public static void main(String[] args) {
int integer;
double sum;
sum = 0;
double average;
Scanner input = new Scanner(System.in);
int count; count = 0;
average = 0;
System.out.println("Please enter an integer: ");
integer = input.nextInt();
while (integer != 0) {
count = count + 1;
sum = sum + integer;
average = sum / count;
}
System.out.println("Average = " + average);
}
}
This is because you are never actually summing over more than one integer. The user only ever enters one number. As a result your loop is essentially acting on just the one number. You need to put the input inside the while loop and save a running sum and count there. Something more like this
while (integer != 0) {
count += 1;
sum += integer;
average = sum / count;
integer = input.nextInt();
}
Explanation
First of all, when you define data types, you can set their default value in the definition. Ex:
double sum = 0;
vs
double sum;
sum = 0;
Secondly, sum = sum + integer; is the same as: sum += integer;
Thirdly, count = count + 1; is the same as: count += 1 OR (and better yet), count++;
As for your actual algorithm, there is one problem and one suggestion:
you are not changing integer's value after each loop. So, you can
either do that in the while condition: while ((integer =
input.nextInt()) != 0) { or, at the end of each loop:
while (integer != 0) {
count ++;
sum += integer;
average = sum / count;
integer = input.nextInt();
}
This is a suggestion for technically better code (in my opinion), but it looks better, is more intuitive and requires less calculations to calculate the average after the while loop is done instead of during. That way, you only calculate it once, where needed, vs. every loop, which is not needed.
________________________________________________________________________________
The Code (complete class)
public class AverageOfIntegers {
public static void main(String[] args) {
int integer;
double sum = 0;
double average = 0;
Scanner input = new Scanner(System.in);
int count = 0;
System.out.println("Please enter an integer: ");
// set integer = to the nextInt() while looping so it calculates properly
while ((integer = input.nextInt()) != 0) {
count ++;
sum += integer;
}
average = sum / count; // calculate the average after the while-loop
System.out.println("Average = " + average);
}
}
________________________________________________________________________________
Example input/output:
Please enter an integer:
5
10
15
0
Average = 10.0
So it did 5 + 10 + 15 = 30 (which is the sum), and then the average is 30 / 3 (30 is the sum, 3 is the count), and that gave you Average = 10.0.
You need to move integer = input.nextInt(); inside the loop, so your program will collect inputs in a loop. See the corrected version:
import java.util.Scanner;
public class AverageOfIntegers {
public static void main(String[] args) {
int integer = 0, count = 0;
double sum = 0.0, average = 0.0;
Scanner input = new Scanner(System.in);
System.out.println("Please enter an integer: ");
integer = input.nextInt();
while (integer != 0) {
count = count + 1;
sum = sum + integer;
System.out.println("Please enter an integer: ");
integer = input.nextInt();
}
average = sum / count;
System.out.println("Average = " + average);
}
}
The problem is that the input.nextInt() should be part of the loop. The way you wrote it, the code gooes into an infinite loop whenever the first input is non-zero. Instead, do:
while ((integer = input.nextInt()) != 0) {
count = count + 1;
sum = sum + integer;
average = sum / count;
}
In the loop:
while (integer != 0) {
count = count + 1;
sum = sum + integer;
average = sum / count;
}
This will only stops when integer is 0, but this variable is not changing in the loop, so it will never be 0 if it wasn't already in the first place.
According to what you said you want to do, you should probably repeat the call to integer = input.nextInt(); inside your loop, lke this:
System.out.println("Please enter an integer: ");
integer = input.nextInt();
while (integer != 0) {
count = count + 1;
sum = sum + integer;
System.out.println("Please enter an integer: ");
integer = input.nextInt();
}
average = sum / count;
Also, as others have said, you only need to compute the average once after the loop, so I moved it too.

Categories