有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么这个方法会重复它的循环?

此方法从用户检索并验证社会保险号码。如果输入有效,它工作正常。如果不是,则while (true)重复,而不是转到

else {
    System.out.println("Make sure the social security number is valid.");
}

声明

方法如下:

public static String getSSN(Scanner sc, String prompt) {
        String ssn = "";

        while (true) {
            System.out.println(prompt);
            if(sc.hasNext()) {
                ssn = sc.next();
                if(ssn.length() == 11 
                    && checkNumeric(ssn.substring(0, 3)) 
                    && "-".equalsIgnoreCase(ssn.substring(3, 4))
                    && checkNumeric(ssn.substring(4, 6)) 
                    && "-".equalsIgnoreCase(ssn.substring(6, 7)) 
                    && checkNumeric(ssn.substring(7, 11)))
                    break;
            }
            else {
                System.out.println("Make sure the social security number is valid.");
            }
        }
        return ssn;       
    }

以下是输出:

Enter a Social Security Number: 
23
Enter a Social Security Number: 
4
Enter a Social Security Number: 
2

共 (2) 个答案

  1. # 1 楼答案

    我认为你应该这样做:

    while(sc.hasNext()) ...
    
  2. # 2 楼答案

    括号不正确。else分支属于if(sc.hasNext())条件。要使代码正常工作,请将其移动到适当的位置:

    public static String getSSN(Scanner sc, String prompt) {
        String ssn = "";
    
        while (true) {
            System.out.println(prompt);
            if(sc.hasNext()) {
                ssn = sc.next();
                if(ssn.length() == 11 
                    && checkNumeric(ssn.substring(0, 3)) 
                    && "-".equalsIgnoreCase(ssn.substring(3, 4))
                    && checkNumeric(ssn.substring(4, 6)) 
                    && "-".equalsIgnoreCase(ssn.substring(6, 7)) 
                    && checkNumeric(ssn.substring(7, 11))) {
                    break;
                } else {
                    System.out.println("Make sure the social security number is valid.");
                }
            }            
        }
        return ssn;       
    }
    

    将单行语句也用大括号括起来被认为是一个好习惯。如果分支发生更改并添加了其他命令,则代码更干净,也更不容易出错