扫描仪上的 NoSuchElementException,我该如何摆脱它?

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();

如果没有上面的if,有错误的行可以完美运行,我真的需要那部分。请帮我。错误是:

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)

不要调用s.next()两次,而是将第一次调用的结果赋给一个变量:

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");
    }
}

连续调用 s.next() 将继续使用扫描仪的值。这些值不一定存在,因为您仅使用 s.hasNext().

检查了一个值是否存在