Search code examples
javastring-comparisonroman-numerals

Can I check a String for characters other than specific ones?


I am writing a Java program that can convert an inputted Roman Numeral into a Short, and I want it to be able to recognize and ask for input again when any letter has been inputted besides a Roman Numeral (I, V, X, L, C, D, and M).

Is there a method similar to .contains(), but with the opposite function?
Or do I have to check each individual letter with some kind of loop?


Solution

  • Well of course, you need some type of filter to test against the input.

    One solution could be to use a string that contains all the possible valid characters in the input and then return false if a character wasn't found in the filter.

    public class HelloWorld
    {
      public static boolean filter(String test, String filter) {
        for(int i = 0; i < test.length(); i++) {
            if (filter.indexOf(test.charAt(i)) == -1) {
                return false;
            }
        }
        return true;
      }
      // arguments are passed using the text field below this editor
      public static void main(String[] args)
      {
        System.out.println(filter("XDQX", "XDQ"));
      }
    }