gpt4 book ai didi

java - Java 新手 - If - Else If 问题

转载 作者:行者123 更新时间:2023-11-29 09:44:02 24 4
gpt4 key购买 nike

我刚刚开始学习 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";}

关于java - Java 新手 - If - Else If 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18523537/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com