-1

When I try to use java scanner it works and in my list I get all the text file content as a list. But when I try to print within the while loop, it throws java.util.NoSuchElementException: No line found exception at the last line. Why would that be the case, wouldn't mylist also thrown had it been out of bound?

try {
        Scanner myscanner = new Scanner(new FileReader(myfilepath));
        while(myscanner.hasNextLine()){
            //System.out.println(myscanner.nextLine() );
            mylist.add(myscanner.nextLine()); 
            numline += 1;
        }
        myscanner.close();
    }
    catch (Exception ex) {
           ex.printStackTrace();
        }
echo
  • 547
  • 7
  • 18

2 Answers2

2

You check that you have next line and then when you print you read 2 lines.

You should change it to:

String line = myscanner.nextLine();
// print and add to list using line variable
Oleg
  • 5,726
  • 2
  • 20
  • 38
0

To avoid that you should create variable to store the result fo myscanner.nextLine() then print it and add it to the list. e.g

 while(myscanner.hasNextLine()){
        String temp = myscanner.nextLine();
        System.out.println(temp);
        mylist.add(temp); 
        numline += 1;
    }
magician
  • 377
  • 3
  • 7