首页 > 解决方案 > 扫描仪 noSuchElementException。它的原因是什么?我该如何解决?

问题描述

            Scanner newName = new Scanner(System.in);  //creating scanner object
            System.out.println("Δωστε ονομα : ");
            String getOnoma = newName.nextLine(); /*throws no such element exception at String getOnoma=newName.nextLine*/
            newName.close();

我不知道如何修复异常,我想这是我第一次在 Java 中使用扫描仪

标签: javaexceptionnosuchelementexception

解决方案


您正在调用 nextLine() 并且当没有行时它会抛出异常,正如javadoc所描述的那样。它永远不会返回 null

使用支票

if(newName.hasNextLine()) {
  String getOnoma = newName.nextLine();
}

无论出于何种原因,如果 Scanner 类遇到无法读取的特殊字符,它也会发出同样的异常。除了在每次调用 nextLine() 之前使用 hasNextLine() 方法之外,请确保将正确的编码传递给 Scanner 构造函数,例如:

Scanner scanner = new Scanner(new FileInputStream(filePath), "UTF-8");

推荐阅读