我正在用 JAVA 解决一个问题,我需要执行一些操作,例如对以下格式的数字进行加法或减法:
0001
当我将它与其他数字相加时,我也想考虑 0,例如
0001 + 1 = 0002
0562 + 0001 = 0563
但是当我尝试做同样的事情时,我无法输出前面带有 0 的数字。我尝试将号码设为 String
但它不起作用。请帮助我如何考虑在数字前面加上 0。
我的代码:
Scanner in = new Scanner(System.in);
String UserInput;
String a;
System.out.println("Enter number: ");
a=in.next();
if (a.length()==4 && a.matches(".*\\d+.*")) {
UserInput=a;
}
UserInput = String.valueOf(Integer.parseInt(UserInput) + 1);
System.out.println(s1);
结果:
输入:
0001
输出:
2
最佳答案
使用System.out.format(String format, Object... args)
将结果整数格式化为四位数字:
int updatedInt = Integer.parseInt(UserInput) + 1;
System.out.format("%04d%n", updatedInt);
参见http://docs.oracle.com/javase/tutorial/java/data/numberformat.html .
关于java - 在进行某些操作时如何考虑数字前的 0 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28656930/