nextInt上的Java NoSuchElementException

时间:2015-01-27 01:07:30

标签: java nosuchelementexception

我对这一切都很陌生,但我正在为德克萨斯计算机科学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();
}
}

打印出&#34; 5&#34;在给出错误之前。以下是我的输入文件的样子:

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

感谢任何帮助。我确实环顾四周寻找类似的问题,但这似乎有点复杂的错误,因为我做了一些类似的程序,但之前从未遇到过这个错误,但我也可以做一些非常愚蠢的事情。

1 个答案:

答案 0 :(得分:1)

Scanner抛出NoSuchElementException时,表示您在输入结束后尝试从扫描仪中读取数据。

如果您想知道自己是否在输入的最后,可以使用hasNextInt

从那里开始。

相关问题