[英]Having trouble with JoptionPane Validation
我遇到的問題是與此代碼:
String birthString = JOptionPane.showInputDialog(
null, "Enter birth year: ", "How long have you been alive?",
JOptionPane.QUESTION_MESSAGE);
Pattern p = Pattern.compile("[A-Z,a-a,&%$#@!()*^]");
Matcher m = p.matcher(birthString);
if (m.find()){
JOptionPane.showMessageDialog(null,
"That doesn't look like numbers to me... Try again.",
"How long have you been alive?", JOptionPane.WARNING_MESSAGE);
}
int birth = Integer.parseInt(birthString);
String currentString = JOptionPane.showInputDialog(
null, "Enter cureent year: ", "How long have you been alive?",
JOptionPane.QUESTION_MESSAGE);
int current = Integer.parseInt(currentString);
Pattern c = Pattern.compile("[A-Z,a-a,&%$#@!()*^]");
Matcher n = c.matcher(currentString);
if (n.find()){
JOptionPane.showMessageDialog(null,
"That doesn't look like numbers to me... Try again.",
"How long have you been alive?", JOptionPane.WARNING_MESSAGE);
}
我想確定的是,如果有人輸入除數字以外的任何內容,則會顯示對話框消息“對我來說這看起來不像數字...請重試”。 唯一的問題是它不執行該操作,該程序只是錯誤。 任何幫助將不勝感激,我知道這是我做錯的小事,只是找不到。
您要匹配一年,為什么不使用更簡單的正則表達式。 \\\\d+
將匹配一個或多個整數字符。 Matcher#matches將對完整的String
進行匹配:
if (!birthString.matches("\\d+")) {
JOptionPane.showMessageDialog(null,
"That doesn't look like numbers to me... Try again.",
"How long have you been alive?", JOptionPane.WARNING_MESSAGE);
}
另請: 模式
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.