SCJP-- 数字格式
给定:
public class LineUp {
public static void main(String[] args) {
double d = 12.345;
// insert code here
}
}
在第 4 行插入的哪个代码片段会产生输出 | 12.345|
?
<前><代码>A. System.out.printf("|%7d| \n", d); B、System.out.printf("|%7f| \n", d); C、System.out.printf("|%3.7d| \n", d); D. System.out.printf("|%3.7f| \n", d); E. System.out.printf("|%7.3d| \n", d); F. System.out.printf("|%7.3f| \n", d); 答案:F
printf 语句的解释是什么,为什么是 |%7d|正在给出 illegalFormatConversionException ?
谢谢
Given:
public class LineUp {
public static void main(String[] args) {
double d = 12.345;
// insert code here
}
}
Which code fragment, inserted at line 4, produces the output | 12.345|
?
A. System.out.printf("|%7d| \n", d); B. System.out.printf("|%7f| \n", d); C. System.out.printf("|%3.7d| \n", d); D. System.out.printf("|%3.7f| \n", d); E. System.out.printf("|%7.3d| \n", d); F. System.out.printf("|%7.3f| \n", d); Answer: F
What is the interpretation of the printf statements , why is the |%7d| is giving illegalFormatConversionException ?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因为 d 是双精度数,所以不能将其格式化为十进制整数。在浮点变量的情况下,如果没有显式转换以表明您知道这一事实,则不能使用“d”格式描述符可能的精度损失。
Because d is a double and it can't be formatted as a decimal integer.You can't use the "d" format descriptor in case of floating-point variables, without an explicit cast in order to signal the fact that you are aware of the possible loss of precision.
因为 %d 格式化一个整数。
来自文档:
Because %d formats an integer.
From the doc:
Formatter 类的
format()
方法采用以下形式的格式字符串:System.out.printnf()
是一种使用相同参数的便捷方法。因此,
%7d
表示[width]
为 7,[conversion]
为d
(适用于整数类型) 。在此示例中,传递的值是无法格式化为整型的double
。The Formatter class's
format()
method takes a format string of the form:System.out.printnf()
is a convenience method that uses the same arguments.So
%7d
indicates a[width]
of 7 and a[conversion]
ofd
which is for integral types. In this example, the value being passed is adouble
which cannot be formatted as an integral type.