2017-04-05 36 views
3

我在試圖弄清楚如何防止用戶輸入數字時遇到了一些麻煩。我瞭解如何防止非數字輸入(即輸入一個字母而不是數字),而不是相反。我如何解決這個問題?嘗試捕獲數字輸入

String[] player_Name = new String[game];  
    for (i = 0; i < game; i++) { 
    try { 
     player_Name[i] = JOptionPane.showInputDialog("Enter the name of the 
player, one by one. "); 
    } catch(Exception e) { 
     JOptionPane.showMessageDialog(null, "Enter a valid name!"); 
     i--; 
    } 
+0

可能[如何使用掃描器只接受有效的int作爲輸入]的副本(http://stackoverflow.com/questions/2912817/how-to-use-scanner-to-accept-only-valid-int-as-input) – tnw

+2

不要使用異常來控制程序流!例外是錯誤處理。 –

+1

@tnw他想要的是相反的 – litelite

回答

1

使用do/while語句。 「輸入時輸入包含最後一個數字」。

String[] player_Name = new String[game];  
for (int i = 0; i < game; i++) { 
    String input; 
    do {    
     input = JOptionPane.showInputDialog("Enter the name of the 
     player, one by one. ");    
     } while (input.matches(".*\\d+.*")); 

     player_Name[i] = input; 
} 
+0

根據第三方庫只是爲了檢查這似乎有點矯枉過正。 –

+0

@Andy Turner的確如此。用簡單的正則表達式應該更簡單,如果還可以檢查字符串混合字符和數字 – davidxxx

0

您可以使用正則表達式只接受字符,下面是代碼塊,

String regex = "^[A-z]+$"; 
    String data = "abcd99"; 
    System.out.println(data.matches(regex)); 

因此,在你的代碼,你可以把這樣的驗證,

String[] player_Name = new String[game]; 
for (int i = 0; i < game; i++) { 
    player_Name[i] = JOptionPane.showInputDialog("Enter the name of the player, one by one.  "); 
    if (!player_Name[i].matches("^[A-z]+$")) { 
     JOptionPane.showMessageDialog(null, "Enter a valid name!");    
    } 
    i--; 
}