I want to write a program in which a box is shown to user and asks to enter a name.
If the name is typed correctly (real name), final message comes up but if for instance the user types an integer, the program asks the user to type a real name in String again.
Code :
import javax.swing.*;
public class Project018 {
public static void main(String[] args) {
String name = JOptionPane.showInputDialog("What is your name?");
try {
int number = Integer.parseInt(name);
} catch (NumberFormatException n){
JOptionPane.showMessageDialog(null, "Dear " + name + "\nwelcome to java programming course");
}
String message = String.format("your name must not contain any number");
JOptionPane.showMessageDialog(null, message);
}
}
I want to know how I can loop back the program to the top when the user types an integer and how I can skip the second message when a real name is entered
I want to know how I can loop back the program to the top when the user types an integer
Well, for this I would use a do-while
loop.
For checking if the input is / has numbers, you shouldn't do it trying to parse the numbers to integer. Instead I would use a Pattern
with a Matcher
and regex
. Otherwise you're not considering this case: Foo123
In this case something like: [0-9]+
for the regex, and if the Matcher
matches with it, then it has a number.
how I can skip the second message when a real name is entered
Based on if the Matcher
matches something you show one dialog or the other
For example:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
public class LoopingJOptionPane {
private static final String REGEX = "[0-9]+";
public static void main(String[] args) {
SwingUtilities.invokeLater(new LoopingJOptionPane()::createAndShowGui);
}
private void createAndShowGui() {
boolean found = true;
do { //This repeats this code if input is incorrect
Pattern pattern = Pattern.compile(REGEX);
String name = JOptionPane.showInputDialog("Enter your name");
Matcher matcher = pattern.matcher(name); //We try to find if there's a number in our string
found = matcher.find();
if (found) { //If there's a number, show this message
JOptionPane.showMessageDialog(null, "Please write only letters");
} else { //Otherwise show this one
JOptionPane.showMessageDialog(null, "Welcome " + name);
}
} while (found); //If it has no numbers, don't repeat
}
}