Namit Namit - 5 months ago 9
Java Question

Using readline() and split()

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


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

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

    String[] broken_text = null; String text = "";
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    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

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

change

String text = ""; 
to
String text = null;

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

use

while(!(text = reader.readLine()).isEmpty())