charAt方法和字符串

时间:2012-11-17 02:38:52

标签: java string

这行程序假设测试一个字符串以确保它是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;
    }

2 个答案:

答案 0 :(得分: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)方法。

答案 1 :(得分: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....")) {
...