gpt4 book ai didi

java - 从标准输入获取输入

转载 作者:搜寻专家 更新时间:2023-10-30 19:44:07 24 4
gpt4 key购买 nike

我想在 for 中从 stdin 获取输入

3
10 20 30

第一个数字是第二行中数字的数量。这是我得到的,但它卡在了 while 循环中……所以我相信。我在 Debug模式下运行,但数组未分配任何值...

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*
}

关于java - 从标准输入获取输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13095983/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com