简体   繁体   中英

how to read multiple lines as input at the same time in java

I want to input a paragraph (multiple lines) at the same time (not one line by one line) in Java. I want to add "the line number is :" to each line I input in command prompt, and exit it when the input is null. The code below is my attempt.

I tried to research on Internet, but I am still confused with Scanner and BufferedReader.

How do I adjust my program?

import java.io.*;

public class Word {

    public static void main(String[] args) throws IOException{
        InputStreamReader is = new InputStreamReader(System.in);
        BufferedReader input=new BufferedReader(is);
        String s=input.readLine();
        int lineNum=1;
        while(s!=null&&s.length()>0) {

            System.out.println("Line number "+lineNum+" : "+s);
            lineNum++;

        }
    }
}

In your code you cast the user input to variable "s" once before the loop. In the loop "s" never changes so there's no exit condition, and it will always print the exact same line. You have to put the line String s=input.readLine(); in the loop, so each time it will read a new line from the user.

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