Walter Medly
Walter Medly

Reputation: 63

How do I fix a NoSuchElementException from a input file?

I was wondering if anyone could help solve this NoSuchElements exception in my program which scans a text very large text and then is added to the ArrayList.

I have tried re-arranging the order of the code to see if that would fix it but now I don't know how to fix it.


Exception itself:

Exception in thread "main" java.util.NoSuchElementException
    at java.base/java.util.Scanner.throwFor(Scanner.java:937)
    at java.base/java.util.Scanner.next(Scanner.java:1478)
    at mainTest.main(mainTest.java:11)

mainTest class:

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

public class mainTest {
    public static void main(String args[]) throws FileNotFoundException {
        ArrayList<String> bigBoi = new ArrayList<>(500000);

        Scanner scan1 = new Scanner(new File("LargeDataSet.txt"));

        while (scan1.hasNextLine()) {
            scan1.next();
            String data = scan1.next() + " " + scan1.next();
            bigBoi.add(data);
        }

        ArrayList<String> successful = new ArrayList<>(500000);
       }
    }

The unit of a .txt file : https://drive.google.com/file/d/1MWfMKMhSvuopOt9WwquABgYBTt0M4eLA/view?usp=sharing

(sorry for needing you to download it from a google drive, the file is so long I probably would've been reported or something if I had pasted 500,000 lines)

Upvotes: 0

Views: 1133

Answers (2)

MartinBG
MartinBG

Reputation: 1648

There is an empty line at the end of LargeDataSet.txt which is valid for scan1.hasNextLine() check, but the scan1.next() throws NoSuchElementException as there's nothing to read.

Changing validation to scan1.hasNext() as suggested in the accepted answer, solves that problem, but the program could still crash if there are less than 3 entries on any line and accepts lines with more than 3 entries.

A better practice is to validate all externally supplied data:

while (scan1.hasNextLine()) {
    String line = scan1.nextLine();
    String[] tokens = line.split("\\s+"); //split by space(s)
    if(tokens.length != 3) { //expect exactly 3 elements on each line
        throw new IllegalArgumentException("Invalid line: " + line);
    }
    bigBoi.add(tokens[1] + " " + tokens[2]);
}

Upvotes: 0

Anuradha
Anuradha

Reputation: 580

Please check with scan1.hasNext() instead of scan1.hasNextLine():

while (scan1.hasNext()) {
        scan1.next();
        String data = scan1.next() + " " + scan1.next();
        bigBoi.add(data);
}

Upvotes: 1

Related Questions