问题
I'm trying to prompt for a first/last name in this code, but I cannot figure out how to re-prompt a user for the name if they forget to fill out the field. Right now if my code does not get any input and the user clicks onwards, I have it so a message box will pop up and then the program will close. I want to be able to just re-prompt for the exact same step without it getting all out of order.
This is what I have so far:
public void getValues(){
firstName = JOptionPane.showInputDialog(null, "Please enter employee's first name");
if (firstName.equals("")){
JOptionPane.showMessageDialog(null,"Please enter a first name, next time.");
System.exit(-1);
} else {
lastName = JOptionPane.showInputDialog(null, "Please enter employee's last name");
if (lastName.equals("")){
JOptionPane.showMessageDialog(null,"Please enter a last name, next time.");
System.exit(-1);
} else {
Thank you.
回答1:
Use a while
loop where necessary until you get the input you want.
Here's a snippet.
String firstname = JOptionPane.showInputDialog(null, "Name?");
while(firstname.equals("")) {
firstname = JOptionPane.showInputDialog(null, "You need to enter a first name!);
}
回答2:
You can use a while
statement to continuously ask the user for input until the input is valid.
Ex:
while((firstName = JOptionPane.showInputDialog(null, "Your Message")).equals("")){
JOptionPane.showMessageDialog(null, "That name isn't valid!");
}
回答3:
You can do something like this:
do {
firstName = JOptionPane.showInputDialog(null, "Please enter employee's first name");
} while (firstName != null && firstName.equals(""));
if (firstName == null) {
// user canceled
}
来源:https://stackoverflow.com/questions/8965839/re-prompting-the-user-for-data-input-with-an-if-statement