Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I specify a numeric pattern with dashes in Java

For this code, I’m trying to get the user to input a pattern of numbers like "####-##-###" including the dashes. I have this code but it’s returning an error.

import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.Scanner;

public class StudentNumber {

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.print("Enter your student number: ");
        int su;
        Pattern p = Pattern.compile("[\\d]{4,}+[-?]{1,1}+[\\d]{2,}+[-?]{1,1}+[\\d]{3,}");
        su = s.nextInt();
        String input = String.valueOf(su);
        Matcher m = p.matcher(input);
        if (m.matches()){
            System.out.println("You have successfully logged in.\nWelcome to your new dashboard!");
        } else {
            System.out.println("Invalid format. Try Again.");
        }
    }
}

the error is

Exception in thread "main" java.util.InputMismatchException
 at java.base/java.util.Scanner.throwFor(Scanner.java:943)
 at java.base/java.util.Scanner.next(Scanner.java:1598)
 at java.base/java.util.Scanner.nextInt(Scanner.java:2263)
 at java.base/java.util.Scanner.nextInt(Scanner.java:2217)
 at com.mycompany.studentnumber.StudentNumber.main(StudentNumber.java:21)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The error you’re getting is because you have the dashes in the string and you’re calling nextInt. You need to read the input as a string (with e.g. nextLine) then apply the regex to that and convert the parts to integers as appropriate.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading