我正在开发一个确定输入的字符串是罗马数字的程序。我的问题是在以下代码中
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);
}
}
我使用正则表达式
num.matches("[IVXLCDM]+")
来确定输入的字符串是否仅包含罗马数字字符。我的问题是,如果要使用最后一个if语句,如果字符串中的字符不是罗马数字字符,我想打印一条消息。在字符串中查找不是罗马数字字符的字符的最有效方法是什么? 最佳答案
找到第一次出现
else {
Matcher matcher = Pattern.compile("[^IVXLCDM]").matcher();
matcher.find();
JOptionPane.showMessageDialog(null, matcher.group() + " is not a roman number in " + num);
}
找到所有出现的地方
else {
JOptionPane.showMessageDialog(null, num.replaceAll("[^IVXLCDM]", "") + " are not roman numbers in " + num);
}