if (条件表达式) {
// 条件为true时执行的代码
}
int age = 18; if (age >= 18) {
System.out.println("您已成年");
}
int score = 85; boolean hasSubmitted = true;
if (score >= 60) {
if (hasSubmitted) {
System.out.println("成绩合格,作业已提交");
} else {
System.out.println("成绩合格,但作业未提交");
}
} else {
System.out.println("成绩不合格");
}
public boolean validateUserInput(String username, String password) {
if (username == null || username.trim().isEmpty()) {
System.out.println("用户名不能为空");
return false;
}
if (password == null || password.length() < 6) {
System.out.println("密码长度至少6位");
return false;
}
if (username.contains(" ")) {
System.out.println("用户名不能包含空格");
return false;
}
return true;
}
// 使用if语句处理用户权限 public void checkPermission(User user, Operation operation) {
if (user.getRole().equals("admin")) {
executeAdminOperation(operation);
} else if (user.getRole().equals("editor")) {
executeEditorOperation(operation);
} else if (user.getRole().equals("viewer")) {
executeViewerOperation(operation);
} else {
throw new PermissionDeniedException();
}
}
// 使用switch语句处理菜单选择 public void handleMenuSelection(int choice) {
switch (choice) {
case 1:
createNewFile();
break;
case 2:
openFile();
break;
case 3:
saveFile();
break;
case 4:
exitProgram();
break;
default:
showErrorMessage("无效选择");
}
}
你可能想看: