爪哇InputStreamReader(System.in)–它没有读取最后一行
一直在努力解决这个问题。长话短说,它不读最后一行的my input。
我想要它做什么...读取文件并退出。
就是这样。它的工作原理上的罚款file ( example: .txt ),但是当涉及到System.in,代码并没有工作!烦人,当它应该很容易。
这是要重新创建的代码和照片!
StringBuilder strBuilder = new StringBuilder();
String line;
// for the last line to "end", I have to do n! ... but how...?
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while((line = br.readLine()) != null) {
System.out.println(line);
strBuilder.append(line);
}
// Does not reach code
System.out.println(strBuilder.toString());
我知道readLine()在终止n或r...在这种情况下,4 fourth line确实不具备后换行,所以我尝试使用!br.isEmpty()或!br.isBlank以“看”,有没有经过更多的行4 fourth line...但我想我失去了一些东西。
( copy and paste this info into the console without a line break after 4 fourth line )
1 first line
2 second line
3 third line
4 fourth line
你会得到这个
如果您按下控制台(因为您输入的是 "n" ),您将可以4 fourth line打印出来,ENTER但这不是我所期望的。
目前,它不会终止。它不会读取用户输入的最后一行。这将是一个循环。
请帮忙 :)
回答
readline() 将读取输入到换行符或文件结尾(以先到者为准)。
如果操作正确,即通过管道将文件输入到 Java 程序的标准输入中,它应该可以工作。像这样:cat myfile.txt | java MyClass或java MyClass < myfile.txt。如果您使用 aFileInputStream代替 ,它也将起作用System.in。
只有当您从控制台手动输入输入时才会出现问题。在这种情况下BufferedReader,无法知道您的输入何时完成,因此它会一直等到换行符或文件结束。在 Linux 中,您可以简单地按Ctrl-D要求控制台关闭 Java 程序的标准输入。
- @Flexer if hackerrank is sending you input and then not sending an end-of-stream line, then hackerrank is buggy and you should file a bug report. However, I rather doubt this. The code you pasted works fine in all situations except idiotic impossible ones, such as input that doesn't end in a newline and isn't closed - which is literally indistinguishable from a slow disk.
- The question here is *how do I know where the input ends*? You can try to simply read all the input character-by-character until end-of-file, collect them into one big string and then split it into separate lines.
THE END
二维码