gpt4 book ai didi

java - 重复用户输入,同时将其添加到数组列表

转载 作者:行者123 更新时间:2023-12-02 03:33:57 25 4
gpt4 key购买 nike

我试图询问用户是否想将另一个人添加到数组列表“list”中。我的想法是循环询问,然后将这些输入添加到数组“inf”中,然后将该数组放入数组列表中。现在,当我重复代码时,它只会删除以前的输入;我该如何制作它以便在每次迭代后添加到数组列表中?

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"));

}
}

最佳答案

您希望在 do-while 结构之外声明列表,并且如果您想打印每个行条目 - 那么您可以在 do- 的末尾执行此操作while结构:

 //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"));

希望这对您有帮助。请尝试一下并告诉我。

关于java - 重复用户输入,同时将其添加到数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37687429/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com