Namit Namit - 1 year ago 99
Java Question

Using readline() and split()

The code below is mostly self explanatory. However, I am having trouble in two cases:

  1. The
    loop does not exit even with the command line is left blank.

  2. If the input is
    test t1
    variable is supposed to be "test" (using
    ) does that, but, it still doesn't enter the
    condition for some reason.

    String[] broken_text = null; String text = "";
    BufferedReader reader = new BufferedReader(new InputStreamReader(;
    while((text = reader.readLine()) != null) {
    broken_text = text.split(" ");
    String first_key = broken_text[0];
    if (first_key == "test") {
    //some statements

I am not sure why this is happening, any help regarding the same will be much appreciated.

Answer Source

use equals() to check string equality.

if (first_key == "test") {
         //some statements

should be

if (first_key.equals("test")) {
         //some statements

your text will never be null because you declared it as

String text = "";

thus your while loop would be an infinite loop


String text = ""; 
String text = null;

or if you wanna leave your text="" string as empty string.


while(!(text = reader.readLine()).isEmpty()) 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download