3 回答
TA贡献1817条经验 获得超14个赞
尝试一下,始终避免重新输入案例并使您的代码更加高效。
public static void printStuff(Record[] objects) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the number and record name you would like to see");
int x = in.nextInt();
String bean = in.next();
if (x >= 1 && x =< 5 ) {
if (bean.equals("email"))
System.out.println(objects[x].getEmail());
else if (bean.equals("name"))
System.out.println(objects[x].getfirstName());
else if (bean.matches("last name"))
System.out.println(objects[x].getlastName());
else if (bean.matches("balance"))
System.out.println(objects[x].getBalance());
else if (bean.matches("color"))
System.out.println(objects[x].getColor());
else if (bean.matches("idnumber"))
System.out.println(objects[x].getnumID());
}
}
TA贡献1873条经验 获得超9个赞
在所有 if 条件中,&&
的优先级高于||
,因此必须将条件更改为:
(x == 1 || x == 2 || x == 3 || x == 4 || x == 5) && bean.equals("email")
.
这对应于您想要的逻辑,如果x
1 到 5 中的某个值 AND bean 等于"email"
。但是,请研究比较运算符,因为您可以将其简化为:
(1 <= x && x <= 5) && bean.equals("email")
.
TA贡献1862条经验 获得超7个赞
也许更容易阅读:
if (1 <= x && x <= 5) {
switch (bean) {
case "email":
System.out.println(record.email);
break;
case "name":
System.out.println(record.firstName);
break;
...
}
}
使用switch 表达式(Java 13, --enable-preview
):
if (1 <= x && x <= 5) {
System.out.println(switch (bean) {
case "email" -> record.email;
case "name" -> record.firstName;
case "last name"-> record.lastName;
...
default -> "unrecognized " + bean;
// default -> throw new IllegalArgumentException(...);
});
}
或者,如果对未知不执行任何操作bean:
if (1 <= x && x <= 5) {
switch (bean) {
case "email" -> System.out.println(record.email);
case "name" -> System.out.println(record.firstName);
...
}
}
添加回答
举报