为什么我的 switch 语句有如此奇怪的行为?
采取以下用 Java 编写的代码:
choice = keyboard.nextByte();
switch (choice)
{
case (byte) 4:
System.out.print("Input the layout type: ");
layoutType = keyboard.nextLine();
System.out.print("Input the layout name: ");
layoutName = keyboard.nextLine();
break;
default:
break;
}
当我运行该程序时,我得到以下结果:
输入布局类型:输入布局名称:
我收到同时输入两个输入的提示!这是为什么?程序不应该停在“keyboard.nextLine()
”处吗?它在 switch
语句之外执行此操作,但不在其中执行此操作。为什么提示用户在 switch 语句内输入会导致这种奇怪的行为?
===================================== 更新:
是的,没错。 keyboard
是java.util.Scanner
类的实例。
Take the following code written in Java:
choice = keyboard.nextByte();
switch (choice)
{
case (byte) 4:
System.out.print("Input the layout type: ");
layoutType = keyboard.nextLine();
System.out.print("Input the layout name: ");
layoutName = keyboard.nextLine();
break;
default:
break;
}
When I run the program, I get the following:
Input the layout type: Input the layout name:
I get prompted for both inputs all at once! Why is that? Shouldn't the program stop at where it says "keyboard.nextLine()
"? It does that outside of the switch
statement but not while inside of it. Why does prompting the user for input inside of the switch
statement cause this weird behavior?
===================================
UPDATE:
Yes, that's right. keyboard
is an instance of the java.util.Scanner
class.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是因为您输入换行符是为了读取字节,并且换行符在某种程度上被视为后续调用
readLine()
的输入。在readByte()
之后添加一个虚拟readLine()
来解决这个问题:It is because you are inputting a newline in order to read the byte, and the newline is somehow considered input for the subsequent call to
readLine()
. Add a dummyreadLine()
afterreadByte()
to solve this:假设
keyboard
是java.util.Scanner
的一个对象,问题如下。首先,您使用
nextByte()
读取一个字节,因此仅将字节值作为输入。其余值,在您的情况下,换行符保留在输入流中。它由keyboard.nextLine()
作为输入读取并返回。因此该行返回一个空字符串。因此,您可能需要额外调用nextLine()
来丢弃该新行,如下所示:Assuming that
keyboard
is an object ofjava.util.Scanner
, the problem lies in the following.Firstly, you read a byte using
nextByte()
, thus only the byte value is taken as input. The remaining values, here in your case the newline character is remaining in the input stream. It is read by thekeyboard.nextLine()
as input and returned. So an empty string is returned by that line. So, you might want to put an extranextLine()
call to discard that new line as follows: