Thiago
Thiago

Reputation: 13302

Android if statement - if a string contains any of the strings from an array

Can you give me a hand please.

I need to do a check, to check if the userCode matches any code in my string array or if the oldUser code also matches any code from the array

String[] code = {"1111", "2222", "3333", "4444", "5555"};

String userCode;
String oldUser;

if (userCode.equals(code) || oldUser.equals(code)) {

RUN 

} else { die }

thanks

Upvotes: 0

Views: 2579

Answers (4)

113408
113408

Reputation: 3444

To achieve a simple verification you can loop through your array OR Easy way to do it

List< String > code = Arrays.asList( new String[] { "1111", "2222", "3333", "4444", "5555" } );

String userCode;
String oldUser;

if (code.contains(userCode) || code.contains(oldUser)) {

 //doStuff() 

} else { 
    return; 
}

Upvotes: 4

Renato Probst
Renato Probst

Reputation: 6054

Use a foreach with a boolean var

boolean isTheSame;
For(String myArrayCodes; code;) {
  if (userCode.equals(myArrayCodes) || oldUser.equals(myArrayCodes))
    isTheSame = true;
  break;
  }
}

if (isTheSame) { // usercode or oldUser is on array
 doSomething();
}
else {
}

Upvotes: -1

Wundwin Born
Wundwin Born

Reputation: 3475

Loop the array and check each entry with your user values

 String[] code = {"1111", "2222", "3333", "4444", "5555"};

 for (int i = 0; i < code.length; i++) {
     if (userCode.equals(code[i]) || oldUser.equals(code[i])) {
          //do
     }
 }

Or using Arrays.asList(),

List<String> codes = Arrays.asList("1111", "2222", "3333", "4444", "5555");

if (codes.contains(userCode) || codes.contains(oldUser)) {
          //do
}

Upvotes: 0

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136022

try this

boolean contains = Arrays.asList(arr).contains(str);

Upvotes: 1

Related Questions