gpt4 book ai didi

java - 将对象分配给数组引用

转载 作者:行者123 更新时间:2023-12-01 07:28:33 25 4
gpt4 key购买 nike

//employee class  
public class Employee {


//properties
private String name;
private int age;
private int salary;


//constructors
public Employee(String name,int age, int salary){
this.name = name;
this.age = age;
this.salary = salary;
}

public Employee(Employee instance){
name = instance.name;
age = instance.age;
salary = instance.salary;
}

//Methods

//getter and setter methods
public String getName(){
return name;
}
public int getAge(){
return age;
}

public int getSalary(){
return salary;
}

public void setName(String name){
this.name = name;
}

public void setAge(int age){
this.name = name;
}

public void setSalary(int salary){
this.salary = salary;
}

//toString
public String toString(){
String result;
result = name + ", " + age + ", $" + salary;
return result;
}
}


//company management
import java.util.Scanner;
public class CompanyManagement {

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Employee[] employeeList;
employeeList = new Employee[20];
String name;
int age;
int salary;
int choice;
int i;

i =0;

do{

System.out.println( "Welcome to the Company Management System. Please enter your choice" + "\n(1)Add Employee" + "\n(2)Delete Employee" + "\n(3)Change Employee Salary" + "\n(4)Exit" + "\nChoice: ");
choice = scan.nextInt();

if(choice == 1)
{

System.out.println( "Please enter employee name: ");
name = scan.nextLine();
name = scan.nextLine();

System.out.println( "Please enter employee age: ");
age = scan.nextInt();

System.out.println( "Please enter employee salary: ");
salary = scan.nextInt();

employeeList[i] = new Employee(name,age,salary);


for(int k = 0;k<=i;k++)
System.out.println(employeeList[i] );
i++;

}

if(choice == 2)
{

}

if(choice ==3)
{

}


}while(choice!=4);
}
}

为什么下面的代码在循环重复时不每次都分配一个新的引用,而是分配数组所有索引的最后一个值。如何解决这个引用问题?

 employeeList[i] =  new Employee(name,age,salary); 

最佳答案

你的代码工作正常。只是代替:

 System.out.println(employeeList[i]);

 System.out.println(employeeList[k]);

关于java - 将对象分配给数组引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20521632/

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