java - 为什么我不能在 try/catch 中输入多个输入?
问题描述
我在尝试在 try/catch 语句中的 do-while 循环中获取多个输入时遇到了困难:
FileOutputStream file;
PrintStream pen;
String name;
char exitInput;
try {
file = new FileOutputStream("names.txt");
pen = new PrintStream(file);
do {
System.out.print("Enter a name: ");
name = input.nextLine();
pen.print(name + "\n");
System.out.println("Would you like to enter more names?");
System.out.print("Option(y/n): ");
exitInput = input.next().charAt(0);
} while(exitInput != 'n');
pen.close();
} catch(IOException exc) {
System.out.println("<INPUT ERROR>");
}
当我运行这段代码时,它会问我一个名字,然后问我是否要输入更多的名字。如果我选择是,那么它只会跳过“name = input.nextLine();” 行和显示:
Enter a name: Would you like to enter more names?
Option(y/n):
键入两个“name = input.nextLine();”时问题似乎得到解决,但是,这不是一个很好的解决方案。
解决方案
input.next()
只消耗一个令牌,而不是整行。当您调用input.nextLine()
它时,会消耗该行的其余部分。
修复该替换input.next()
为input.nextLine()
.
推荐阅读
- javascript - Hidden elements reappears when another function is called
- java - 如何在 Polybius 密码中打印字母的特定坐标?
- python - Coinmarketcap 数据嵌套字典
- python - PySide2 QThread 正在冻结 UI
- python - 在两个数据帧之间进行推断(舍入问题)
- python - 结合年、月、周数和迄今为止的日期
- swift - 我的 swift 框架中是否需要“frameworkName.h”标头?
- c++ - 将 quickfix c++ 交叉编译到 arm 架构中时出错
- delphi-7 - 如何使用 OleVariant 在方法中发送字节数组
- java - Spring Java Format + IntelliJ + 链式方法调用包装