gpt4 book ai didi

java - java中如何结束if语句?

转载 作者:行者123 更新时间:2023-11-30 08:04:24 25 4
gpt4 key购买 nike

我是java初学者,正在解决华氏度和摄氏度之间转换器的问题。但是,如果有人选择第一个选项,则当该代码运行时,第二个选项会自动运行,如下所示。我做错了什么?

import java.util.Scanner;

public class FahrenheittoCelsius {

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("If you would like to convert a temperature from Fahrenheit to Celcius, enter 1.");
System.out.println("If you would like to convert a temperature from Celcius to Fahrenheit, enter 2.");
int mode = scan.nextInt();
if (mode == 1);
{
System.out.println("Enter the temperature in Fahrenheit");
int Ftemp = scan.nextInt();
int Cnewtemp = (Ftemp - 32) * 5 / 9;
System.out.println("The temperature in Celcius is " + Cnewtemp + " degrees.");
}
if (mode == 2);
{
System.out.println("Enter the temperature in Celcius");
int Ctemp = scan.nextInt();
int Fnewtemp = Ctemp * 9 / 5 + 32;
System.out.println("The temperature in Fahrenheit is " + Fnewtemp + " degrees.");
}
}

}

最佳答案

删除 if 语句后面的分号。您在它们实际开始之前结束它们,因此所有代码都会运行。

在 Java 中,括号应紧跟在右括号之后。 (之后的行也算作紧接在之后的行)

代码应如下所示:

import java.util.Scanner;

public class FahrenheittoCelsius {

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("If you would like to convert a temperature from Fahrenheit to Celcius, enter 1.");
System.out.println("If you would like to convert a temperature from Celcius to Fahrenheit, enter 2.");
int mode = scan.nextInt();
if (mode == 1)
{
System.out.println("Enter the temperature in Fahrenheit");
int Ftemp = scan.nextInt();
int Cnewtemp = (Ftemp - 32) * 5 / 9;
System.out.println("The temperature in Celcius is " + Cnewtemp + " degrees.");
}
if (mode == 2)
{
System.out.println("Enter the temperature in Celcius");
int Ctemp = scan.nextInt();
int Fnewtemp = Ctemp * 9 / 5 + 32;
System.out.println("The temperature in Fahrenheit is " + Fnewtemp + " degrees.");
}
}

}

关于java - java中如何结束if语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31363162/

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