java - Java 扫描器实用程序仅在我的简单程序中工作一次
问题描述
我是 Java 和一般编码的新手,我无法让第二个扫描仪来处理我的简单程序。在程序中使用第二个扫描仪会给我以下错误:
线程“main”中的异常你感觉如何?java.util.NoSuchElementException:找不到行
这是我的代码:
import java.util.Scanner;
public class Part2 {
public static void main(String[] args) {
//This part asks the user how they are doing, and then it says hello to them
Scanner userName = new Scanner(System.in);
System.out.print("What is your name? ");
String name = userName.nextLine();
userName.close();
System.out.println("Hello "+name);
//This part asks the user how they are feeling, and then it says it is happy that they are feeling that way
Scanner userAttitude = new Scanner(System.in);
System.out.print("How are you feeling? ");
String attitude = userAttitude.nextLine();
userAttitude.close();
System.out.println("Glad to hear you are feeling "+attitude);
}
}
解决方案
不要关闭 System.in
当您关闭扫描仪时,它就是这样做的。
此外,无需在同一输入流上创建第二个 Scanner:使用第一个。
推荐阅读
- perl - perl:绘制两个单独的数组
- git - 从克隆的存储库本地恢复提交/在特定提交后重置所有更改
- intellij-idea - 取消注释已注释块内的较小块
- ios - 如何在 Swift 中解析特定的 JSON
- java - 在 Spring Integration 中将“application.errorChannel”添加到配置中
- c++ - Qt 5.11.2(Clang 8.0 (Apple),64 位),未找到 QJSEngine 文件
- unix - Unix awk - 每个唯一值的出现次数
- docker - 将 docker cli bash 命令转换为 api 以供外部应用程序在生产中使用的最安全方法
- mongoose - 猫鼬响应的对象属性未定义
- c - 未定义对函数文件错误 C 的引用(编译)