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

  • Please post your code in text next time. – AxelH Aug 17 '18 at 08:20
  • [Never post pictures of text when you can post the actual text. Be sure that it is properly formatted and readable.](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-on-so-when-asking-a-question) –  Sep 21 '18 at 18:14

2 Answers2

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);
    }
}
JohanLarsson
  • 195
  • 1
  • 7
  • 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 – Curious_guy1111 Aug 17 '18 at 07:14
  • 1
    You made ArrayList and LinkedList handle Objects, so I made the variable into an Object. Maybe use Strings throughout the code instead. – JohanLarsson Aug 17 '18 at 07:23
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);
}
Ali
  • 117
  • 9