Scanner NoSuchElementException when calling .next() method

后端 未结 3 964
余生分开走
余生分开走 2021-01-16 18:50

In Java, I\'m getting this Exception:

Exception in thread \"main\" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at          


        
3条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-16 19:21

    You are calling .next() twice on every iteration of the loop, so when you are near the end, you jump off the end of the list and the compilter tells you there is nothing there.

    Instead of this:

    for(int counter = 0 ; counter < file.next().length(); counter ++) {
        System.out.println(`file.next()`.charAt(counter));    
    }
    

    Do this instead:

    String temp = file.next();
    for(int counter = 0 ; counter < next.length(); counter ++) {
        System.out.println(temp .charAt(counter));    
    }  
    

    SEE HERE

提交回复
热议问题