1

My program should accept file input of any data type and display it. However after reading the 7th element, I get the error "NoSuchElementException"

This is my code:

THis is my code

2

2 Answers 2

9

In the while loop you are doing two "in.next()" in a row without checking "in.hasNext()"

You should store the in.next() in a variable and then add that variable to ArrayType and LinkType.

while(in.hasNext()) {
    Object o = in.next();
    ArrayType.add(o);
    LinkType.add(o);
}

Based on your comment, if you just want to print it out to see that everything else is working, use this:

public static void main(String[] args) throws IOException {
    List<String> lines = Files.readAllLines(Paths.get(("input.txt")));
    for (String line : lines) {
        System.out.println(line);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I've modified as suggested. However, now after the while loop, when I try to print the ArrayType, nothing is displaying Also, after a few seconds, I am getting the OutOfMemoryException now
You made ArrayList and LinkedList handle Objects, so I made the variable into an Object. Maybe use Strings throughout the code instead.
1

I think you are trying to do this:

public static void main(String[] args) throws FileNotFoundException {
    Scanner in = new Scanner(new FileReader("input.text"));
    List<String> arrayType = new ArrayList<>(100);
    List<String> linkedType = new LinkedList<>();
    while (in.hasNext()){
        String line = in.next();
        arrayType.add(line);
        linkedType.add(line);
    }
    System.out.println(arrayType);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.