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

后端 未结 5 980
臣服心动
臣服心动 2021-01-25 19:10

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 integer

5条回答
  •  终归单人心
    2021-01-25 19:41

    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);
        }
    }
    

提交回复
热议问题