[英]Stdin reading multiple lines
I have the following code: 我有以下代码:
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
String submittedString = "";
System.out.flush();
submittedString = stdin.readLine();
int numberofLines = Integer.parseInt(submittedString.split(" ")[0]);
for(int i = 0; i < numberofLines; i++)
submittedString += stdin.readLine();
zipfpuzzle mySolver = new zipfpuzzle();
mySolver.getTopSongs(submittedString);
However, despite the input being over multiple lines, this only reads the first. 但是,尽管输入跨越多行,但这仅读取第一行。
Where is my mistake? 我的错误在哪里?
If it makes any difference, I am compiling on eclipse. 如果有什么不同,我正在eclipse上编译。
Cheers! 干杯! Dario 达里奥
Just use an array and populate it within your for-loop: 只需使用数组并将其填充到您的for循环中即可:
String[] inputs = new String[numberofLines];
for (int i = 0; i < numberofLines; i++)
inputs[i] = stdin.readLine();
Extra Note: 特别提示:
If you want multiple lines with single String: 如果要使用单个String多行:
String submittedString = "";
for (int i = 0; i < numberofLines; i++)
submittedString += stdin.readLine() + System.getProperty("line.separator");
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
String line = "";
while ((line = stdin.readLine()) != null){
// Do something.
submittedString += line + '\n';
}
submittedString = stdin.readLine();
BufferedReaders readLine method will read System.in until it hits a new line, therefore if you're using the first line of the file to determine the number of lines to read then your data must be incorrect. BufferedReaders的readLine方法将读取System.in,直到遇到新的一行为止,因此,如果您使用文件的第一行来确定要读取的行数,则您的数据必须不正确。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.