我正在尝试创建一个程序,它将打印出华氏温度。我的目标是不使用任何条件,如if语句或任何循环。
public class TemperatureConverter {
public static void main(String[] args) {
double celsius, fahrenheit;
Scanner input = new Scanner(System.in);
System.out.print("Enter the temperature in degrees Celsius: ");
fahrenheit = input.nextDouble();
celsius = 5.0/9.0 * (fahrenheit - 32);
System.out.printf(+celsius, "degrees Celsius is" +fahrenheit "degrees Fahrenheit");
}
}我收到一个错误,就是:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The method printf(String, Object...) in the type PrintStream is not applicable for the arguments (double, String)
Syntax error on token ""degrees Fahrenheit"", delete this token
at TemperatureConverter.main(TemperatureConverter.java:14)编辑:
我没有想出我需要想出的东西。当我运行这个程序时,输出如下:
在这个例子中,用户输入45作为提示符。
输入以摄氏度为单位的温度: 45 42.77777777777778摄氏度是华氏45.0度
发布于 2014-01-11 15:50:46
为了纠正你的错误:
System.out.print(celsius + "degrees Celsius is " + fahrenheit + " degrees Fahrenheit");如果您想使用printf,也可以这样做。
System.out.printf("%f degrees Celsius is %f degrees Fahrenheit",celsius,fahrenheit);我这么做的原因主要是简单的语法。字符串是双引号中的内容。例如,"blah"是一个包含单词blah的字符串。
如果您想连接两个字符串,那么在Java中使用+操作符。因此,您想要添加"foo"和"bar",就可以编写"foo" + "bar",然后得到"foobar"。
在您的尝试中,您犯了两个错误:
首先,字符串连接的意图是错误的。+ celsius不是语法错误,因为摄氏是一个数字,但是如果它是一个字符串,那么编译器在+的左边没有任何东西来连接摄氏度的值。如果你什么都不想做的话,"" + celsius就没问题了。
+ celsius实际上什么也不做,因为它是一个数字。积极还是消极都不重要。当然,-celsius会翻转标牌。如果希望始终显示正数(尽管输出结果可能不正确),则可以使用Math.abs(摄氏)。
其次,由于您使用的是System.out.printf,所以需要遵循特定的格式。例如,第一个参数必须是字符串(可能包含%d、%f、%s等),函数将替换为您提供的后续参数。
这就是我的解决方案,它两次使用%f (浮点数),我给它两样东西-- celsius和fahrenheit,它们是双倍的,Java意识到一切都很好,只是替换了其中的值。如果您想要两位小数位,可以使用%.2f之类的东西,这也是printf比普通打印或println (print +新行)的优势所在。
要解决另一个真正的问题是,您正在以摄氏计算温度,但将其保存到变量华氏温度。如果你改变了,一切都会好起来的。
System.out.print("Enter the temperature in degrees Fahrenheit: "); 发布于 2014-01-11 15:52:13
要打印输出,使用:
System.out.println(celsius + "degrees Celsius is" + fahrenheit + "degrees Fahrenheit");或
System.out.printf("%f degrees Celsius is %f degrees Fahrenheit",celsius,fahrenheit);编辑出了什么问题。
java.lang.Error: Unresolved compilation problems:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The method printf(String, Object...)printf()的语法错误,请参考链接发布于 2014-01-11 15:57:11
试着考虑以下打印语句:
System.out.println(celsius+" is degrees Celsius and " +fahrenheit+ " is degrees Fahrenheit");https://stackoverflow.com/questions/21064293
复制相似问题