0

我对这一切都很陌生,但我正在为德克萨斯计算机科学 UIL 活动练习,我正在解决练习问题,但我遇到了这个错误。

Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at bridge.bridge.main(bridge.java:28)

这是我的代码。老实说,除了看起来很糟糕之外,我不知道它有什么问题。

import java.util.*;
import java.io.*;

public class bridge {

public static void main(String[] args) throws IOException {
    Scanner input = new Scanner(new File("bridge.dat"));
    int convoys = input.nextInt();
    int vehicles;
    int weight = 0;
    int speed = 0;
    int speedholder;
    int checker = 0;
    boolean placeholder = true;
    for(int i = 0; i < convoys; i++){
        vehicles = input.nextInt();
        for(int y = 0; y < vehicles; y++) {
            if(!placeholder) {
                placeholder = true;
                weight += checker;
                speedholder = input.nextInt();
                if(speedholder < speed || speed == 0) {
                    speed = speedholder;
                }
            }
            else {
                checker = input.nextInt();
                if(weight + checker > 42) {
                    placeholder = false;
                }
                else {
                    weight += checker;
                    speedholder = input.nextInt();
                    if(speedholder < speed || speed == 0) {
                        speed = speedholder;
                    }
                }
            }
        }
        System.out.println(speed);
        speed = 0;
        weight = 0;
    }
    input.close();
}
}

它在给出错误之前打印出“5”。这是我的输入文件的样子:

2
8
10 10
5 25
40 5
35 15
12 23
30 20
42 25
8 30
10
42 10
23 30
40 5
2 10
1 20
4 30
6 28
28 3
17 8
35 10

任何帮助表示赞赏。我确实四处寻找类似的问题,但这似乎是一个更复杂的错误,因为我已经做过一些程序,但以前从未遇到过这个错误,但我也可能只是做了一些非常愚蠢的事情。

4

1 回答 1

1

当 aScanner抛出 aNoSuchElementException时,这意味着您在到达输入末尾后尝试从扫描仪中读取。

如果你想知道你是否在输入的末尾,你可以使用hasNextInt.

从那里去。

于 2015-01-27T01:13:11.243 回答