在扫描仪中循环 if else

Loop if else in scanner

如果用户输入了某些内容并且它使我的代码中的语句为假,我想循环我的扫描仪,如果用户输入了错误的语句,循环将继续,但如果我输入正确的语句,它仍然会继续.

Scanner sc = new Scanner(System.in);
    
    System.out.println("Enter your student number: ");
    String sn = sc.nextLine();
    
    String REGEX = "[0-9]{4}.[0-9]{2}.[0-9]{3}";
    Pattern pattern = Pattern.compile(REGEX);      
    Matcher matcher = pattern.matcher(sn);
   
    do {
        if (matcher.matches()) {
            System.out.println("You have succesfully logged in");   
            System.out.println("Hello " + sn + " welcome to your dashboard");   
        }
        else    
            System.out.println("Please enter your student number in this format: 'xxxx-xx-xxx' ");
            System.out.println("Enter your student number: ");
            sc.nextLine();

          
    } while (true);
Matcher matcher = pattern.matcher(sn);

这与 'sn' 中当前的模式相匹配。如果 'sn' 发生变化,则不会影响匹配器。如果您读取另一行而没有将结果分配给任何内容,那不会影响 'sn' 或匹配器。

而且你没有循环终止 - 它只是“do while true”没有出路。

所以,三个问题:

  1. 需要在循环内创建匹配器。

  2. 第二次nextLine调用的结果需要赋值给'sn'

  3. 您需要一个循环终止。我建议一个标志,'loggedIn',最初是 false,在成功匹配时设置为 true,循环以 'while (!loggedIn)'

    结束

我会这样重写

Scanner sc = new Scanner(System.in);

System.out.println("Enter your student number: ");
String sn = sc.nextLine();

String REGEX = "[0-9]{4}.[0-9]{2}.[0-9]{3}";
Pattern pattern = Pattern.compile(REGEX);

while(!pattern.matcher(sn).matches()) {
    System.out.println("Please enter your student number in this format: 'xxxx-xx-xxx' ");
    System.out.println("Enter your student number: ");
    sn = sc.nextLine();
}
System.out.println("You have succesfully logged in");
System.out.println("Hello " + sn + " welcome to your dashboard");