我有以下 Java 代码:
import java.util.Scanner;
public class C2F_F2C {
public static void main(String[] args) {
boolean isNotValid = false;
double toConvert;
do {
System.out.print("What do you want to convert from Celsius to Fahrenheit? ");
Scanner in = new Scanner(System.in);
String toConvertString = in.nextLine();
isNotValid = false;
try {
toConvert = Double.parseDouble(toConvertString);
}
catch (java.lang.NumberFormatException e) {
System.out.println("Error: Not a number");
isNotValid = true;
}
} while (isNotValid);
double inCelsius = toCelsius(toConvert);
System.out.println("The value " + toConvert + " in Celsius is " + inCelsius);
}
public static double toCelsius( double fahrenheit ) {
double celsius = (fahrenheit -32)*(5/9);
return celsius;
}
}
但是,当我运行它时,它会引发以下错误:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The local variable toConvert may not have been initialized
The local variable toConvert may not have been initialized
at C2F_F2C.main(C2F_F2C.java:24)
我在 do..while 循环之前初始化了变量,并在 try..catch 循环中设置了值。似乎尚未设置变量。抱歉,如果这是一个相当基本的问题,但我似乎无法弄清楚。