tags:

views:

508

answers:

5

Hi Geeks,

I dont know whats the wroing with the below code.... I am getting input from textbox and putting the input in a string. If the textbox is empty it will return a empty string. In the below code

   String[] str = new String[9]; 
   for(int i=0;i<9;i++){
       if(str[i].equals("")){
          System.out.println("set " + cmds[i] + " " + str[i]);
          WriteThread.sendCommand("set " + cmds[i] + " " + str[i] + "\n", false);
       }
    }

In the above code str[i] stores the input text of textboxes and I am trying to check if any element of array is empty.I also tried with str[i] == "" and str[i] == null. But no luck. The statement inside the if block if i am printing the string str[i], it shows nothing that means it is empty.

Am I doing anything wrong way? Can anybody please suggest?

+5  A: 

You could try :

if (str[i] == null || str[i].trim().equals("")){
// your code
}
fastcodejava
it worked for me.... Thanks a lot..
Surjya Narayana Padhi
A: 

The above code only executes if the string is empty, is that the desired behavior? Also declaring str as new right before the loop pretty much guarantees it will be empty.

If you are trying to assign the values from textboxes you will need to have those assignments somewhere before the loop.

GrayWizardx
+1  A: 

You can use the Apache Commons Lang to check a String:

if (StringUtils.isBlank(str[i]) {
    ...
}

StringUtils.isBlank is checking if the String is null or empty (i.e. if it is equals to "" when all blank characters are removed).

romaintaz
A: 

I actually tried to run your code snippet and got a NullPointerException on your conditional

str[i].equals("")

str[i] == null worked for me. Are you sure you put the right code in your question. It seems odd to be testing for an empty string of an empty array you just initialized.

algernon
A: 

thank you. that piece of code helped me too much :)

Emre