扫描仪noSuchElementException。它的原因是什么?我该如何解决?

问题描述 投票:-1回答:1
            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中使用扫描程序

java exception nosuchelementexception
1个回答
0
投票

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

使用支票

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

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

Scanner scanner = new Scanner(new FileInputStream(filePath), "UTF-8");
© www.soinside.com 2019 - 2024. All rights reserved.