Java 摄氏/华氏转换错误
很抱歉,我的初学者犯了错误,但我编写了一个计算器,可以将华氏温度转换为摄氏温度,将摄氏温度转换为华氏温度,但我一直遇到以下错误:Java 摄氏/华氏转换错误,java,Java,很抱歉,我的初学者犯了错误,但我编写了一个计算器,可以将华氏温度转换为摄氏温度,将摄氏温度转换为华氏温度,但我一直遇到以下错误: Exception in thread "main" java.lang.NumberFormatException: For input string: "69C" at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1241) at java.lang.Dou
Exception in thread "main" java.lang.NumberFormatException:
For input string: "69C"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1241)
at java.lang.Double.valueOf(Double.java:504)
at Converter.main(Converter.java:39)
这是我的代码,希望您能帮助:
import java.util.Scanner;
public class Converter {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Welcome to the Fahrenheit/Celsius Converter!");
System.out.println("To convert, type in your temperature and the
identify if you are using fahrenheit or celsius.");
System.out.println("Example: 69F or 69C F = Fahrenheit C = Celsius");
String temperature;
char f = 'f';
char c = 'c';
double answer , temp;
temperature = keyboard.nextLine();
if (temperature.contains("F")) {
temperature = temperature.replace(f , ' ');
temp = Double.valueOf(temperature);
answer = temp - 30 / 2;
System.out.println("Poof! The temperature is " + answer + "C");
} else {
System.out.println("You entered the temperature wrong!");
}
if (temperature.contains("F")) {
temperature = temperature.replace(f , ' ');
temp = Double.valueOf(temperature);
answer = temp - 30 / 2;
System.out.println("Poof! The temperature is " + answer + "C");
} else {
System.out.println("You entered the temperature wrong!");
}
if (temperature.contains("C")) {
temperature = temperature.replace(c , ' ');
temp = Double.valueOf(temperature);
answer = temp + 30 * 2;
System.out.println("Poof! The temperature is " + answer + "F");
} else {
System.out.println("You entered the temperature wrong!");
}
if (temperature.contains("c")) {
temperature = temperature.replace(c , ' ');
temp = Double.valueOf(temperature);
answer = temp + 30 * 2;
System.out.println("Poof! The temperature is " + answer + "F");
} else {
System.out.println("You entered the temperature wrong!");
}
}
}
你不能把69C转换成数字,可以吗。替换是区分大小写的 试一试
当然,您可以将变量更改为“C”您不能将69C转换为数字,可以吗。替换是区分大小写的 试一试
当然,您可以将变量更改为“C”该错误会告诉您需要知道的所有信息-一直到行号!。“69C”不是整数,所以当您试图解析它时,它不起作用 错误会告诉您需要知道的一切-一直到行号!。“69C”不是整数,所以当您试图解析它时,它不起作用 我想您需要的是f='f'而不是f'。如果您不想同时检查这两个参数,请使用
String.toLowercase()
或String.toUppercase()
cases@vandale它在代码中检查像if(temperature.contains(“F”))@user2310289是的,但是如果他不想同时检查“C”和“c”一样,然后他可以转换大小写并缩短代码(虽然他似乎只检查“F”),我想你需要的是F='F'而不是“F”。使用String.toLowercase()
或String.toUppercase()
打开温度
如果您不想同时检查两者cases@vandale它是在代码中检查像if(temperature.contains(“F”))@user2310289是的,但是如果他不想像他那样同时检查“C”和“C”,那么他可以转换大小写并缩短代码(他似乎只检查“F”)但是)我忘了提到,当您尝试将f转换为c时,这可以正常工作。你只是不能把c转换成f。我忘了提到,当你试图把f转换成c时,这个方法很好用。你不能从c到f。
temperature = temperature.replace('C' , ' ');