1

这行程序假设测试一个字符串以确保它是 5 个字符并且以字符“u”开头。现在只是测试字符串是否是5个字符而不是测试的第二部分?

String UID;
        do {
            System.out.println("Enter the Student's UID in the form of u####");
            UID = input.nextLine();
            if (UID.length() != 5) {
                System.out.println("INCORRECT INPUT");
            }
        } while (UID.length() != 5 && UID.charAt(0) != 'u');
        return UID;
    }
4

2 回答 2

1

您可以大大简化:

while (true) {
    System.out.println("Enter the Student's UID in the form of u####");
    String UID = input.nextLine();
    if (UID.length() == 5 && UID.charAt(0) == 'u') {
        return UID;
    }
    System.out.println("INCORRECT INPUT");
} 

甚至更进一步

...
if (UID.matches("u....")) {
...
于 2012-11-17T03:27:07.713 回答
1

您应该按如下方式更改您的条件检查:

do {
    //... 
    if(UID.length() != 5 || UID.charAt(0) != 'u') {
        //incorrect input
    }
} while(UID.length() != 5 || UID.charAt(0) != 'u');
//continue until either of the conditions is true

而且您不需要循环本身内部的检查。

IMO,最好只进行一次条件检查

while(true) {
    //... 
    if(UID.length() != 5 || UID.charAt(0) != 'u') {
        //incorrect input
    } else {
        break;
    }
} 

您也可以使用该String.startsWith(String)方法。

于 2012-11-17T02:50:30.757 回答