【发布时间】:2014-10-30 07:35:11
【问题描述】:
我在 java 中传递数组时遇到了问题。代码是:
package input_output;
import static java.lang.System.out;
import java.util.Scanner;
public class InputOutput {
private static Scanner sc;
public static void main(String []args){
sc = new Scanner(System.in);
out.print("Enter the length of arrays :\t");
int n = sc.nextInt();
Employee[] emp = new Employee[n];
for(int i=0;i<n;i++){
out.print("\nEnter name and age of " + (i+1) + " employee :\t");
emp[i] = new Employee();
emp[i].setName(sc.nextLine());
sc.nextLine();
emp[i].setAge(sc.nextInt());
}
Operation operate = new Operation(emp,n);
operate.printOnScreen();
}
}
class Operation{
Employee []emp;
public Operation(Employee[] emp,int n){
this.emp=emp;
for(Employee e: this.emp)
e = new Employee();
}
public void printOnScreen() {
for(Employee e : emp){
e = new Employee();
out.println("Name:\t" + e.getName() + "\t\tAge:\t" + e.getAge() + "\n");
}
}
}
Employee 类是一个简单的 bean,包含年龄和姓名的 getter 和 setter 方法。
输出来了:
名称:空
年龄:0
我的错误是什么?
现在我把构造函数改成了
public Operation(Employee[] emp, int n){
this.emp=emp;
}
并删除该行:
e = new Employee();
来自PrintOnScreen()
输出是:
姓名:
年龄:21
【问题讨论】:
-
你想用
for(Employee e: this.emp) e = new Employee();达到什么目的? -
请不要更改问题,以免导致有效答案无效。用更正的版本更改源代码是不对的。
-
是否也发布
Employee类的代码,以便我们查看getter/setter 是否正确实现?
标签: java arrays parameter-passing