为什么nextLine()返回一个空字符串?
这可能是最简单的事情之一,但我没有看到我做错了什么。
我的输入包括一个带有数字的第一行(要读取的行数),带有数据的一串行和仅带有\ n的最后一行。 我应该处理这个输入,在最后一行之后,做一些工作。
我有这个输入:
5 test1 test2 test3 test4 test5 /*this is a \n*/
为了阅读输入,我有这个代码。
int numberRegisters; String line; Scanner readInput = new Scanner(System.in); numberRegisters = readInput.nextInt(); while (!(line = readInput.nextLine()).isEmpty()) { System.out.println(line + "<"); }
我的问题是为什么我不打印任何东西? 程序读取第一行,然后什么都不做。
nextInt
不读取以下换行符,因此第一个nextLine
( 返回当前行的其余部分 )将始终返回空字符串。
这应该工作:
numberRegisters = readInput.nextInt(); readInput.nextLine(); while (!(line = readInput.nextLine()).isEmpty()) { System.out.println(line + "<"); }
但我的建议是不要将nextLine
与nextInt
/ nextDouble
/ next
/等混合nextLine
,因为任何试图维护代码(包括你自己)的人都可能没有意识到或已经忘记了上述内容,所以可能会对上面的代码感到有些困惑。
所以我建议:
numberRegisters = Integer.parseInt(readInput.nextLine()); while (!(line = readInput.nextLine()).isEmpty()) { System.out.println(line + "<"); }
我想我之前看过这个问题。 我认为你需要添加另一个readInput.nextLine()
,否则你只是在5
的结尾和之后的\n
之间读取
int numberRegisters; String line; Scanner readInput = new Scanner(System.in); numberRegisters = readInput.nextInt(); readInput.nextLine(); while (!(line = readInput.nextLine()).isEmpty()) { System.out.println(line + "<"); }
实际上它并没有完全回答这个问题(为什么你的代码不起作用),但你可以使用下面的代码。
int n = Integer.parseInt(readInput.readLine()); for(int i = 0; i < n; ++i) { String line = readInput().readLine(); // use line here }
至于我,它更具可读性,甚至可以节省您的时间,在极少数情况下,当测试用例不正确时(在文件末尾有额外的信息)
顺便说一下,你似乎参加了一些编程竞赛。 请注意,扫描仪输入大量数据可能会很慢。 您可以考虑将BufferedReader
与可能的StringTokenizer
一起使用(此任务中不需要)