I am working on a program that determines is a entered string is a roman numeral. my issue is that in the following code
public void romancheck(String num){
if(num.isEmpty()){
JOptionPane.showMessageDialog(null, "No number typed");
}
if (num.matches("[IVXLCDM]+")){
repeatefinder(num);
if(repeated == 'I' || repeated == 'V' || repeated == 'X' || repeated == 'L' || repeated == 'C' || repeated == 'D' || repeated == 'M'){
JOptionPane.showMessageDialog(null, repeated + " is repeated more than three times in " + num);
}
else{
JOptionPane.showMessageDialog(null, num + " is a roman number");
}
}
if(){
JOptionPane.showMessageDialog(null, + " is not a roman number in " + num);
}
}
I use the regex num.matches("[IVXLCDM]+")
to determine if the entered string only contains roman numeral chars my issue is i want to print a message if a char in the string is not a roman numeral char using the last if statement. what would be the most effective way to find the chars in the string that are not roman numeral chars?
This finds the first occurance
else {
Matcher matcher = Pattern.compile("[^IVXLCDM]").matcher();
matcher.find();
JOptionPane.showMessageDialog(null, matcher.group() + " is not a roman number in " + num);
}
This finds all occurances
else {
JOptionPane.showMessageDialog(null, num.replaceAll("[^IVXLCDM]", "") + " are not roman numbers in " + num);
}
Just use replaceAll
with your regex on the input string, so that only characters that are not roman numerals are left over, with underscores between to preserve the index:
String notRomanNumerals = num.replaceAll("[IVXLCDM]+", "_");
System.out.println("Error: not all characters are roman numerals: "+ notRomanNumerals);
If then you want the index of the character in the string, then just do
for(int i=0;i<notRomanNumerals.length;i++) {
if(notRomanNumerals.charAt(i) != '_') {
// i is an index of a char that is not a roman numeral
// Do what you want with it
}
}
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.