gpt4 book ai didi

java - 如何比较字符串

转载 作者:行者123 更新时间:2023-11-29 09:40:25 24 4
gpt4 key购买 nike

我试图让用户按下数字,然后他们输入他们想要查看的可用选项的字符串。到目前为止一切正常,除了当用户输入字符串时它没有给出首选输出。*显示电子邮件而不是颜色、用户 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());
}
}

最佳答案

在所有的 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") .

关于java - 如何比较字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58359289/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com