FileWriter not putting 0's into my output file

54 views Asked by At

I have this being performed on a button click event The employee class has a toString method which would display everything that it took to make that object. Once it gets to print the zipcode using FileWriter though, the first 0 in place doesn't show up.

private class ButtonListenerSubmit implements ActionListener
{
    public void actionPerformed (ActionEvent event)
    {
        int phone, zipcode;
        double pay;
        String phoneString, zipcodeString, payString;
        phoneString = phoneNumberTF.getText();
        zipcodeString = zipcodeTF.getText();
        payString = payRateTF.getText();
        phone = Integer.parseInt(phoneString);
        zipcode = Integer.parseInt(zipcodeString);
        pay = Double.parseDouble(payString);

        Employee one = new Employee(fNameTF.getText(), lNameTF.getText(), addressTF.getText(), townTF.getText(), stateTF.getText(), zipcode, phone, pay);
        try {
            PrintWriter out = new PrintWriter(new FileWriter(one.lastName + one.firstName + ".txt"));
            out.println(one);
            out.close();
        } catch(IOException e) {

        }
    }
}
4

There are 4 answers

0
Patrick J Abare II On

Problem is that your zipcode is an int integers won't hold 012345 they'll automatically truncate it to 12345.

Try a string.

0
AudioBubble On

Make the data type of the zip code String

0
Md. Nasir Uddin Bhuiyan On

You should use zipcodeString as a argument in Employee class initialization. Also you will not get full phone number if you add a phone number which starts with 0 while using phone variable. Because integer avoids 0 if it is a first character. So use zipecodeString and phoneString to get full input.

Try this:

Employee one = new Employee(fNameTF.getText(), lNameTF.getText(), addressTF.getText(), townTF.getText(), stateTF.getText(), zipcodeString, phoneString, pay);
0
user3707125 On

You should add padding to your zipcode field in Employee.toString method. Replace this:

... + "ZipCode: " + zipCode + ... // or whatever code you have for this

With this:

... + "ZipCode: " + String.format("%s5", zipCode).replaceAll(" ", "0") + ...