java - 扫描仪 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 中使用扫描仪
解决方案
您正在调用 nextLine() 并且当没有行时它会抛出异常,正如javadoc所描述的那样。它永远不会返回 null
使用支票
if(newName.hasNextLine()) {
String getOnoma = newName.nextLine();
}
无论出于何种原因,如果 Scanner 类遇到无法读取的特殊字符,它也会发出同样的异常。除了在每次调用 nextLine() 之前使用 hasNextLine() 方法之外,请确保将正确的编码传递给 Scanner 构造函数,例如:
Scanner scanner = new Scanner(new FileInputStream(filePath), "UTF-8");
推荐阅读
- amazon-web-services - 当我对等不同区域的两个 VPC 时,流量是否会通过公共 Internet?
- python - 如何将视频(例如缩放通话)裁剪成多个文件?
- javascript - .forEach(...) 在获取时未定义
- html - 使用输入删除 mat-form-field 的边框(也用于悬停和焦点)
- javascript - 带有条件输出/应用的 Javascript 数组过滤器
- java - 在 java 程序中使用来自 hub.KerasLayer 和 python 和 tensorflow 2.1.0 的模型时,“图中没有名为 [input] 的操作”
- dataframe - 如何识别列pysapk中的第一条记录
- ios - Swift 5:更改 REST API 查询的 url,在 UILabel 中显示响应
- python - 了解 PyTorch LSTM 的输入形状
- javascript - Highcharts 更新功能无法正常工作