I have a String[] with values like so:
public static final String[] VALUES = new String[] {"AB","BC","CD","AE"}; Given String s, is there a good way of testing whether VALUES contains s?
You can implement a simple search along with a status value.
Here String s is your search value. I have hardcoded here but you can take it as a user input also.
String[] VALUES = new String[] {"AB","BC","CD","AE"}; String s="ABC"; boolean status =false; for(int i=0;i<VALUES.length;i++) { if(VALUES[i].equals(s)) { System.out.println("Element Found"); status=true; break; } } if(status==false) System.out.println("Element Not Found"); } You can check it by two methods
A) By converting the array into string and then check the required string by .contains method
String a = Arrays.toString(VALUES); System.out.println(a.contains("AB")); System.out.println(a.contains("BC")); System.out.println(a.contains("CD")); System.out.println(a.contains("AE")); B) This is a more efficent method
Scanner s = new Scanner(System.in); String u = s.next(); boolean d = true; for (int i = 0; i < VAL.length; i++) { if (VAL[i].equals(u) == d) System.out.println(VAL[i] + " " + u + VAL[i].equals(u)); }
indexOfandcontainsinjava.util.Arrays- which would both contain straightforward loops. Yes, you can write those in 1 minute; but I still went over to StackOverflow expecting to find them somewhere in the JDK.