由于某些原因,我的代码无法运行,说我有一些错误。
//ask for user input for the selected vehicle
if(choice == 'A' || 'a') {
System.out.println("How many miles would you like to drive the van?: ");
milesDriven = input.nextInt();
} else if(choice == 'B' || 'b') {
System.out.println("How many miles would you like to drive the honda?: ");
milesDriven = input.nextInt();
} else if(choice == 'C' || 'c') {
System.out.println("Here are the statuses of your cars!\n");
Garage.printCarStatus();
} else {
System.out.println("That is an invalid choice!");
}
答案 0 :(得分:2)
从 -
更改代码中的条件if(choice == 'A' || 'a') // the OR operation is not applicable of char values
到
if(choice == 'A' || choice == 'a') // boolean operands using OR
答案 1 :(得分:1)
您正在使用if条件不正确。 “||”运算符仅对二进制值或布尔值起作用。编写代码的正确方法是
if (choice == 'B' || choice == 'b') {
... your code here
}
答案 2 :(得分:0)
除了我上面的评论,
我建议您通过转换为大写或小写来简化代码
if ('A' == Character.toUpperCase(choice)) {
}
else if ('B' == Character.toUpperCase(choice)) {
}
//等
答案 3 :(得分:0)
您可以像if,
一样使用if语句String mychoice=String.valueOf(choice);
if(mychoice.equalsIgnoreCase("A")){
//your code here
}
这里你不关心小写或大写字符值。