0

Could you please advise what is missing for my code below? My code is running but it didn't write in a file. Inputs where via textfields. Below is what i have.

public class JFrameNewAccount extends javax.swing.JFrame {

 ArrayList<BankAccount> list = new ArrayList<BankAccount>();
 BankAccount account = new BankAccount();


public JFrameNewAccount() {
    initComponents();



 }
private void btnSaveAActionPerformed(java.awt.event.ActionEvent evt) {
account.setAccountName(txt_accountname.getText());
account.setAccountNo(txt_accountnumber.getText()); 

String fileName = "bank.txt";
    FileWriter file = null;

    try {
        file = new FileWriter(fileName,true);
        PrintWriter pw = new PrintWriter(file);
        for(BankAccount str: list) {
            pw.println(str);
        }

       pw.flush();
       pw.println("\n");


    } catch(FileNotFoundException ex) {
       JOptionPane.showMessageDialog(this, "Can't create your account!");

    } catch (IOException ex) {
        Logger.getLogger(JFrameNewAccount.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
       try {
           file.close();
       } catch (IOException ex) {
           Logger.getLogger(JFrameNewAccount.class.getName()).log(Level.SEVERE, null, ex);
       }
    }

Please advise.

dyonas
  • 1
  • 4
  • 1
    I don't see a code, which adds `BankAccount` object to `list`.. – sanbhat May 29 '13 at 07:12
  • Could you please give me an example of that? – dyonas May 29 '13 at 07:14
  • looks like your `list` is empty. add backAccount to list.. `list.add(backAccount);` – sanbhat May 29 '13 at 07:15
  • it prints wrong output: it prints this on the file: finalassignment.BankAccount@b80017 It gives me an error when I'm trying to use list.add(BankAccount); `account.setAccountName(txt_accountname.getText()); account.setAccountNo(txt_accountnumber.getText()); list.add(account);` – dyonas May 29 '13 at 07:21
  • 2
    can you please update the question with above comment? – sanbhat May 29 '13 at 07:23
  • Read the post I've made below. The update 1 is what you need to read to fix the issue you're seeing i.e. the output looking like "finalassignment.BankAccount@b80017" – javatarz May 29 '13 at 07:31

1 Answers1

1

You should try posting a SSCCE next time.

Your problem is that you've created an ArrayList (viz. "list"), created an object for the ArrayList (viz. "account"), added data to the object (by calling setAccountName and setAccountNo) and tried to write everything in the ArrayList into the file.

At no point, did you set the object into the ArrayList.

I'm assuming you're trying to create a frame that sets data from the screen into the file. If so, this is what I'd do. (changes are in lines 1 and 4 of your ActionPerformed)

Note: I'm not cleaning up your code (if I could nit pick, I'd write it a bit differently). The point of the response is to show you why your code doesn't work, which is what the question is.

public class JFrameNewAccount extends javax.swing.JFrame {

    private List<BankAccount> list = new ArrayList<>();

    public JFrameNewAccount() {
        initComponents();
    }

    private void btnSaveAActionPerformed(java.awt.event.ActionEvent evt) {
        BankAccount account = new BankAccount();
        account.setAccountName(txt_accountname.getText());
        account.setAccountNo(txt_accountnumber.getText()); 
        list.add(account);

        String fileName = "bank.txt";
        FileWriter file = null;

        try {
            file = new FileWriter(fileName,true);
            PrintWriter pw = new PrintWriter(file);
            for(BankAccount str: list) {
                pw.println(str);
            }

           pw.flush();
           pw.println("\n");
        } catch(FileNotFoundException ex) {
           JOptionPane.showMessageDialog(this, "Can't create your account!");
        } catch (IOException ex) {
            Logger.getLogger(JFrameNewAccount.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
           try {
               file.close();
           } catch (IOException ex) {
               Logger.getLogger(JFrameNewAccount.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

Update: Just saw your comment. Your solution will not give you the output you need because you're attempting to write an object. You need to override it's toString. Sample below

public class BankAccount {
    private String accountName;
    private String accountNumber;

    @Override
    public String toString() {
        return "Account Name: \"" + accountName + "\"" + System.getProperty("line.separator") + "Account Number: \"" + accountNumber + "\"";
    }

    // Setters and getters here
    public String getAccountName() {
        return accountName;
    }

    public String getAccountNumber() {
        return accountNumber;
    }

    public void setAccountName(String accountName) {
        this.accountName = accountName;
    }

    public void setAccountNumber(String accountNumber) {
        this.accountNumber = accountNumber;
    }
}

Explanation: Streams only write Strings to them. If you try to put an object into System.out.println() you'll get a similarly weird output. The output you see is the default toString() implemented in the Object class in java which shows you the class name and the object's hash code. You can either customise your toString or change the way your write the object to file (by calling getters internally) or the output stream (i.e. System.out.println())

Update 2: If you want to format it with new lines between each field, you can use a "\n" or "\r\n" based on the operating system. It's best to let Java decide which one will work. One of the ways to do that is to use System.getProperty("line.separator") but there are other ways as listed in this wonderful Stack Overflow post asking about platform independent new line characters.

Community
  • 1
  • 1
javatarz
  • 1,174
  • 16
  • 30
  • This is awesome! Thank you so much!!!!! Thanks for the tips! highly appreciated!!!!. I'm having problem in getting the accountType; it was in radiobutton, i can't get it. – dyonas May 29 '13 at 07:47
  • When I'm trying to create a new line for every data, it gives me an error. how can make the output like this: Account No: 101 // then new line Accont Name: John // then new line Account Type: // then new line Initial Balance: – dyonas May 29 '13 at 08:10
  • Updated the solution to have new lines as you've requested it. If you like a solution, you should accept it and up vote it (if you can). It's a good way to show appreciation towards those who take time to help you out :) – javatarz May 29 '13 at 09:47
  • On what line you have modified? Also, how can accept it and vote it?, Sorry, but I'm new here and i don't know how accept it. Uhmm, i have a follow-up question, assuming that i have a radiobutton (for account type, Savings and Checking), how can I get the selected button? Do i have to add a getter and setter for that like with the account number and account name? – dyonas May 29 '13 at 09:59
  • Accepting an answer works as mentioned http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work You can up vote for an answer by clicking the up arrow on the left of the post you like. You can only do this if you have privileges. As for your second question, I think there is a second post open for it. Best to answer it there. Each StackOverflow question has to stay on track. Can't be answering across posts :) – javatarz May 30 '13 at 13:32