Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/392.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java将计数与用户输入错误进行比较_Java - Fatal编程技术网

Java将计数与用户输入错误进行比较

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

我正在创建一个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 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;
    }
}