Scanner NoSuchElementException when calling .next() method

后端 未结 3 934
余生分开走
余生分开走 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:25

    The Scanner.next() method will move the internal iterator along one. Your code should be:

    public static void readFile(String path) {
        Scanner file = null;
        try {
            file = new Scanner(new File (path));
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            while (file.hasNext()) {
                String next = file.next();
                for(int counter = 0 ; counter < next.length(); counter ++) {
                    System.out.println(next.charAt(counter));    
                }
            }
        }
    }
    

提交回复
热议问题