让我们首先初始化您的学生类的对象,将错误检查放在一边。正如您所说,无论如何您都必须设置这两个字段(fullName 和 studentId)。这就是我们将拥有的:
public class Student {
private String studentId;
private String fullName;
public Student(String studentId, String fullName) {
this.studentId = studentId;
this.fullName = fullName;
}
public static void main(String[] args) {
Student s = new Student("12", "John Doe");
}
}
上面的代码首先可以满足您的需求。我希望你明白那里发生了什么?如果没有,那就问吧。
好的,我们现在需要的是添加这个“长度检查”。关键是理解“if”结构。“如果”允许您仅在满足特定条件时执行某些代码块。条件可以是任何表达式,但它必须被评估为“真”或“假”(它需要是布尔值)。“如果”构造如下所示:
if (expression) {
System.out.println("Expression was true!");
}
你可以用你的条件来代替“表达”,如果它是真的,代码将被执行。看到这个:
if (3 > 2) {
System.out.println("Three is greater than two");
}
好吧,我们可以使用这些知识来执行我们的长度测试:
if (fullName.length() < 4) {
System.err.println("Name '" + fullName + "' is too short");
}
使用相同的构造(但条件不同)来测试 studentId。我相信您应该能够修改原始来源以检查字符串长度。
至于这个赋值——在这种情况下你不需要 else 构造,但要完整:你可以将它与“if”结合使用,在不满足条件时执行某些代码,如下所示:
if (fullName.length() < 4) {
System.err.println("Too short!");
}
else {
System.out.println("OK");
}
希望这可以帮助。