我的代码有问题。请帮我解决它。当输入 q 时,程序应该退出并返回平均值。如果您输入 5 个数字,则可以正常工作。数组大小应为 20。这是代码:
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;
}
}