求问这个简短的java程序我哪里错了??

2025-03-13 09:46:16
推荐回答(3个)
回答1:

  1. 死循环了

  2. 方法里套方法了

回答2:

while条件一直成立,后面代码没有执行的可能,你写了就会报错的

回答3:

看我理解的对不对,感觉是你的Scanner 这个应该放最上面。

public static void main(String[] args) {
    int[] arr = {20, 10, 15, 30};
    Scanner scanner = new Scanner(System.in);
    while (true) {
        while (scanner.hasNext()) {
            String s = scanner.nextLine();
            int i = Integer.parseInt(s);
            if (i >= arr.length) {
                System.out.println("超出数组长度!");
                continue;
            }
            System.out.println(arr[i]);
        }
        try {
            TimeUnit.MICROSECONDS.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}