0

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++;

        }
    }
}

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.