菜单驱动程序,用于添加和显示员工详细信息。 从用户那里获取员工详细信息的输入。 将其存储到数组列表中并显示。
我已将条目添加到列表中,但总是最后输入的数据会替换列表中的所有元素。 在开关案例1中获取输入并将其添加到arraylist并在另一种情况下显示它:
class Employee
{
Scanner sc = new Scanner(System.in);
int empid,n;
String empname, empdesignation, empdept, empproject;
public Employee() { }
public Employee(int id,String name,String desig,String dept,String proj)
{
this.empid=id;
this.empname=name;
this.empdesignation=desig;
this.empdept=dept;
this.empproject=proj;
}
public void setEmpNo() {
System.out.print("Enter the number of employees: ");
n = sc.nextInt();
}
public int getEmpNo() {
return n;
}
public int getID() {
return empid;
}
public void setID(int id) {
this.empid = id;
}
public String getName() {
return empname;
}
public void setName(String name) {
this.empname = name;
}
public String getDept() {
return empdept;
}
public void setDept(String dept) {
this.empdept = dept;
}
public String getDesig() {
return empdesignation;
}
public void setDesig(String desig) {
this.empdesignation = desig;
}
public String getProject() {
return empproject;
}
public void setProject(String proj) {
this.empproject = proj;
}
public void displayemp(int id, String name,
String dept, String designation, String project)
{
System.out.print("\n============================================================\n");
System.out.println("ID: " + id);
System.out.println("Name: " + name);
System.out.println("Department: " + dept);
System.out.println("Designation: " + designation);
System.out.println("Project: " + project);
System.out.print("\n============================================================\n");
}
}
public class trying
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int ch = 0, id, n, abc, count = 0, pcount = 0;
final int maxEmp=1000;
String name, designation, dept, pname, mgrname, project;
Employee emp5 = new Employee();
Project proj5 = new Project();
List<Employee> list = new ArrayList<Employee>();
List<Project> list1 = new ArrayList<Project>();
switch (ch) {
case 1:
emp5.setEmpNo();
int a = emp5.getEmpNo();
for (int i = 1; i < a+1; i++)
{
System.out.print("Enter ID: ");
id = sc.nextInt();
emp5.setID(id);
sc.nextLine();
System.out.print("Enter Name: ");
name = sc.nextLine();
emp5.setName(name);
System.out.print("Enter Department: ");
dept = sc.nextLine();
emp5.setDept(dept);
System.out.print("Enter Designation: ");
designation = sc.nextLine();
emp5.setDesig(designation);
System.out.print("Enter Project: ");
project = sc.nextLine();
emp5.setProject(project);
list.add(emp5);
}
break;
case 5:
System.out.println("Showing Employee Details:");
for(Employee e:list)
{
System.out.println(e.empid+" "+e.empname+" "+e.empdept+" "
+e.empdesignation+" "+e.empproject);
}
break;
}
} while (!(ch <= 0 || ch > 7));
}
我需要显示数组列表的所有条目,但是最后输入的数据会重复显示。
答案 0 :(得分:1)
Employee emp5 = new Employee();
这将在for循环后出现:
for (int i = 1; i < a+1; i++) {
Employee emp5 = new Employee();
....
}
您将必须创建新的员工obj。此时,您将继续更新相同的obj。
更新
在列表中添加项目后尝试创建新的obj
list.add(emp5);
emp5 = new Employee();