Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/306.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 从stdin获取输入_Java_Io_Stdin - Fatal编程技术网

Java 从stdin获取输入

Java 从stdin获取输入,java,io,stdin,Java,Io,Stdin,我想在的中从stdin获取输入 3 10 20 30 第一个数字是第二行中的数字量。这是我得到的,但它被困在while循环中。。。所以我相信。我在调试模式下运行,数组没有得到任何赋值 import java.util.*; public class Tester { public static void main (String[] args) { int testNum; int[] testCases; Scanner i

我想在的中从stdin获取输入

3
10 20 30
第一个数字是第二行中的数字量。这是我得到的,但它被困在while循环中。。。所以我相信。我在调试模式下运行,数组没有得到任何赋值

import java.util.*;

public class Tester {   

   public static void main (String[] args)
   {

       int testNum;
       int[] testCases;

       Scanner in = new Scanner(System.in);

       System.out.println("Enter test number");
       testNum = in.nextInt();

       testCases = new int[testNum];

       int i = 0;

       while(in.hasNextInt()) {
           testCases[i] = in.nextInt();
           i++;
       }

       for(Integer t : testCases) {
           if(t != null)
               System.out.println(t.toString());               
       }

   } 

} 

这与环境有关

in.hasNextInt()
它让您保持循环,然后在三次迭代后,“i”值等于4,testCases[4]抛出ArrayIndexOutOfBoundException

解决办法可能是

for (int i = 0; i < testNum; i++) {
 *//do something*
}
for(int i=0;i
更新您的while以仅读取所需的数字,如下所示:

      while(i < testNum && in.hasNextInt()) {
while(i

while
中添加的附加条件
&&i
将在您读取与数组大小相等的数字后停止读取数字,否则它将变得不确定,并且当数字数组
测试用例
已满时,您将获得
ArrayIndexOutOfBoundException
testNum
numbers.

谢谢..出于某种原因,它可以与for循环一起工作;但是它不能与while循环一起工作..即使在添加了条件之后为什么它可以与for循环一起工作,但是我尝试了你的方法,但它不起作用,奇怪的是,当我在每次迭代中更新'I'变量时,它应该起作用h hasNextInt()方法保持循环或等待下一个整数。@miatech这很愚蠢。我们需要将
i
作为第一个条件,并将
放在.hasNextInt()中作为第二个条件。我更新了答案,它工作得很好。在.hasNextInt()中,前面的
正在等待另一个输入,然后再去评估条件。请尝试让我知道。