1

我刚刚学习 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.");
        }
  }

}

在此先感谢您的帮助!

4

3 回答 3

9

在您的if条件temp <= 0 && measure.equals("C")中,条件measure.equals("C")将始终false是因为您在此处覆盖了变量的值measure

if (measure.equals("C"))
   {measure = "Celsius";}
else 
   {measure = "Fahrenheit";}
于 2013-08-30T01:36:06.413 回答
2

正确检查您的代码。如果用户输入“C”,则您已初始化 measure = “Celcius”。所以 measure 的值是“Celcius”而不是“C”。声明另一个变量 String measure="Celcius"; 然后在你的 if else 语句中:

 if (measure.equals("F"))
        { measurement = "Fahrenheit";}
于 2013-08-30T01:46:29.877 回答
1

之后

 if ((temp <= 0 && measure.equals("C")) || (temp <= 32 && !measure.equals("C")))
    {
    System.out.print("The temperature is " + temp + " " + measure + ".  The water
    is freezing!");
    }

您必须要么将其他ifs 放入 else 中,要么使用 areturn以免评估下一个ifs。如果温度小于 0,那么它也小于 100。

于 2013-08-30T01:38:49.693 回答