我只是在学习Java,并且完全被这些代码所困扰。我环顾四周,但语言知识的一部分是知道要问的正确问题,而且我已经没有想法去搜索了。一切看起来都不错,但我希望一个更有经验的人能够教育我一点点。
每当我执行此代码或逐步执行时,对于100到213(无论摄氏温度或华氏温度)的温度,Else If将始终运行。任何人都可以告诉我为什么会这样,或者让我进入正确的思维框架?这是代码:
package chapter.pkg3;
import java.util.Scanner;
public class Chapter3 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Please enter the temperature: ");
double temp = in.nextDouble();
System.out.print("Please enter the temperature measurement, C or F: ");
String measure = in.next();
if (measure.equals("C"))
{ measure = "Celsius";}
else
{measure = "Fahrenheit";}
if ((temp <= 0 && measure.equals("C")) || (temp <= 32 && !measure.equals("C")))
{
System.out.print("The temperature is " + temp + " " + measure + ". The water
is freezing!");
}
if ((temp <= 100 && measure.equals("C")) || (temp <= 212 && !measure.equals("C")))
{
System.out.print("The temperature is " + temp + " " + measure + ". The water
is liquid.");
}
if ((temp > 100 && measure.equals("C")) || (temp > 212 && !measure.equals("C")))
{
System.out.print("At " + temp + " " + measure + " the water has become gas.");
}
}
}
提前感谢您的帮助!
答案 0 :(得分:9)
在if
temp <= 0 && measure.equals("C")
条件下,条件measure.equals("C")
始终为false
,因为您覆盖变量{{1}的值这里:
measure
答案 1 :(得分:2)
正确检查您的密码。如果用户输入“C”,则已初始化measure =“Celcius”。所以措施的价值是“Celcius”而不是“C”.Declare另一个变量String measurement =“Celcius”; 然后在你的if else声明中:
if (measure.equals("F"))
{ measurement = "Fahrenheit";}
答案 2 :(得分:1)
之后
if ((temp <= 0 && measure.equals("C")) || (temp <= 32 && !measure.equals("C")))
{
System.out.print("The temperature is " + temp + " " + measure + ". The water
is freezing!");
}
您必须将其他if
放入其他地方,或使用return
以便不评估下一个if
。如果温度小于0,那么它也小于100。