gpt4 book ai didi

java - Switch 和 If Else 组合

转载 作者:行者123 更新时间:2023-12-01 11:03:02 24 4
gpt4 key购买 nike

我想知道这个程序? if else 和 switch 可以组合吗?我认为这可能就是如果没有从代码中删除逻辑或,除了发生错误之外,程序的最后部分无法运行的原因。

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");

}
}

最佳答案

问题不在于同时使用 switch 语句和 if 语句。这没有什么问题。

这里有一个错误:

(hourHome == 3 || 4 || 5)

45 不是 boolean 表达式,不能这样使用。您的意思可能是:

(hourHome == 3 || hourHome == 4 || hourHome == 5)

关于java - Switch 和 If Else 组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33193243/

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