我不明白为什么当我编译这段代码时我得到了不正确的邮政编码。
John Smith
486 test St.
Yahoo, MA 898 - 2597JohnSmith
486 test St.
Yahoo, MA 898 2597
代码
public class test
{
public static void main(String[] args) {
String firstName = "John";
String lastName = "Smith";
int streetNumber = 486;
String streetName = "test St.";
String city = "Yahoo";
String state = "MA";
int zip = 01602;
int zipplus4 = 2597;
System.out.print(firstName + " " + lastName + "\n" + streetNumber + " " + streetName + "\n" + city + ", " + state + " " + zip + " - " + zipplus4);
System.out.println(firstName + lastName);
System.out.println(streetNumber + " " + streetName);
System.out.println(city + ", " + state + " " + zip + " - " + zipplus4);
}
}
最佳答案
当您指定一个带有前导零的数字时,它将被视为八进制(以 8 为基数,而不是以 10 为基数的十进制或以 16 为基数的十六进制)。
01602 octal == 898 decimal
由于 Java 在设计时并未考虑到邮政编码,因此要获得所需的效果,请删除前导零,并在打印时对其进行格式化:
System.out.println(city + ", " + state + " " + new java.text.NumberFormat("00000").format(zip) + " - " + new java.text.NumberFormat("0000").format(zipplus4));
关于java不断改变第一个邮政编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5130178/