PrintWriter不会输出所有字符

时间:2018-10-03 20:30:05

标签: java barcode checksum jfilechooser printwriter

public static void main(String[] args) throws FileNotFoundException {

    // Open file containing names with FileChooser dialog
    JFileChooser chooser = new JFileChooser( );
    chooser.showOpenDialog(null);
    File fileObj = chooser.getSelectedFile( );

    // Read names and write greetings, each in their own file.
    Scanner in = new Scanner(fileObj);
    PrintWriter pw;
    pw = new PrintWriter(new File("labels.txt"));
    while (in.hasNextLine( )) {
        String line = in.nextLine();
        String[ ] fields = line.split(",");
        String name = fields[0];
        String address = fields[1];
        String city = fields[2];
        String state = fields[3];
        String zipcode = fields[4];

        pw.println(name);
        pw.println(address);
        pw.println(city + ", " + state + " " + zipcode);
        pw.println(getBarCode(zipcode));
        pw.println();
    }
    in.close( );
    pw.close( );
}

public static int returnChecksum(String zipcode) {

    int sumOfDigits = 0;
    int value = 0;
    int checksum = 0;

    for(int i = 0; i < zipcode.length(); i++) {
        if (zipcode.charAt(i) != '-'){
            value = Integer.parseInt(
                    zipcode.substring(i,  (i + 1)));
            sumOfDigits += value;
        }
    }
    checksum = (10 - sumOfDigits % 10) % 10;
    return checksum;
}

public static String getBarCode(String zipcode)  {
    String chars = " 1234567890-";
    String[ ] codes = {"   ", ":::||", "::|:|", "::||:", ":|::|",
            ":|:|:", ":||::", "|:::|", "|::|:", "|:|::", "||:::" , ""};
    String retVal = "";

    for(int i = 0; i < zipcode.length( ); i++) {
        char c = zipcode.charAt(i);
        int index = chars.indexOf(c);
        String code = codes[index];
        retVal += code ;
    }
    retVal += codes[returnChecksum(zipcode)];

    return "|" + retVal  + "|";
}   

我的问题是我正在读取的地址之一的校验和为0,并且没有将其完全输出到labels.txt文件中。原来是这样的:

Meredith Baker
1343 Maple Avenue
Denver, CO 80236-2982
||::|:||:::::|:|::||::||::::|:||:|::|::|:::|:|   |

当我需要这样的结果时:

Meredith Baker
1343 Maple Avenue
Denver, CO 80236-2982
||::|:||:::::|:|::||::||::::|:||:|::|::|:::|:|||:::|

其他所有东西都很完美,所有其他地址的输出都与我想要的一样,但是只是缺少了一个细节而烦扰了我。

1 个答案:

答案 0 :(得分:0)

如果returnChecksum()返回0,则codes[0] = " "。但是,您需要与chars数组中char'0'的索引相对应的字符串。因此,请像对待其他字符一样使用indexOf。这是长版-您可以简化它:

// 0 <= checksum <= 9
int checksum = returnChecksum(zipcode);
// Convert single digit number to char
char checksumAsChar = Integer.toString(checksum).charAt(0);
// Find in string. 1 <= index <= 10
int index = chars.indexOf(checksumAsChar);
retVal += codes[index];

重新安排可能会更容易:

String chars = "0123456789-";
String[ ] codes = {"|:|::", ":::||", "::|:|", "::||:", ":|::|",
        ":|:|:", ":||::", "|:::|", "|::|:", "||:::" };