我试图让用户按下一个数字,然后输入他们想要看到的可用选项的字符串。到目前为止,一切都正常,除了当用户键入字符串时,它不会给出首选的输出。*显示电子邮件,而不是颜色、用户id等。以下是我的代码。再次感谢!
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 == 2 || x == 3 || x == 4 || x == 5 && bean.equals("email")) {
System.out.println(objects[x].getEmail());
}
else if (x == 1 || x == 2 || x == 3 || x == 4 || x == 5 && bean.equals("name")) {
System.out.println(objects[x].getfirstName());
}
else if (x == 1 || x == 2 || x == 3 || x == 4 || x == 5 && bean.matches("last name")) {
System.out.println(objects[x].getlastName());
}
else if (x == 1 || x == 2 || x == 3 || x == 4 || x == 5 && bean.matches("balance")) {
System.out.println(objects[x].getBalance());
}
else if (x == 1 || x == 2 || x == 3 || x == 4 || x == 5 && bean.matches("color")) {
System.out.println(objects[x].getColor());
}
else if (x == 1 || x == 2 || x == 3 || x == 4 || x == 5 && bean.matches("idnumber")) {
System.out.println(objects[x].getnumID());
}
}发布于 2019-10-13 07:07:30
在所有if条件中,&&的优先级高于||,因此您必须将条件更改为:
(x == 1 || x == 2 || x == 3 || x == 4 || x == 5) && bean.equals("email")。
如果x是1到5之间的某个值,并且bean等于"email",则这与您想要的逻辑相对应。但是,请研究比较运算符,因为您可以将其简化为:
(1 <= x && x <= 5) && bean.equals("email")。
https://stackoverflow.com/questions/58359289
复制相似问题