This question already has answers here:
How can I pad an integer with zeros on the left?

(15个答案)


6个月前关闭。





在此示例中,我要这样做,以便在此范围内输入任何数字。例如,如果用户输入数字2,则帐号类似于00000002,它会自动添加0。在这种情况下可以做到吗?

System.out.println("What is your 8 digit Account Number?"); //Enter Account Number.
AccountNumber = ask.nextInt();  //user is asked for an input for the account number. I want input to fall within that range

if (AccountNumber > 00000000 && AccountNumber < 99999999) {
}
else  {
 System.out.println("Invalid Account Number \n");

 System.out.println("Re-Enter Account Number");
 AccountNumber = ask.nextInt();
}

最佳答案

不可能在整数的左边得到零。因此,在这种情况下,我建议您使用String。
String.format(“%07d”,AccountNumber)

10-07 13:23