-1

I have the following text:

My name is Omer
//new line
I want to start my own personal project and achieve a lot with it
//new line
//new line
I also have problems that I encounter along the way but I know I will overcome them
//new line
Good
Bye
//new line
Bye

So that was the example above, I also want to use a BufferedReader. Let's say my BufferedReader is called br. Using br.readLine(), I can read lines from the console(I will input every single letter, I also use an InputStreamerReader)

If I do for example:

String line;
do {
line = br.readLine();
} while(line.lenght != 0)

It will stop after I enter a new line.

How can I read that text correctly? (I think that this is the first question that I ask here, sorry for any mistakes that I have maybe made)

JobHunter69
  • 1,706
  • 5
  • 25
  • 49
Esmer Omer
  • 65
  • 5

3 Answers3

1

You can use:

String line;
while((line=br.readLine())!=null) {
    // your code here..
}

Note: don't do do-while, use while. Your input may be empty from the beginning, and you don't want to have a Null Pointer Exception.

Giorgi Tsiklauri
  • 9,715
  • 8
  • 45
  • 66
0

just use readlines as readline just reads one line and return

String line;
do {
line = br.readLines();
} while(line.lenght != 0)
0

BufferedReader#readLine returns null when there is nothing left to read, so the following will work:

while((line=br.readLine())!=null){
    //do something with line
}

Files.lines or Files.readAllLines can be used to simplify this.


If you are reading input from the console, you can enter a string like "exit" to indicate that the program should stop reading.

while(!(line=br.readLine()).equalsIgnoreCase("exit")){
    //do something with line
}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • returns null when there is nothing left to read -> Alright, but how can I stop reading after I entered my text? It keeps asking me to input more and more endlessly :D – Esmer Omer Jul 31 '20 at 13:56