You have a good way to solve this. The problem is that you do not actually check every letter, so you need to do checks inside the for loop or you will only check the last letter. But then you cannot print βYESβ, because you want to print it only if all the letters are βyesβ, so you can use a boolean to check this as such:
boolean isMatch = true; for (int counter = 0; counter < strLength && isMatch; counter++) { letter = word.charAt(counter); if (letter != 'I' && letter != 'O' && letter != 'S' && letter != 'H' && letter != 'Z' && letter != 'X' && letter != 'N') { System.out.print("NO"); isMatch = false; } } if (isMatch) { System.out.print("YES"); }
But, as others have pointed out, using a regex is more efficient (and it has a working regex for whatever you want. An asterisk means zero or more of what is inside the brackets.):
if (word.matches("[HIOSX]*")) { System.out.print("YES"); } else { System.out.print("NO"); }
ddmps
source share