提问人:Sereseli97 提问时间:10/3/2020 更新时间:10/3/2020 访问量:56
为什么我不能在 try/catch 中输入多个输入?[复制]
Why can't I type multiple inputs inside try/catch? [duplicate]
问:
我在尝试在 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>");
}
当我运行此代码时,它会询问我一个名称,然后询问我是否要输入更多名称。如果我选择YES,那么它只是跳过“name = input.nextLine();”行并显示:
Enter a name: Would you like to enter more names?
Option(y/n):
键入两个“name = input.nextLine();”时,问题似乎可以解决,但是,这不是一个很好的解决方案。
答:
-1赞
talex
10/3/2020
#1
input.next()
只使用一个令牌,而不是整行。当您调用它时,请使用该行的其余部分。input.nextLine()
要解决此问题,请替换为 。input.next()
input.nextLine()
评论
while(exitInput != 'n')
字符串不能这样比较。stackoverflow.com/questions/513832/......