java - charAt 方法和字符串

标签 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;
    }

最佳答案

您应该按如下方式更改您的状况检查:

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)方法。

关于java - charAt 方法和字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13427133/

相关文章:

java - 字符串 url 编码两次,我无法获取初始字符串

java - 无法从 build.gradle 中的 System.getenv() 访问 mac 上的环境变量

c++ - 良好的 C++ 字符串操作库

c# - 是否可以在不使用连接器的情况下将 C# 变量包含在字符串变量中?

java - 在 Android 中扫描条形码

java - GWT Maven 插件替换 web.xml

java - 没有类型的 Lambda 表达式

c# - 从文本文件中拆分字符串

c - ispalindrome C,检查空间的问题

python - 括号和单引号中的 Argparse 文件输出