所以我有這個練習題,我應該用員工的資訊創建一個陣列并將其傳遞給班級;我的代碼有問題,我似乎無法弄清楚。
代碼的目的是:將代碼中看到的資訊放入一個陣列中,然后傳遞給類中的方法,然后列印給用戶。(類中的代碼非常好,因此這里不包含它)。
如果有人可以提供幫助,那就太棒了。
謝謝你。
// 代碼。
// The Scanners.
Scanner input = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
// Taking Number Of Employees From The User.
System.out.println("How many employees are there: ");
int numberOfEmployees = input.nextInt();
//Creating An Array With The Size Of Employees Entered By The User.
Employee[] E = new Employee[numberOfEmployees];
// Filling Out Information About Employees In Array.
for(int i = 0; i <= E.length-1; i ){
System.out.println("Enter employee " i "'s name: ");
String name = scan.nextLine();
System.out.println("Enter employee " i "'s birth date: ");
String bday = scan.nextLine();
System.out.println("Enter employee " i "'s salary: ");
double salary = input.nextDouble();
System.out.println("Enter employee " i "'s overtime: ");
int overtime = input.nextInt();
E[i] = (name, bday, salary, overtime);
}
System.out.println("Employee's Information"
"\n----------------------"
"\n----------------------");
for(int i = 0; i <= E.length-1; i ){
E[i].print();
}
}
uj5u.com熱心網友回復:
這里有兩個問題需要解決。
第一,不要創建多個Scanner物件,從System.in. 我知道你這樣做了,因為這個問題(檢查出來):掃描儀在使用 next() 或 nextFoo() 后跳過 nextLine()?- 但除了創建另一個Scanner.
第二個問題在這里:
E[i] = (name, bday, salary, overtime);
你有一個Employee[]你想要填充的。但是你的語法錯了。你實際上想要創建一個new Employee(...)來填充你的陣列。
所以這一行應該是正確的(前提是Employee具有給定型別的建構式):
E[i] = new Employee(name, bday, salary, overtime);
在您的代碼片段中考慮這一點時:
Scanner scan = new Scanner(System.in);
// Taking Number Of Employees From The User.
System.out.println("How many employees are there: ");
int numberOfEmployees = scan.nextInt();
scan.nextLine(); // <- reads the newline from the console
//Creating An Array With The Size Of Employees Entered By The User.
Employee[] E = new Employee[numberOfEmployees];
// Filling Out Information About Employees In Array.
for(int i = 0; i <= E.length-1; i ){
System.out.println("Enter employee " i "'s name: ");
String name = scan.nextLine();
System.out.println("Enter employee " i "'s birth date: ");
String bday = scan.nextLine();
System.out.println("Enter employee " i "'s salary: ");
double salary = scan.nextDouble();
System.out.println("Enter employee " i "'s overtime: ");
int overtime = scan.nextInt();
// create a new employee with the entered information and save in the array
E[i] = new Employee(name, bday, salary, overtime);
}
uj5u.com熱心網友回復:
我不確定雙掃描儀。
顯而易見的是,由于您定義了一個 Employee 物件型別的空陣列,該陣列只能由 Employee 物件容納。
Employee[] E = new Employee[numberOfEmployees]
要定義一個物件,您需要為其分配記憶體,例如:
new Employee(name, bday, salary, overtime);
然后將其分配到陣列 E
E[i] = new Employee(name, bday, salary, overtime);
我希望能把事情弄清楚。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/354275.html
上一篇:獲取錯誤:二元運算子“==”不能應用于兩個“x”運算元,如何洗掉此物件陣列中的特定數量的元素
下一篇:ifelse條件沒有正確執行
