简体   繁体   中英

Java Calculating average from users input

I have a problem with my code.Please help me to solve it. Program should quit and return average when q is entered. If you enter 5 numbers it is working fine. The array size should be 20. Here is the code:

import java.util.Scanner;

public class test{

public static void main(String[] args){

int x;

int count=0;
char q= 'q'; 
Scanner input = new Scanner(System.in);
int[] array = new int[5];
System.out.print("You have entered 0 numbers, please enter a number or q to quit:" );

while (input.hasNextInt()){

for (int i = 0; i < array.length; i++)
{

    array[i] = input.next();

    count++;
    System.out.print("You have entered " +count+ " numbers, please enter a number or q to quit:" );
    }
}

System.out.println("Average is " + Average(array));
}



public static int Average(int[] array) {
int sum = 0;
for (int i = 0; i < array.length; i++)
sum += array[i];
return sum / array.length;
}

}

Use List instead of array. Check if input is q print the average and return system.exit(0)

您应该在每个 input.nextInt() 之前检查 input.hasNextInt()。

You're using a compound loop which is negating the ability to break out of the first/outter loop.

You should consolidate the two loops into a single loop, looking for two escape conditions, either the user presses q or they enter 5 numbers...

Because you're expecting mixed input, you need to convert the input manually to an int....

String line = null;
// Loop until count >= 5 or the user inputs "q"
while (count < array.length && !(line = input.nextLine()).equalsIgnoreCase("q")) {
    try {
        // Convert the input to an int...
        int value = Integer.parseInt(line);
        array[count] = value;
        count++;
        System.out.print("You have entered " + count + " array, please enter a number or q to quit:");
    } catch (NumberFormatException exp) {
        System.out.println(line + " is not an int value...");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM