1

sorry if my formatting is garbage. I'm trying to add 2 strings and a boolean to an arrayList doing the following.

while((in.hasNextLine())){
    list.add(new Task(in.next(),in.next(), in.hasNextBoolean()));
    }

I keep getting a no such element exception. If I take the while loop away like so

list.add(new Task(in.next(),in.next(), in.hasNextBoolean()));

It functions fine but I can only add the first line of the text file. Is there something wrong in the loop or with the Scanner?

try {
        in = new Scanner(f1);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    while((in.hasNextLine())){
    list.add(new Task(in.next(),in.next(), in.hasNextBoolean()));
    }

f1 is declared as File f1 = new File ("src/mylist.txt");

Any help would be great! Thanks!

4
  • in.next(),in.next(), in.hasNextBoolean() What do you think with this? Commented Apr 14, 2016 at 4:45
  • Sorry I don't quite understand what you're asking. Commented Apr 14, 2016 at 4:51
  • 1
    hasNextBoolean() does not consume the boolean value. --- Also, after the last next() (or nextBoolean()) call, the "cursor" is still at the end of the line, so if your last line ends with a newline, hasNextLine() will return true, even though there are no more elements. --- Using Scanner to read lines of 3 values like that is very error-prone. Suggest using BufferedReader, readLine() and split(), for more controlled parsing. Commented Apr 14, 2016 at 4:52
  • Okay thanks I'll try a few of those methods and see if I can get anywhere with it. Commented Apr 14, 2016 at 4:56

1 Answer 1

1

NoSuchElementException exception is throwed by in.next(), in list.add(new Task(in.next(),in.next(), in.hasNextBoolean())),.

and for in.next(), if you don't use any Pattern in Scanner to match the next token. it will use default Pattern private static Pattern FIND_ANY_PATTERN = Pattern.compile("(?s).*") to match whole line. it will cause in.next() will read whole line.

so list.add(new Task(in.next(),in.next(), in.hasNextBoolean())) will throw NoSuchElementException, you have read twice but you only check once.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.