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

后端 未结 5 975
臣服心动
臣服心动 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:42

    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.

提交回复
热议问题