2016-09-16 52 views
0

我是一個初學者程序員(第一篇文章在這裏!),我無法弄清楚如何用「do while」循環創建錯誤消息。如果給定的輸入不在字母表中,它應該顯示錯誤信息,直到給出只有字母的輸入,然後移動到程序的其餘部分。即使給予正確的輸入,我的代碼似乎也會永久循環。任何建議,非常感謝! :)做while循環錯誤消息

do { 
    input = JOptionPane.showInputDialog("What is your name?"); 
    if (input.contains("[a-zA-Z]")) 
     name = input; 
    else 
     System.out.println("Please enter a valid name containing: ‘a-z’ or ‘A-Z’ lower or upper case"); 
} while (!input.contains("[a-zA-Z]")); 

回答

0

你用錯誤的方法來驗證您的正則表達式什麼。 .contains()需要一個字符序列。這不是你想要的。 您應改爲使用.matches()方法。

String input = ""; 
do{ 
input = JOptionPane.showInputDialog("What is your name?"); 
    if (input.matches("[a-zA-Z]+")) // Replacing the contains() 
     name = input; 
     else 
     System.out.println 
    ("Please enter a valid name containing: ‘a-z’ or ‘A-Z’ lower or upper case"); 
}while (!input.matches("[a-zA-Z]+")); //Once again replacing contains() 
+0

這完美地工作,太感謝你了! :) –

+0

@GregSmith不客氣。 –

0

String.contains()方法匹配一組字符序列。 您指定的是正則表達式,因此,您應該使用String.matches()Pattern類來執行檢查。

它應該是這樣的使用類Pattern類。

Pattern p = Pattern.compile("[a-zA-Z]+"); 
Matcher m = p.matcher(input); 
if(m.matches){ 
//Do something 
} 

請參閱本documentation更多細節

0

input.contains("[a-zA-Z]")檢查是否輸入包含文本[A-ZA-Z]。可以使用matches方法。

input.matches("[a-zA-z]+") 

此外,您應該使用[a-zA-z] +作爲模式,因爲您試圖匹配一個或多個字母。

0

該問題與您如何檢查給定輸入有關。

String input; 
     String name = ""; 
     do { 
      input = JOptionPane.showInputDialog("What is your name?"); 
      if (input.matches("[a-zA-Z]+")) { 
       name = input; 
      } else { 
       System.out.println("Please enter a valid name containing: ‘a-z’ or ‘A-Z’ lower or upper case"); 
      } 
     } while (!input.matches("[a-zA-Z]+")); 

使用字符串匹配功能可以幫你實現你想要

1

您可以向用戶顯示錯誤彈出窗口,以便他知道他/她的輸入有問題。

在else語句你在哪裏打印消息只是做

JOptionPane.showMessageDialog(frame, 
"Please enter a valid name containing: ‘a-z’ or ‘A-Z’ lower or upper case.", 
"Input error", 
JOptionPane.ERROR_MESSAGE); 

return; 

For more information