我可以检查字符串中特定字符以外的字符吗?

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

我正在编写一个 Java 程序,可以将输入的罗马数字转换为 Short,我希望它能够在输入除罗马数字以外的任何字母时识别并再次要求输入(I、V、X、L、C、D 和 M)。

有没有类似.contains()但功能相反的方法?
还是我必须用某种循环检查每个字母?

我建议你使用正则表达式来检查输入是否为罗马数字。你可以找到这个问题的正则表达式here。使用 String#matches() 确定您的输入是否与正则表达式匹配。

if(!input.matches("^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$")) { // input is the String the user entered
    // handle invalid input here
}

当然,您需要某种类型的过滤器来测试输入。

一个解决方案可能是使用包含输入中所有可能有效字符的字符串,然后 return 如果在过滤器中找不到字符则返回 false。

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"));
  }
}

只需测试有效字符,而不是有效序列,可以使用包含来完成:

boolean roman (String s) 
{
    for (char c: s.toCharArray()) 
        if (! "IVXCLDM".contains(""+c)) 
            return false; 
    return true; 
}

不过,我更喜欢正则表达式

boolean roman (String s) 
{
    return s.matches ("[IVXCLDM]+");
}

这意味着该集合中任意数量(+)的字符,至少一个。