3

I have a dilemma I am trying to find out the best way to compare a string variable called (code) to an array of strings. if it equal it i want it to break the for loop. Which would should I select. I think the 2nd one will work but the 1st one seems like it would and its simpler. Any advice would be appreciated.

String[] badcodes = {"8QQ", "8BQ", "8JQ"};
if (code.equals(badcodes)) {
 break;
}
String[] badcodess = {"8QQ", "8BQ", "8JQ"};
for (String s : badcodess) {
 if (s.equals(code)) {
 break; // break out of for loop
 }
}

--------------based on answer ----------------------

String[] badcodes = {"8QQ", "8BQ", "8JQ"};
boolean check = Arrays.asList(badcodess).contains(code);
if (check = true) {
 // do something
} else {
 // do something
}
asked Mar 14, 2018 at 16:33
3
  • You mean, if any of the strings in the array equals the value of code? Commented Mar 14, 2018 at 16:35
  • "compare a string variable called (code) to an array of strings" A String will never be equal to a String[] Commented Mar 14, 2018 at 16:35
  • Yes that is correct thanks Commented Mar 14, 2018 at 16:38

2 Answers 2

2

You can convert your array to a List then use List::contains to check if the list contain the code or not :

boolean check = Arrays.asList(badcodess).contains(code);
answered Mar 14, 2018 at 16:35
5
  • I wrote some code above I want to use an if statement, would that work ? since check in boolean i am checking if it is true or not correct? Commented Mar 14, 2018 at 16:48
  • @Jonathan you can just use if (check){//do something}else{//do something else} no need to use check = true this is an assignment and not comparing, to check if a check equals to true or not you need to use double equal Commented Mar 14, 2018 at 16:49
  • so your saying I dont have to write check = true ? Commented Mar 14, 2018 at 16:51
  • exactly just use if(check) it equivalent to if(check == true) Commented Mar 14, 2018 at 16:51
  • 1
    OKAY I see if it contain the code do this if not do this check = true is not needed because if it equals true your going to do something anyway... I see i got it Commented Mar 14, 2018 at 16:53
2

Your first option would not do what you expect to do. And even if someArray.equals(anotherArray) would do an element-wise comparison (which it doesn't) - you would need to have the special array contain all objects of the existing array, in the exact same order. In that sense: first understand why this approach is flawed in many ways, to then drop it.

The second option is fine, but if you really want to "improve" the whole thing - use ArrayList instead - which has a contains() method.

answered Mar 14, 2018 at 16:35
0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.