尝试用用户输入的姓名和年龄填充两个列表,然后将它们打印到控制台

Trying to populate two Lists with names and ages entered by the user, and then print them into the Console

所以,我正在尝试制作一个“无限”数组列表,其中包含用户输入的姓名和年龄,特别是当他们被问及是否要输入其他姓名和年龄时,并回答“是”。 但是,我只能得到用户最近输入的姓名和年龄。

当用户对输入另一个姓名和年龄说“不”时,我试图让程序将姓名和年龄发送到控制台。但是,它会在我回答该问题之前打印姓名和年龄。

我将post下面有问题的代码。

    String add;
    String answer;

    ArrayList<String> names = new ArrayList<>();
    ArrayList<int[]> ages = new ArrayList<>();

    do      
    {
        // Get the users name
        System.out.println("What's your name? ");
        name = keyboard.nextLine();
        
        // Get the users name
        System.out.println("What's your age? ");
        age = keyboard.nextInt();

       // Adds the names and ages from the user input into the Arrays
        names.add(name);
        ages.add(age);
        
        // Ask the user if they want to enter in another record
        System.out.println("Do you want to enter an additional record? ");
        answer = keyboard.nextLine();
    }
    
    while (answer.equals("yes"));

    do
    {
        // System.out.println(name);
        // System.out.println(age);
        /* System.out.println(Arrays.asList(print) + ", " + (ages));
         // Printing the records to different lines of the console
           System.out.println("");
        */
    for (String print : names)
        {
            // System.out.println(names);
            // System.out.println(ages);
              System.out.println(print + ", " + (ages)); 
             
            // Printing the records to different lines of the console
              System.out.println("");
              break;
        }   
    }
    while (answer.equals("no"));

此外,我询问用户是否要将姓名和年龄数组写入文件。是意味着写入文件,不意味着我写了一条消息,上面写着“感谢您的参与”。然而,如果我输入“是”或“否”,取决于我在下面的位置,它要么不给出文件提示,要么进入打印姓名和年龄的无限循环,这取决于我把它放在哪里。

String answer2;
String write;
String fileName;

ArrayList<String> names = new ArrayList<>();
ArrayList<String> ages = new ArrayList<>();


// If I put it here, it will do a infinite loop of the names and ages inputted.
// Prompt the user if they want to write to a file.
System.out.println("Do you want to write to a file? ");
answer2 = keyboard.nextLine();

do
{
 // If I put it here, it will continue to ask me the question infinitely.
          // Prompt the user if they want to write to a file.
          // System.out.println("Do you want to write to a file? ");
          //answer2 = keyboard.nextLine();
}
while (answer.equals("no"));

do
{
    // Prompt for the filename
    System.out.println("Enter your filename: ");
    fileName = keyboard.nextLine();
    //break;
    
    //PrintWriter outputFile;
    try 
    {
        PrintWriter outputFile = new PrintWriter(fileName);
        
        // Write the name(s) and age(s) to the file
        outputFile.println(names);
        outputFile.println(ages);
        
        outputFile.close();
    } 
    
    catch (FileNotFoundException e) 
    {
        // 
        e.printStackTrace();
        break;
    }
}   

while (answer2.equals("yes"));

do
{
    System.out.println("Thanks for playing!");
    break;
}

while (answer2.equals("no"));
keyboard.close();

失踪

 names.add(name);
 ages.add(age);

最后一个打印循环应该更像:

for (int i = 0; i < names.length; i++) {
    System.out.println(names.get(i) + " is " + ages.get(i) + " years old");
}

为对象的每个属性使用单独的数据结构(在本例中为列表)绝不是一个好主意。相反,为对象创建一个 class 并为您的对象创建一个数据结构(即列表),您使用输入创建该数据结构。

例如:

public record Person (String name, int age) {}

然后在你的方法的顶部:

List<Person> people = new ArrayList<>();

在你的输入循环中:

people.add(new Person(name, Integer.parseInt(age));

然后打印:

people.forEach(System.out::println);

打印使用默认的 toString() 实现,但您可以根据需要覆盖它。

不要分别存储两个姓名和年龄列表,这会使您的解决方案非常脆弱。而是使用对象的力量。

属性 nameage 必须不是通过列表索引关联,而是必须合并到一个对象中。

现在你有两个用户属性。并且您必须在添加或删除用户时同时修改两个列表。如果您决定需要第三个和第四个用户 属性 怎么办?添加更多列表不是一种选择。 User 必须是对象。

在 Java 16 语言中引入了一种特殊的 class 调用 record。记录是透明的数据载体,语法非常简洁,定义一个记录有两个属性 nameage 你只需要这一行:

public record User(String name, int age) {}

这相当于带有构造函数的 class,getter、equals/hasCodetoString()(所有这些代码都将由编译器为您生成) .

为了更好地组织代码,我建议您将添加用户和打印用户列表的功能提取到单独的方法中。

public class UserManager {
    
    public record User(String name, int age) {}
    
    public Scanner keyboard = new Scanner(System.in);
    public List<User> users = new ArrayList<>();
    
    public void startMainMenu() {
        System.out.println("""
                To add a new record enter N
                To print existing records enter P
                To exit enter Q""");
    
        boolean quit = false;
        while (!quit) {
            String command = keyboard.nextLine().toUpperCase();
            switch(command.charAt(0)) {
                case 'N' -> addNewUser();
                case 'P' -> print();
                case 'Q' -> quit = true;
            }
        }
    }
    
    public void addNewUser() {
        String answer = "no";
        do {
            System.out.println("What's your name? ");
            String name = keyboard.nextLine(); // Get the users name
            
            System.out.println("What's your age? ");
            int age = keyboard.nextInt(); // Adds the names and ages from the user input into the Arrays
            keyboard.nextLine();
            
            users.add(new User(name, age));
            
            // Ask the user if they want to enter in another record
            System.out.println("Do you want to enter an additional record? ");
            answer = keyboard.nextLine();
            
        } while (answer.equalsIgnoreCase("yes"));
        
        System.out.println("--- Main menu --- enter N, P or Q");
    }
    
    public void print() {
        for (User user: users) System.out.println(user);
        System.out.println("--- Main menu --- enter N, P or Q");
    }
}

main() - 演示

public static void main(String[] args) {
    UserManager userManager = new UserManager();
    userManager.startMainMenu();
}

写入文件

public static void writeToFile(List<String> names, List<String> ages) {
    // Prompt for the filename
    System.out.println("Enter your filename: ");
    String fileName = keyboard.nextLine();
    
    try(PrintWriter outputFile = new PrintWriter(fileName)) {
        for (int i = 0; i < names.size(); i++) {
            outputFile.println("name: " + names.get(i) + ", age: " + ages.get(i));
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}