从标准输入获取输入

13

我希望以以下方式从标准输入获取输入:

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());               
       }

   } 

} 
2个回答

10

这与情况有关。

in.hasNextInt()

它允许您保持循环,然后在三次迭代后“i”值等于4,并且testCases [4]引发ArrayIndexOutOfBoundException。

解决此问题的方法可能是

for (int i = 0; i < testNum; i++) {
 *//do something*
}

谢谢。出于某种原因,它可以使用for循环工作;但是即使添加了条件,它也无法使用while循环工作。 - miatech

2
更新您的while循环,只读取所需数字,如下所示:
      while(i < testNum && in.hasNextInt()) {

while中添加的附加条件&& i < testNum将在读取与您的数组大小相等的数字后停止读取数字,否则它将无限期地进行,当数字数组testCases已满(即完成使用testNum个数字)时,您将获得ArrayIndexOutOfBoundException。请保留HTML标签。

1
为什么它在for循环中可以工作,但我尝试了您的方法,它却不起作用,奇怪的是,因为我每次迭代都更新了“i”变量。 - miatech
有关 hasNextInt() 方法的问题,它会一直循环或等待下一个整数... - miatech
1
@miatech 这是一个愚蠢的错误。我们需要把 i < testNum 放在第一条件,in.hasNextInt() 放在第二条件。我更新了答案,现在它完美地工作了。之前 in.hasNextInt() 在评估条件之前还在等待输入。请试一下并告诉我结果。 - Yogendra Singh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接