check if array is just one letter

Najib Razak :

I want to check if the input is only 1 letter or more than 1, below is my code

public ResponseEntity<String> moReceiver(@RequestParam("data")String data)
String[]subKeyword=data.split(" ");
String subKwd=subKeyword[1];
    if(subKwd =="")
    {
     System.out.println("One letter"); 
    }
    else
    {
     System.out.println("More than One letter"); 
    }

tried to use

==""

but doesnt work.. :( ,and got this error --->Index 1 out of bounds for length 1

TheWhiteRabbit :

Array indexes are zero-based and string comparison should be done using 'equals'.

String subKwd = subKeyword[0];
if(subKwd.equals("")){
  System.out.println("Zero letters");
}

Or you could also check the size of the string:

if(subKwd.length() == 0){
  System.out.println("Zero letters");
} else if(subKwd.length() == 1){
  System.out.println("One letter");
} else {
  System.out.println("More letters");
}

If your rely on the fact that your keyword is indeed the second 'field' in your data you'll need to add an additional check to see if your data indeed contains at least 2 fields:

String[] subKeyword = data.split(" ");
if(subKeyword.length > 1){
  String subKwd = subKeyword[1];
  if(subKwd.length() == 0){
    System.out.println("Zero letters");
  } else if(subKwd.length() == 1){
    System.out.println("One letter");
  } else {
    System.out.println("More letters");
  }
} else {
  System.out.println("No subkeyword present in data");
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325665&siteId=1