0

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

2
  • 1
    Arrays.binarySearch(code, userCode) == 0 if you want speed in searching the array. Commented Aug 25, 2014 at 3:36
  • @Rod_Algonquin You also must ensure the array is sorted before you can use Arrays.binarySearch Commented Aug 25, 2014 at 3:42

4 Answers 4

4

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; 
}
Sign up to request clarification or add additional context in comments.

2 Comments

I would suggest changing String[] code to List< String > code = Arrays.asList( new String[] { ... } ); To avoid recreating a new List object twice in the if statement.
Yes that could be a nice optimization
1

try this

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

Comments

0

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
}

Comments

-1

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 {
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.