我正在尝试使用接收输入java.util.Scanner
:
Scanner scanner = new Scanner(System.in);
int bla = scanner.nextInt();
String blubb = scanner.nextLine();
But the nextLine()
命令只是被跳过并返回一个空字符串。我怎么解决这个问题?
The nextInt
方法不会消耗整数后面的新行字符,因此当您调用时nextLine
它只是读取紧跟在整数后面的换行符。
Example
如果您有此输入:
42\n
foo\n
The readInt
调用消耗42
但不是新行字符:
\n
foo\n
现在当你打电话时readLine
它消耗第一行的其余部分,其中仅包含新行字符。
Solution
尝试丢弃整数之后的行的其余部分:
int bla = scanner.nextInt();
scanner.nextLine(); // Discard the rest of the line.
String blubb = scanner.nextLine();
Or use nextLine
一致地读取每一行,然后自己将字符串解析为整数:
String blaString = scanner.nextLine();
int bla = Integer.valueOf(blaString);
String blubb = scanner.nextLine();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)