我只是在学习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.");
}
}
}
先谢谢您的帮助!
最佳答案
在像if
这样的temp <= 0 && measure.equals("C")
条件中,条件measure.equals("C")
将始终为false
,因为您在此处覆盖了变量measure
的值:
if (measure.equals("C"))
{measure = "Celsius";}
else
{measure = "Fahrenheit";}