Search code examples
javaregexswingexceptionjoptionpane

How do I limit the number of digits in a user input?


Pattern p = Pattern.compile("^[0-9]{0,3}$");
Matcher m = p.matcher(in);
if (m.find()) {
    JOptionPane.showMessageDialog(null, " 4 integers please");
}

It is a button that adds numbers

Trying to create exception that limits amount of numbers in dialog , it detects if the number is within the limit but does not stop the program.


Solution

  • You can simply use in.matches("\\d{4}") as the condition and add to the textarea only if this condition is true.

    import javax.swing.JOptionPane;
    
    public class Main {
        public static void main(String[] args) {
            String in = JOptionPane.showInputDialog("Number: ");
            if (in.matches("\\d{4}")) {
                // ...Code to add the value to the textarea
            } else {
                JOptionPane.showMessageDialog(null, "Only 4 digits please.");
            }
        }
    }