jgmills jgmills - 5 months ago 13
Java Question

Repeat user inputs while adding it to an array list

I’m trying to ask the user if they want to add another person to array list, "list". My thought was to loop to ask, then add those inputs into an array, "inf" and then put that array within an array list. Right now when I repeat the code it just erases the previous inputs; how would I make it so it adds to the array list after each iteration?

public class test {

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

Scanner scan = new Scanner(System.in);

String ask = "no";

do {
System.out.println("Add? (yes/no)");
ask = scan.nextLine();
if (ask.equals("yes")){

//gather user info
System.out.println("Last Name: ");
String LastN = scan.nextLine();


System.out.println("First Name: ");
String FirstN = scan.nextLine();


System.out.println("# of Children:");
String Children = scan.nextLine();


System.out.println("Address:");
String Adr = scan.nextLine();

System.out.println("Phone #:");
String Pho = scan.nextLine();

Date dategather = new Date();
String Date = String.format("%tD", dategather);

//Input the data into an array
String[] inf = {LastN,FirstN,Children,Adr,Date,Pho};

ArrayList<String> list = new ArrayList<String>();

Collections.addAll(list,inf);

System.out.println(list);

}

} while (ask.equals("yes"));

}
}

Answer

You'd want to declare the list outside the do-while structure, and if you want to print each line entry - then you do that right at the end of the do-while structure:

 //here you declare the list OUTSIDE:

 ArrayList<String> list = new ArrayList<String>();

  do {
            System.out.println("Add? (yes/no)");
            ask = scan.nextLine();
            if (ask.equals("yes")){

                //gather user info
                System.out.println("Last Name: ");
                String LastN = scan.nextLine();

                System.out.println("First Name: ");
                String FirstN = scan.nextLine();

                System.out.println("# of Children:");
                String Children = scan.nextLine();

                System.out.println("Address:");
                String Adr = scan.nextLine();

                System.out.println("Phone #:");
                String Pho = scan.nextLine();

                Date dategather = new Date();   
                String Date = String.format("%tD", dategather);

                //Input the data into an array
                String[] inf = {LastN,FirstN,Children,Adr,Date,Pho};

                Collections.addAll(list,inf);
                //so here you want to display what the person just entered:
                System.out.println("You Have Entered : \n Last Name: "+LastN+"  First Name: "+FirstN+" Children : "+Children+" Address: "+Adr+" Date of Birth: "+Date+" Phone Number: "+Pho);               

            }

            } while (ask.equals("yes"));

I hope this helps you. Please give it a try and let me know.

Comments