gpt4 book ai didi

java - 如何让我的 java ArrayList 正确显示?

转载 作者:行者123 更新时间:2023-12-02 03:51:50 24 4
gpt4 key购买 nike

我有一个类,用户可以在其中输入有关用户确定的员工数量的员工信息(名字和姓氏、地址、雇用日期)。

import java.util.ArrayList;
import java.util.Scanner;

public class Employee {
public static void main(String [] args){
String employeeName = null;
String employeeAddress = null;
String hireDate = null;

Scanner userInput = new Scanner(System.in);
System.out.println("How many employees would you like to enter information for?");
int numEmployees = userInput.nextInt();

for( int i = 0; i < numEmployees; i++) {
Scanner input = new Scanner(System.in);
System.out.println("Enter employees first name: ");
String firstName = input.nextLine();
System.out.println("Enter employees last name: ");
String lastName = input.nextLine();
System.out.println("Enter street employee lives on:");
String street = input.nextLine();
System.out.println("Enter city employee lives in:");
String city = input.nextLine();
System.out.println("Enter state employee lives in:");
String state = input.nextLine();
System.out.println("Enter employee's zip code:");
String zip = input.nextLine();
System.out.println("Enter month employee was hired:");
String month = input.nextLine();
System.out.println("Enter day employee was hired:");
String day = input.nextLine();
System.out.println("Enter year employee was hired:");
String year = input.nextLine();

Name name = new Name(firstName, lastName);
Address address = new Address(street, city, state, zip);
Date date = new Date(month, day, year);

employeeName = name.getName();
employeeAddress = address.getAddress();
hireDate = date.getDate();

ArrayList<String> obj = new ArrayList<String>();
obj.add(employeeName);
obj.add(employeeAddress);
obj.add(hireDate);
System.out.println(obj);
}
}
}

我试图让程序通过用户提示,获取该信息并将其放在 ArrayList 中的某个位置,然后重复用户之前确定的任意次数,并在最后一次显示所有内容。像这样的事情:

FirstName LastName, Address, Hire Date
FirstName LastName, Address, Hire Date

等等。现在,我的代码将运行用户提示,显示该提示,然后运行下一轮提示并显示该提示:

Enter Name:
Name
Enter Address:
Address
Enter Hire Date:
Hire Date

[Name, Address, Hire Date]

Enter Name:
Name
Enter Address:
Address
Enter Hire Date:
Hire Date

[Name, Address, Hire Date]

我意识到这是因为我的数组和数组显示位于 for 循环内,但是当我将数组移到循环外时,我没有显示。当我仅将数组显示移到循环之外时,我的代码无法编译。

最佳答案

移动此行:

System.out.println(obj);

跳出for循环。并使用List来包含ArrayList。然后将其显示在单独的 for 循环中:

List<ArrayList<String>> objs = new ArrayList<ArrayList<String>>(); //use list of objs
for( int i = 0; i < numEmployees; i++ )
{
//all the inputs

ArrayList<String> obj = new ArrayList<String>();
obj.add(employeeName);
obj.add(employeeAddress);
obj.add(hireDate);
objs.add(obj);

}

for( int i = 0; i < numEmployees; i++ ) //for loop just to display
System.out.println(objs.get(i)); //display each element here

关于java - 如何让我的 java ArrayList 正确显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35809224/

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