0

My objective is to create a function which will write an Arraylist of Account(my class) type in a file. I have written the following code but the ArrayList myList is only adding the details specified in the second run of the loop twice..Plus for the second run it just skips the name field entry to ac.

public void builIT(){
    Scanner sc = new Scanner(System.in);
    ArrayList<Account> myList = new ArrayList<>();
    Account a = new Account();
    String name = null;
    String ac = null;
    String phone = null;
    String email = null;
    String password = null;
    double balance = 0;
    try{
        FileOutputStream fout = new FileOutputStream("c:\\Users\\srawa\\Desktop\\thisisit");
        ObjectOutputStream oos = new ObjectOutputStream(fout);
        for(int i=0;i<2;i++){                
            System.out.print("Name:");
                name=sc.nextLine();
            System.out.print("ACNO:");
                ac=sc.nextLine();
            System.out.print("Phone:");
                phone=sc.nextLine();
            System.out.print("Email:");
                email=sc.nextLine();
            System.out.print("Password:");
                password=sc.nextLine();
            System.out.print("Balance:");
                balance=sc.nextDouble();
            a.set(name,ac,phone,email,password,balance);
            System.out.println(a);
            myList.add(a);               
            System.out.println(myList);
        }

        oos.writeObject(myList);
        oos.close();
    }catch(Exception e){
        e.printStackTrace();
    }
    }

Please help. Thank you. P.S.- I'm new to Stackoverflow.

  • 2
    How many times do you call `new Account()`. What do you deduce on the number of **different** accounts the list contains? Advice: instead of using `set()` to set all the fields of your account, use a constructor. That will make your mistake impossible. And you will never have an account containing nothing. – JB Nizet Jun 25 '16 at 16:40
  • Double duplicate :) Welcome to StackOverflow, by the way. – OneCricketeer Jun 25 '16 at 16:42
  • @cricket_007 umm.. then can i get the link to the original quesiton.. – Sourabh S. Rawat Jun 25 '16 at 16:47
  • @JBNizet ok i changed the set to the constructor..all is ok..but its still skipping the step of inputting the name field for the second run of the loop. :/ – Sourabh S. Rawat Jun 25 '16 at 16:51
  • 1
    Read the duplicate questions. – JB Nizet Jun 25 '16 at 16:56

0 Answers0