如何在 Java 中指定带破折号的数字模式

How can I specify a numeric pattern with dashes in Java

对于此代码,我试图让用户输入数字模式,例如“####-##-###”,包括破折号。我有这段代码,但它返回错误。

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.");
        }
    }
}

错误是

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)

你得到的错误是因为你在字符串中有破折号并且你正在调用 nextInt。您需要将输入读取为字符串(例如 nextLine),然后将正则表达式应用于该字符串并将部分转换为适当的整数。

su = s.nextInt();

由于您期望的输入包含破折号,即 -,它不是 int,它是一个字符串,因此使用方法 nextLine(而不是方法 nextInt).

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

public class StudentNumber {

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.print("Enter your student number: ");
        Pattern p = Pattern.compile("[\d]{4,}+[-?]{1,1}+[\d]{2,}+[-?]{1,1}+[\d]{3,}");
        String input = s.nextLine();
        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.");
        }
    }
}

这是示例的输出 运行:

Enter your student number: 123-456-789
Invalid format. Try Again.

这是另一个示例 运行:

Enter your student number: 1234-56-789
You have successfully logged in.
Welcome to your new dashboard!

由于您在 int 输入中使用 -,输入不能将其作为整数,而是使用 Scanner() next() 方法 class.

String input = in.next()

此外,如果您正在使用

Pattern p = Pattern.compile("[\d]{4,}+[-?]{1,1}+[\d]{2,}+[-?]{1,1}+[\d]{3,}");

它也验证了 111111-11-11111。为避免这种情况,请改用

Pattern p = Pattern.compile("[\d]{4}+[-?]{1}+[\d]{2}+[-?]{1}+[\d]{3}");