3 回答

TA貢獻(xiàn)1817條經(jīng)驗(yàn) 獲得超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貢獻(xiàn)1873條經(jīng)驗(yàn) 獲得超9個贊
在所有 if 條件中,&&
的優(yōu)先級高于||
,因此必須將條件更改為:
(x == 1 || x == 2 || x == 3 || x == 4 || x == 5) && bean.equals("email")
.
這對應(yīng)于您想要的邏輯,如果x
1 到 5 中的某個值 AND bean 等于"email"
。但是,請研究比較運(yùn)算符,因?yàn)槟梢詫⑵浜喕癁椋?/p>
(1 <= x && x <= 5) && bean.equals("email")
.

TA貢獻(xiàn)1862條經(jīng)驗(yàn) 獲得超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 表達(dá)式(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(...);
? ? });
}
或者,如果對未知不執(zhí)行任何操作bean:
if (1 <= x && x <= 5) {
? ? switch (bean) {
? ? ? ? case "email" -> System.out.println(record.email);
? ? ? ? case "name" -> System.out.println(record.firstName);
? ? ? ? ...
? ? }
}
添加回答
舉報