gpt4 book ai didi

java - 摄氏度到华氏度转换器程序中的语法错误

转载 作者:行者123 更新时间:2023-12-01 11:48:05 24 4
gpt4 key购买 nike

我必须允许用户选择要进行的转换以及从什么程度开始,然后打印从该程度开始直到接下来的 9 个转换(10 个转换)的转换。我必须使用回调函数来编写它。开头还有一个菜单。我在 line 处有一个“else without if”。另外,我的回调函数无法正确计算数字。如何解决此错误并修复我的回调函数?

import java.util.Scanner;

public class FahrToCel {

public static Scanner input = new Scanner(System.in);

public static void main(String[] args) {

double choice = 0;
double fahrenheit = 0;
double celsius = 0;
double answer = 0;


//print the welcome message and the menu options for the user
System.out.printf("Welcome to Candace's Fahrenheit and Celsius "
+ "convertor. ");
System.out.printf("Please choose one of the following options: \n"
+ " Press 0 to exit \n Press 1 to to convert to Celsius \n"
+ " Press 2 to convert to Fahrenheit > ");
choice = input.nextInt();

//print what happens when the user hits a button
if (choice == 0){
// the user is going to exit the game
System.out.printf("Well hopefully you can play again soon! :) ");
} else {
//perform code for the operation
for ( double i = fahrenheit; i >-100; i-=10 ){
if (choice == 1) {
// it will convert from fahrenheit to celsius
System.out.printf("Please pick a number in Fahrenheit: > ");
fahrenheit = input.nextDouble();
celsius = FahrToCel();
System.out.printf("%f ", i);
}
}
for ( double i = celsius; i >-10; i-=10 ){
if (choice == 2){
// it will convert from celsius to fahrenheit
System.out.printf("Please pick a number in celsius: > ");
celsius = input.nextDouble();
fahrenheit = CelToFahr();
System.out.printf("%f ", i);
}
}

} else {
System.out.printf("I'm sorry, I did not ask you to enter that "
+ "number. ");
}
}

public static double CelToFahr(){
double celsius = 0;
double fahrenheit = 0;
celsius = (fahrenheit - 32) * (5.0/9.0);
return celsius;
}

public static double FahrToCel( ){
//perform the conversion for fahrenheit to celsius
double celsius = 0;
double fahrenheit = 0;
fahrenheit = ((9.0/5.0) + 32) * celsius;
return fahrenheit;

}

}

最佳答案

您正在寻找这样的结构

if (choice == 0){
// ...
}
else if (choice == 1) {
for ( double i = fahrenheit; i >-100; i-=10 ){
// ...
}
}
else if (choice == 2) {
for ( double i = celsius; i >-10; i-=10 ){
// ...
}
}
else {
// ...
}

现在,您在 else 内有一些 if 语句,并且您的范围变得困惑。然后,您的循环将进入那些 else if 语句内部。另请注意,您进行了多次转换,但打印每次输入的初始值,而不是转换后的温度。

关于java - 摄氏度到华氏度转换器程序中的语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28999566/

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