一个非常简单的 java 程序有问题,没有显示正确的结果

Having issue with a very simple java program, not displaying proper result

我的代码不起作用:

Scanner hello = new Scanner (System.in);
double a = 10;
double c;

System.out.print("Enter the value: ");
c = hello.nextDouble();
double f = a + c;
System.out.printf("The sum of 10 plus user entry is : ", a+c);

没有任何语法错误,没有显示错误,这是结果: 输入值:100 10 加用户条目的总和为:

所以第二行没有结果,对于程序中的命令( a+c )。但是如果我在 ( a+c ) 命令之前使用 ' %.2f ',它工作正常, 喜欢:

System.out.printf("The sum of 10 plus user entry is : %.2f", a+c);

我试图搜索“%.2f”,但了解到它仅用于确定后面的数字将显示为带两位小数的数字。 (有点圆满了,我猜)..

我完全是 Java 的菜鸟。现在开始在大学学习它。只是想知道这个概念以及为什么这个程序只在输入“%.2f”的情况下工作,而不是没有它的原因,尽管它没有显示错误。如果有人能回答就太好了。谢谢:-)

您使用了错误的功能。 你应该使用

System.out.println(myString)

或者

System.out.print(myString)

您可以将您的代码格式化为

System.out.println(myExplinationString + a+c)

Java 的 System.out.printf() 方法不附加信息;它代替了它。 '%.2f' 表示:"Replace this with the next argument, and convert it to a floating-point number 2 places precise." 删除 '%.2f' 意味着 a+c 无处可去,printf() 将丢弃它。

由于 Java 的 System.out.printf() 方法实际上是基于 C/C++ 的 printf(),您可能需要查看 this 指南.

System.outjava.io.PrintStream class that is provided as a static field of the System class. printf(String format, Object... args) is one of the methods of the PrintStream class, check this Oracle tutorial on formatting numbers. In brief, the first argument is a format string that may contain plain text and format specifiers, e.g. %.2f, that are applied to the next argument(s). All format specifiers are explained in the description of the java.util.Formatter class. Note, that double value is autoboxedDouble 的实例。