3

I'm having a bit of trouble trying to figure out how to prevent user input that are numerical. I understand how to prevent non-numerical inputs (ie. inputting a letter instead of a number) but not the other way around. How do I work around this?

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--;
     }
Ken
  • 135
  • 10
  • Possible duplicate of [How to use Scanner to accept only valid int as input](http://stackoverflow.com/questions/2912817/how-to-use-scanner-to-accept-only-valid-int-as-input) – tnw Apr 05 '17 at 19:47
  • 2
    Don't use exceptions to control program flow! Exceptions are for error handling. – Frank Puffer Apr 05 '17 at 19:47
  • 1
    @tnw he wants the exact opposite of that – litelite Apr 05 '17 at 19:48
  • http://stackoverflow.com/questions/1102891/how-to-check-if-a-string-is-numeric-in-java could be interesting for you – litelite Apr 05 '17 at 19:49
  • 2
    You should read [Number 15](http://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/). And the rest of the post, too, it's good. – Andy Turner Apr 05 '17 at 19:50
  • @FrankPuffer agreed, don't use Exceptions for program flow - use them for "transaction" success / failure – ControlAltDel Apr 05 '17 at 19:51
  • @litelite So put a `!` in front of the if statement... `hasNextDouble` would probably be more appropriate too. – tnw Apr 05 '17 at 19:53

2 Answers2

1

Use a do/while statement. "Do input while the input contains at last one number".

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;
 }
davidxxx
  • 125,838
  • 23
  • 214
  • 215
0

You can use Regular Expression to accept only characters, below is the chunk of code,

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

So in your code you can put the validation like this,

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