我的任務是爲用戶輸入郵編創建一個條形碼。如果用戶輸入以0開始的郵政編碼(即05123)或校驗位爲0(即10027)的郵政編碼,我無法找到一種方法,以使它給我一個正確的結果。任何人都有建議?我在初學java班。當郵政編碼從0開始或以0結尾時,程序不運行
public class Zipcode{
private String zipcode = "";
private String barcode = "";
private String tempCode = "";
private int zipnum = 0;
private int zipnumForCD = 0;
private int checkDigit = 0;
private int reversedZip = 0;
private int digitSum = 0;
public Zipcode(int zip_number){
zipnum = zip_number;
zipnumForCD = zip_number;
getCheckDigit();
createUpdatedZip();
createBarcode();
}
public Integer getCheckDigit(){
while (zipnumForCD > 0){
digitSum = digitSum + zipnumForCD % 10;
zipnumForCD = zipnumForCD/10;
}
if (digitSum % 10 == 0)
{
checkDigit = 0;
}
else
{
checkDigit = 10 - digitSum % 10;
}
return checkDigit;
}
public void createUpdatedZip(){
zipnum = Integer.valueOf(String.valueOf(zipnum) + String.valueOf(checkDigit));
for (int i = zipnum; i !=0; i /= 10){
reversedZip = reversedZip * 10 + i % 10;
}
}
public void createBarcode(){
while (reversedZip > 0){
switch (reversedZip % 10)
{
case 0:
tempCode = "||:::";
break;
case 1:
tempCode = ":::||";
break;
case 2:
tempCode = "::|:|";
break;
case 3:
tempCode = "::||:";
break;
case 4:
tempCode = ":|::|";
break;
case 5:
tempCode = ":|:|:";
break;
case 6:
tempCode = ":||::";
break;
case 7:
tempCode = "|:::|";
break;
case 8:
tempCode = "|::|:";
break;
case 9:
tempCode = "|:|::";
break;
default:
break;
}
reversedZip = reversedZip/10;
barcode += tempCode;
}
barcode = "|" + barcode + "|";
}
public String getBarcode(){
return barcode;
}
}
,這裏是我的測試類:
import java.util.Scanner;
public class ZipTest{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Please enter a ZIP code: ");
int zip = input.nextInt();
Zipcode code = new Zipcode(zip);
System.out.println("The bar code: ");
System.out.println(code.getBarcode());
}
}
井,'int' doesn't有前導零,所以你可能要重新考慮該郵政編碼表示的是由'int'。我將切換到「String」。 – SomeJavaGuy
@KevinEsche哦,這是真的!但如果它不是一個整數,你將如何去處理所有這些方法?即必須將郵政編碼除以10,等等。 –
@jaynepants你不用10除,你用'charAt()'一次提取一個數字字符。 – Andreas