我想知道这个节目吗?是否可以组合使用else和switch?我认为这可能是为什么如果没有从代码中删除逻辑OR,程序的最后一部分不能从发生的错误中运行。
public static void main(String[] args) {
int houseType;
int hourHome;
Scanner input = new Scanner(System.in);
System.out.println("Please select your type of residence: ");
System.out.println("Press 1 for an apartment");
System.out.println("Press 2 for a house");
System.out.println("Press 3 for a dormitory");
houseType = input.nextInt();
switch (houseType) {
case 1:
System.out.println("You entered you reside in an apartment");
break;
case 2:
System.out.println("You entered you reside in a house");
break;
case 3:
System.out.println("You entered you reside in a dormitory");
break;
default:
System.out.println("You have entered an invalid selection");
break;
}
Scanner input2 = new Scanner(System.in);
System.out.println("Please select the average number of hours you're home per day ");
System.out.println("Press 1 for 18 hours or more");
System.out.println("Press 2 for 10 to 17 hours");
System.out.println("Press 3 for 8 to 9 hours");
System.out.println("Press 4 for 6 to 7 hours");
System.out.println("Press 5 for 0 to 5 hours");
hourHome = input.nextInt();
switch (hourHome) {
case 1:
System.out.println("You entered you are home for 18 hours per day or more");
break;
case 2:
System.out.println("You entered you are home between 10 and 17" +
"hours per day");
break;
case 3:
System.out.println("You entered you are home between 8 and 9 hours per day");
break;
case 4:
System.out.println("You entered you are home between 6 and 7 hours per day");
break;
case 5:
System.out.println("You entered you are home between 0 and 5 hours per day");
break;
default:
System.out.println("You have entered an invalid selection");
break;
}
if (houseType == 1 && hourHome == 1) {
System.out.println("Based on your selections, it's recommended you get pot-bellied pig");
} else if (houseType == 1 && hourHome == 2) {
System.out.println("Based on your selections, it's recommended you get a dog");
} else
if (houseType == 1 && ((hourHome == 3 || 4 || 5)) {
System.out.println("Based on your selections, it's recommended you get a snake");
}
}
答案 0 :(得分:1)
问题不在于使用switch语句和if语句。这没什么不对。
您在此处有错误:
(hourHome == 3 || 4 || 5)
4
和5
不是布尔表达式,不能像这样使用。你可能意味着:
(hourHome == 3 || hourHome == 4 || hourHome == 5)
答案 1 :(得分:0)
您需要在代码中更改一些内容
变化:
hourHome = input.nextInt();
为:
hourHome = input2.nextInt();
变化:
(hourHome == 3 || 4 || 5)
到:
else if (houseType == 1 && ((hourHome == 3 || hourHome == 4 || hourHome == 5))){
是的,你可以在switch语句中嵌入if / else。
您还可以将单个扫描仪用于hourHome和houseType