Try to enter numeric inputs
I am having trouble trying to figure out how to prevent user input. I understand how to prevent non-numeric inputs (i.e. entering a letter instead of a number), but not vice versa. How do I get 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--;
}
+3
source to share
2 answers
Use the do / while statement. "Enter the input until the input finally contains 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;
}
+1
source to share
You can use regex to accept only characters, below is the code snippet,
String regex = "^[A-z]+$";
String data = "abcd99";
System.out.println(data.matches(regex));
So, in your code, you can put 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--;
}
0
source to share