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)
>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.