Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/google-app-engine/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 尝试捕捉数字输入_Java_Try Catch_Joptionpane - Fatal编程技术网

Java 尝试捕捉数字输入

Java 尝试捕捉数字输入,java,try-catch,joptionpane,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

我在试图找出如何防止用户输入数字时遇到了一些麻烦。我知道如何防止非数字输入(即输入字母而不是数字),但不是相反。我如何解决这个问题

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--;
     }
String[]player_Name=新字符串[游戏];
对于(i=0;i
使用do/while语句。 “当输入包含最后一个数字时进行输入”

String[]player_Name=新字符串[游戏];
for(int i=0;i
您可以使用正则表达式仅接受字符,下面是代码块

  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--;
}
String[]player_Name=新字符串[游戏];
for(int i=0;i
Don't use exceptions to control program flow(不使用异常控制程序流)的可能重复项!异常是用于错误处理的。@tnw他想要与此完全相反的内容,这对你来说可能很有趣。你应该读一下。这篇文章的其余部分也很好。依靠第三方库来检查这一点似乎有点过火了。@Andy Turner确实如此。用一个简单的正则表达式它应该更简单,如果还可以检查字符串混合字符和数字
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--;
}