Greg Jones
Greg Jones

Reputation: 1

Java NoSuchElementException on nextInt

I'm fairly new to all this, but i'm practicing for a Texas Computer Science UIL event and i'm working on a practice problem, but i have run into this error.

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)

Here's my code. I honestly have no clue whats wrong with it besides being awful to look at.

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

it prints out "5" before giving the error. And heres what my input file looks like:

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

Any help is appreciated. I did look around for similar questions, but this seemed a bit more complex of an error, as i have done a few programs like but never got this error before, but i also could have just done something really stupid.

Upvotes: 0

Views: 1038

Answers (1)

tbodt
tbodt

Reputation: 17007

When a Scanner throws a NoSuchElementException, it means you're trying to read from the scanner after you reached the end of the input.

If you want to find out if you're at the end of the input, you can use hasNextInt.

Go from there.

Upvotes: 1

Related Questions