if (number1 + 8 == number2 || number1 - 8 == number2){
if (name1.equals(name2)){
if (cod1 == cod2){
if (some1.equals(some2)){
System.out.println("They're in the same group");
}
System.out.println("They are in the same column");;
}
System.out.println("They are in the same section");
}
System.out.println("They are in the same subgroup");
}
else{
System.out.println("They are different");
}
}
}
我怎么能改变这一点,以便我最后只收到一条消息?现在它提供所有消息或只是它们是不同的。我知道我不能实际休息,因为这不是一个循环,但我可以采取什么行动来解决这个问题?我需要重写吗?谢谢你的帮助。
答案 0 :(得分:1)
String output = "";
,然后将所有System.out.println
替换为output =
,并将字符串更改为适当的输出。此外,字符串赋值需要在嵌套的if。
然后在最外面的if else
之外,执行System.out.println(output);
String output = "";
if (number1 + 8 == number2 || number1 - 8 == number2){
output = "They are in the same subgroup";
if (name1.equals(name2)){
output="They are in the same section";
if (cod1 == cod2){
output="They are in the same column";
if (some1.equals(some2)){
output="They're in the same group";
}
}
}
}
else{
output="They are different";
}
System.out.println(output);
答案 1 :(得分:0)
if (number1 + 8 == number2 || number1 - 8 == number2) {
if ("abc".equals("def")) {
if (cod1 == cod2) {
if (some1.equals(some2)) {
System.out.println("They're in the same group");
} else
System.out.println("They are in the same column");
;
} else
System.out.println("They are in the same section");
} else
System.out.println("They are in the same subgroup");
}
else {
System.out.println("They are different");
}
在if。
中使用else条件答案 2 :(得分:0)
我不确定组,列和部分之间的关系,但是你可以做一些这样的事情,你首先检查最具体的案例。这避免了许多级别的嵌套条件。
if (some1.equals(some2)) {
System.out.println("They're in the same group");
} else if (cod1 == cod2) {
System.out.println("They are in the same column");
} else if (name1.equals(name2)) {
System.out.println("They are in the same section");
} else if (number1 + 8 == number2 || number1 - 8 == number2) {
System.out.println("They are in the same subgroup");
} else {
System.out.println("They are different");
}
仅当群组在所有列中都是唯一的时才会起作用 - 例如,检查两个生物是否是同一物种,然后扩大到检查属,然后家庭因为你赢了就有效在不同的属中具有相同的物种名称;但是使用它来测试房屋地址是否相等,首先检查街道名称是无效的,因为你将在不同的城市拥有同名的街道。