尝试捕获数字输入

时间:2017-04-05 19:46:22

标签: java try-catch joptionpane

我在尝试弄清楚如何防止数字化的用户输入时遇到了一些麻烦。我理解如何防止非数字输入(即输入字母而不是数字)但不是相反。我该如何解决这个问题?

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--;
     }

2 个答案:

答案 0 :(得分: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;
 }

答案 1 :(得分: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--;
}