我一直在java傳遞數組中遇到問題。代碼是:在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");
}
}
}
僱員類是一個簡單的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();'來實現什麼? – Tom 2014-09-05 11:08:52
請不要更改問題,以便使有效答案無效。使用更正後的版本更改源代碼是不正確的。 – 2014-09-05 11:17:57
如何發佈'Employee'類的代碼,以便我們可以看到getter/setter是否被正確實現? – 2014-09-05 11:32:20