Search code examples
javajava.util.scannernosuchelementexception

NoSuchElementException on Scanner, how do i get rid of it?


Scanner s = new Scanner(new File(filename));
        while (s.hasNext()) 
        {
            if(s.next().contains(","))
            {
                String str= s.next().replaceAll("[^a-zA-Z0-9]", "");
                List<String> brokenSentence = Arrays.asList(str.split(","));
                writer.write(brokenSentence +"\n");
            }
            else
            {
                String edited = s.next().replaceAll("[^a-zA-Z0-9]", "");//error  
                writer.write(edited +"\n");
            }
        }
        s.close();

The line with error works perfectly without the if above,I really need that part. Please help me. The error is:

Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1478)
at Programming_2021/free_time.Gutenburg2.main(Gutenburg2.java:67)

Solution

  • Don't invoke s.next() twice, but assign the result of the first call to a variable:

    while (s.hasNext()) {
        String value = s.next();
            
        if(value.contains(",")) {
            String str = value.replaceAll("[^a-zA-Z0-9]", "");
            List<String> brokenSentence = Arrays.asList(str.split(","));
            writer.write(brokenSentence +"\n");
        } else {
            String edited = value.replaceAll("[^a-zA-Z0-9]", "");
            writer.write(edited +"\n");
        }
    }
    

    Continuously calling s.next() will keep consuming values from the scanner. Those values are not necessarily there because you have only checked for the presence of one value using s.hasNext().