java.util.Scanner跳转输入请求 [英] java.util.Scanner jumps over input requests

查看:126
本文介绍了java.util.Scanner跳转输入请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 java.util.Scanner 接收输入:

I am trying to receive input using java.util.Scanner:

Scanner scanner = new Scanner(System.in);
int bla = scanner.nextInt();
String blubb = scanner.nextLine();

但是 nextLine()命令才会得到跳过并返回一个空字符串。我该如何解决这个问题?

But the nextLine() command just gets skipped and an empty string is returned. How can I solve this problem?

推荐答案

nextInt 方法没有消耗整数后面的新行字符,所以当你调用 nextLine 时,它只是在整数后面读取新行字符。

The nextInt method does not consume the new line character after the integer so when you call nextLine it just reads the new line character immediately following the integer.

示例

如果您有此输入:

42\n
foo\n

readInt 来电消耗 42 但不是新行字符:

The readInt call consumes the 42 but not the new line character:

\n
foo\n

现在,当您调用 readLine 时,它将消耗第一行的其余部分,该行仅包含换行符。

Now when you call readLine it consumes the rest of the first line, which contains only the new line character.

解决方案

尝试在整数后丢弃剩下的行:

Try discarding the rest of the line after the integer:

int bla = scanner.nextInt();
scanner.nextLine(); // Discard the rest of the line.
String blubb = scanner.nextLine();

或者始终使用 nextLine 来读取每一行然后自己将字符串解析为整数:

Or use nextLine consistently to read each line and then parsing the string to an integer yourself:

String blaString = scanner.nextLine();
int bla = Integer.valueOf(blaString);
String blubb = scanner.nextLine();

这篇关于java.util.Scanner跳转输入请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆