我试图让用户按下一个数字,然后输入他们想要看到的可用选项的字符串。到目前为止,一切都正常,除了当用户键入字符串时,它不会给出首选的输出。*显示电子邮件,而不是颜色、用户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")。
发布于 2019-10-13 07:13:42
试一试,总是避免重复输入大小写,让你的代码更有效率。
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());
}
}发布于 2019-10-13 07:17:11
也许读起来更容易一些:
if (1 <= x && x <= 5) {
switch (bean) {
case "email":
System.out.println(record.email);
break;
case "name":
System.out.println(record.firstName);
break;
...
}
}使用switch expression (Java13,--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);
...
}
}https://stackoverflow.com/questions/58359289
复制相似问题