Caleigh O'Brien :
Here is some code that works, but looks inelegant. What is a better way to search for any occurrence of these strings inside another string?
String AndyDaltonInjury = "broken right thumb";
if (AndyDaltonInjury.toLowerCase().contains("broken") &&
(AndyDaltonInjury.toLowerCase().contains("knee") ||
AndyDaltonInjury.toLowerCase().contains("leg") ||
AndyDaltonInjury.toLowerCase().contains("ankle") ||
AndyDaltonInjury.toLowerCase().contains("thumb") ||
AndyDaltonInjury.toLowerCase().contains("wrist")))
{
System.out.println("Marvin sends in the backup quarterback.");
}
Nikolas :
Use the Set
collection and its method Set::contains
insde streaming the split array with the space (" "
) delimiter:
Set<String> set = new HashSet<>(Arrays.asList("knee", "leg", "ankle", "thumb", "wrist"));
String lower = "broken right thumb".toLowerCase();
String split[] = lower.split(" ");
if (lower.contains("broken") && Arrays.stream(split).anyMatch(set::contains)) {
System.out.println("Marvin sends in the backup quarterback.");
}
Moreover, I highly recommend you to use lower-cased variable names.