I am writing code for an assignment an it must follow these guidelines: /* returns true if s consists only of letters that * are also Roman numerals */
I have written code that looks like this:
if (!s.contains("I") || !s.contains("V") || !s.contains("X") ||
!s.contains("L") || !s.contains("C") || !s.contains("D") || !s.contains("M")
|| !s.contains("i") || !s.contains("v") || !s.contains("x") ||
!s.contains("l") || !s.contains("c") || !s.contains("d") ||
!s.contains("m")) {
return false;
} else{
return true;
}
}
This looks like it would work but it does not. Help would be appreciated!
Put the characters into a list and check if that list contains the character your checking. This is way cleaner and better maintainable. Now just run the string into a forloop. If you find a character that is roman break and return false..otherwise return true.
public static boolean checkRomanNums(String s){
List<Character> romanNumerials=Arrays.asList('I','V','X','L','C','D','M');
for(int i=0;i<s.length();i++){
if(romanNumerials.contains(s.charAt(i))){
return false;
}
}
return true;
}
你应该使用类似return s.matches("(?i)[ivxlcdm]+");
public static boolean containsOnlyRomanNumerals(String s) {
return s.matches("[IVXLCDMivxlcdm]*");
}
This should do the trick. The regular expression checks if s
consists only of the characters in the square brackets.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.