简体   繁体   中英

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.

Cheers! Dario

Just use an array and populate it within your for-loop:

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 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM