我在类似的问题上找了一点,找不到能够帮助我解决问题的答案。
我正在尝试读取用户输入,似乎没有将变量设置为输入。
例如:
System.out.println("Would you like Syrup?(Y/N)");
String wantSyrup = keyboard.next();
char syrupWant = wantSyrup.charAt(0);
switch (syrupWant){
case 'y':
System.out.println("Which syrup would you like?");
System.out.println("Hot fudge, Chocolate, Caramel, Strawberry");
syrupChoice = keyboard.nextLine();
keyboard.nextLine();
System.out.println("You entered: "+syrupChoice);
if((syrupChoice.equalsIgnoreCase(hotFudge)) | (syrupChoice.equalsIgnoreCase(chocolateSyrup))|
(syrupChoice.equalsIgnoreCase(caramel))| (syrupChoice.equalsIgnoreCase(strawberrySyrup))){
System.out.println(syrupChoice);
}else{
System.out.println("Not a valid choice. You now have Hot Fudge as your syrup.");
syrupChoice = hotFudge;
}
break;
default: break;
}
这是非常长的If语句搞砸了吗?我从来没有把那么多的OR放在一个如果。
当我输入任何类型的糖浆时,控制台会回来。
Would you like Syrup?(Y/N)
y
Which syrup would you like?
Hot fudge, Chocolate, Caramel, Strawberry
caramel
You entered:
Not a valid choice. You now have Hot Fudge as your syrup.
注意:它会等到我输入一个值。那就是为什么我有
syrupChoice = keyboard.nextLine();
keyboard.nextLine();
但无论我输入什么,它都会出现空白。我显然希望它能正确读取输入并打印正确的值。 (如果数据无效,请更改为热门软糖。)
编辑**我现在将代码更改为:
System.out.println("Would you like Syrup?(Y/N)");
String wantSyrup = keyboard.next();
char syrupWant = wantSyrup.charAt(0);
switch (syrupWant){
case 'y':
System.out.println("Which syrup would you like?");
System.out.println("Hot fudge, Chocolate, Caramel, Strawberry");
syrupChoice = keyboard.nextLine();
keyboard.nextLine();
System.out.println("You entered: "+syrupChoice);
if(syrupChoice.equalsIgnoreCase(hotFudge)
|| syrupChoice.equalsIgnoreCase(chocolateSyrup)
|| syrupChoice.equalsIgnoreCase(caramel)
|| syrupChoice.equalsIgnoreCase(strawberrySyrup))
{
System.out.println(syrupChoice);
}else{
System.out.println("Not a valid choice. You now have Hot Fudge as your syrup.");
syrupChoice = hotFudge;
}
break;
default: break;
}
结果仍然相同
答案 0 :(得分:0)
有一些小问题。首先,|
是按位或运算符,||
是逻辑或运算符。你也有一些无关的keyboard.nextLine()
。
System.out.println("Would you like Syrup?(Y/N)");
String wantSyrup = keyboard.nextLine();
char syrupWant = wantSyrup.charAt(0);
switch (syrupWant){
case 'y':
System.out.println("Which syrup would you like?");
System.out.print("Hot fudge, Chocolate, Caramel, Strawberry: ");
syrupChoice = keyboard.nextLine();
System.out.print("You entered: ");
if(syrupChoice.equalsIgnoreCase(hotFudge)
|| syrupChoice.equalsIgnoreCase(chocolateSyrup)
|| syrupChoice.equalsIgnoreCase(caramel)
|| syrupChoice.equalsIgnoreCase(strawberrySyrup))
{
System.out.println(syrupChoice);
}else{
System.out.println("Not a valid choice. You now have Hot Fudge as your syrup.");
syrupChoice = hotFudge;
}
break;
default: break;
}
答案 1 :(得分:0)
用if语句中的逻辑OR:|
替换二进制OR:||
:
if((syrupChoice.equalsIgnoreCase
(hotFudge)) || (syrupChoice.equalsIgnoreCase
(chocolateSyrup)) || (syrupChoice.equalsIgnoreCase
(caramel)) || (syrupChoice.equalsIgnoreCase
(strawberrySyrup))){
System.out.println(syrupChoice); }