我的代码有问题。请帮我解决。输入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;
}
}
答案 0 :(得分:0)
使用List而不是数组。检查输入是否为q打印平均值并返回system.exit(0)
答案 1 :(得分:0)
你应该在每个input.nextInt()之前检查input.hasNextInt()。
答案 2 :(得分:0)
你正在使用复合循环,否定了突破第一个/外部循环的能力。
您应该将两个循环合并为一个循环,查找两个转义条件,用户按q
或输入5个数字......
因为您期望混合输入,所以您需要手动将输入转换为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...");
}
}