public static void main(String[] args) {
String input = getInputString();
int numCount = countNum(input);
JOptionPane.showMessageDialog(null, "字符串 [" + input + "] 中數字的個數為:" + numCount );
}
/** 計算字符串中數字的個數 */
public static int countNum(String str){
int count = 0;
for(char c:str.toCharArray()){
if(Character.isDigit(c)){
count++;
}
}
return count;
}
private static String getInputString() {
String input = null;
while(true){
input = JOptionPane.showInputDialog("請輸入字符串");
if(input == null || input.trim().length() == 0)
JOptionPane.showMessageDialog(null, "忽悠我是吧, 別正個空的字符串啊 ~");
else
return input;
}
}
}