Java将计数与用户输入错误进行比较
我正在创建一个while循环,以确定(count==numbers.length)是否会中断while循环。每当我运行print语句查看哪里出错时,无论count设置为什么,numbers.length也设置为相同的值,无论我实际输入了多少个数字(如果有的话)。如何修复此错误Java将计数与用户输入错误进行比较,java,Java,我正在创建一个while循环,以确定(count==numbers.length)是否会中断while循环。每当我运行print语句查看哪里出错时,无论count设置为什么,numbers.length也设置为相同的值,无论我实际输入了多少个数字(如果有的话)。如何修复此错误 // Create a scanner to read user input Scanner s = new Scanner(System.in); // Prompts user to enter the intege
// Create a scanner to read user input
Scanner s = new Scanner(System.in);
// Prompts user to enter the integer count
System.out.print("How many integers would you like to enter: ");
int count = s.nextInt();
s.nextLine();
// s.nextLine() closes the previous scanner reader
while(true) {
// Prompts user to enter the integer numbers here based on count
System.out.print("\nEnter your integer numbers here: ");
int [] numbers = new int[count];
Scanner numScanner = new Scanner(s.nextLine());
for (int i = 0; i < count; i++) {
if (numScanner.hasNextInt()) {
numbers[i] = numScanner.nextInt();
if (numbers.length == count) {
break;
}
}
else {
System.out.print("Must enter the correct amount of numbers");
}
}
}
//创建扫描仪以读取用户输入
扫描仪s=新的扫描仪(System.in);
//提示用户输入整数计数
System.out.print(“您希望输入多少个整数:”);
int count=s.nextInt();
s、 nextLine();
//s.nextLine()关闭上一个扫描仪读取器
while(true){
//提示用户根据计数在此处输入整数
System.out.print(“\n在此处输入整数:”);
int[]数字=新的int[计数];
Scanner numScanner=新扫描仪(s.nextLine());
for(int i=0;i
此行创建一个计数大小的整数数组。因此,在初始化数组时,其大小将等于count
。最终,数组中的所有值都将为0
您可能需要使用列表来代替。e、 g:
List<Integer> numbers = new ArrayList<>();
...
numbers.add(numScanner.nextInt());
这里有几个问题:
首先,您需要使用i
,而不是number.length
,因为前者将为输入的每个数字递增,而后者将始终与count
相同
其次,break
不会退出while
循环,而只是退出for
循环。由于您也想退出while
循环,因此可以使用布尔值代替while(true)
,然后将该值设置为false
boolean needInput = true;
while (needInput) {
....
if (i == count) {
needInput = false;
break;
}
}
if (numbers.size() == count){
break;
}
boolean needInput = true;
while (needInput) {
....
if (i == count) {
needInput = false;
break;
}
}