2

Hello i'm new to java and i would like to ask some question regarding JOptionPane.showinput so that it will only accept letters/numbers only and if they enter an incorrect one it will result to an error and need to retype again (searched the site for some solution but they don't work on my code i don't know why) And lastly i was planning to multiple choices on my joptionpane but when i typed icon it got registered as an error heres my code

JFrame frame = new JFrame("Student Record");
JOptionPane.showMessageDialog(frame,
    "Welcome to the School's Student Grade Record!");
System.out.println("School's Student Grade Record");
String name;
name = JOptionPane.showInputDialog(frame,"Enter the name of the student");
System.out.println("The name of the student is: "+name);
Object[] choices = {"Filipino", "Math", "English"};
String grade = (String)JOptionPane.showInputDialog(frame,
    "What grade subject do you choose to input?\"","Customized Dialog",
    JOptionPane.PLAIN_MESSAGE,icon,choices,"Math");
System.exit(0);
Yamiess
  • 251
  • 4
  • 15

1 Answers1

2

for getting a valid string that contains only alphabets and numbers then regex are a great help ^[a-zA-Z0-9]*$ it allows only alphabets and numbers only and the following code will ask repeatedly until a valid input is given

String input;
            String string = "";
            do {
                input = JOptionPane.showInputDialog("Enter String ");
                if (input.matches("^[a-zA-Z0-9]*$")) {
                    string = input;
                    System.out.println("Name "+string);
                } else {
                    System.out.println("Please enter a valid name containing: ‘a-z’ or ‘A-Z’ lower or upper case or numbers");
                }
            } while (!input.matches("^[a-zA-Z0-9]*$"));

now about your icon here is a way to specify icons

Sahil Manchanda
  • 9,812
  • 4
  • 39
  • 89
  • Hello there used your code and it worked well i deleted the 0-9 though since i only need the letters and such, but then i encountered a problem where putting space on the name will result in the please enter a valid name.. any ideas on what i should put on the input matches? – Yamiess Oct 14 '16 at 09:50
  • Ok this might be stupid but is there any possible way so that only 1 space is allowed? – Yamiess Oct 14 '16 at 09:53
  • @Yamiess '^' is beginning of string for allowing only one space read http://stackoverflow.com/a/2932439/2299040 and accept the answer – Sahil Manchanda Oct 14 '16 at 10:55
  • @Yamiess click on the tick icon appearing nearby the answer – Sahil Manchanda Oct 14 '16 at 11:00