Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

try catch numeric inputs

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--;
     }
like image 709
Ken Avatar asked Jan 26 '26 05:01

Ken


1 Answers

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;
 }
like image 59
davidxxx Avatar answered Jan 27 '26 18:01

davidxxx