我的节目再次遇到了同样的问题。
这次的问题是程序在59到20之间不输出任何内容。程序刚终止。据我所知,所有if语句的格式都是一样的,但也许我需要一些新的眼睛,因为我的大脑阻止了错误
以下是代码:
import java.util.Scanner;
public class LazyDaysCamp
{
public static void main (String[] args)
{
int temp;
Scanner scan = new Scanner(System.in);
System.out.println ("What's the current temperature?");
temp = scan.nextInt();
if (temp > 95 || temp < 20)
{
System.out.println ("Visit our shops!");
} else if (temp <= 95)
if (temp >= 80)
{
System.out.println ("It's good weather for swimming");
} else if (temp >=60)
if (temp < 80)
{
System.out.println ("It's good weather for tennis");
} else if (temp >= 40)
if (temp < 60)
{
System.out.println ("It's good weather for golf");
} else if (temp >= 20)
if (temp < 40)
{
System.out.println ("It's good weather for skiing");
}
}
}
}
}
}
}
我知道如果有人指出if语句有点过分,但我需要这样做(级联if)。否则我会使用逻辑运算符。
这是输出:
----jGRASP exec: java LazyDaysCamp
What's the current temperature?
100
Visit our shops!
----jGRASP: operation complete.
----jGRASP exec: java LazyDaysCamp
What's the current temperature?
85
It's good weather for swimming
----jGRASP: operation complete.
----jGRASP exec: java LazyDaysCamp
What's the current temperature?
70
It's good weather for tennis
----jGRASP: operation complete.
----jGRASP exec: java LazyDaysCamp
What's the current temperature?
50
----jGRASP: operation complete.
----jGRASP exec: java LazyDaysCamp
What's the current temperature?
30
----jGRASP: operation complete.
----jGRASP exec: java LazyDaysCamp
What's the current temperature?
15
Visit our shops!
----jGRASP: operation complete.
答案 0 :(得分:2)
你的问题在于else语句。例如,当您尝试'50'
时else if (temp >=60)
该语句返回false,甚至没有转到下面的if语句,这意味着它没有机会跟随该语句的else来获得正确的结果。
我建议只删除所有其他内容并使用if语句。
答案 1 :(得分:1)
你的一些if语句没有大括号来表示它们的条件块。这使得很难确定您实际想要完成的任务。在Java语句中,如果下一行包含应该执行的语句,则可以在if语句后省略。在您的方案中情况并非如此,上述惯例不是最佳实践。我建议在条件语句中使用大括号来表示它们的分离。
答案 2 :(得分:1)
请注意,您的几个if语句是不必要的。如果温度为>= 80
,则当您检查温度为< 80
时,温度不能超过< 80
。这已经好几次了。
问题是你的else-if-statements被作为总是为真的不必要的if语句的替代。因此,甚至永远不会评估else-if条件。
if (temp < 80) // this is unnecessary because it's previously checked, and is always true
{
System.out.println ("It's good weather for tennis");
}
else if (temp >= 40) // this is attached to the true-if and therefore isn't evaluated