What does an integer that has zero in front of it mean and how can I print it?(前面为零的整数是什么意思,如何打印?)
问题描述
类测试{公共静态无效主要(字符串参数[]){int a = 011;System.out.println(a);}}
为什么我得到的是 9
而不是 011
?
我怎样才能得到 011
作为输出?
解决方案:
如果您希望您的整数保持值 11,那么不要花哨,只需分配 11.毕竟,符号不会改变值的任何内容.我的意思是,从数学的角度来看 11 = 011 = 11,0.
int a = 11;
格式仅在您打印时(或将 int
转换为 String
时)才重要.
String with3digits = String.format("%03d", a);System.out.println(with3digits);
格式化程序%03d"
用于添加前导零.
或者,您可以使用 printf
方法在 1 行中完成.
System.out.printf("%03d", a);
class test{
public static void main(String args[]){
int a = 011;
System.out.println(a);
}
}
Why I am getting 9
as output instead of 011
?
How can I get 011
as output?
The JLS 3.10.1 describes 4 ways to define integers.
An integer literal may be expressed in decimal (base 10), hexadecimal (base 16), octal (base 8), or binary (base 2).
An octal numeral consists of a digit 0 followed by one or more of the digits 0 through 7 ...
A decimal numeral is either the single digit 0, representing the integer zero, or consists of an digit from 1 to 9 optionally followed by one or more digits from 0 to 9 ...
In summary if your integer literal (i.e. 011
) starts with a 0, then java will assume it's an octal notation.
Solutions:
If you want your integer to hold the value 11, then don't be fancy, just assign 11. After all, the notation doesn't change anything to the value. I mean, from a mathematical point of view 11 = 011 = 11,0.
int a = 11;
The formatting only matters when you print it (or when you convert your int
to a String
).
String with3digits = String.format("%03d", a);
System.out.println(with3digits);
The formatter "%03d"
is used to add leading zeroes.
Alternatively, you could do it in 1 line, using the printf
method.
System.out.printf("%03d", a);
这篇关于前面为零的整数是什么意思,如何打印?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:前面为零的整数是什么意思,如何打印?
基础教程推荐
- 如何强制对超级方法进行多态调用? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01