我有3個類:公司,部門和員工。公司由部門組成,部門由員工組成。很基本。但是,當我嘗試設置每個員工的部門,我收到以下錯誤:java:將對象添加到對象的ArrayList;得到錯誤
-
令牌「countingGuru」
- 語法錯誤,VariableDeclaratorId預期後令牌(S),錯位構建此令牌
- 語法錯誤(S )
我已經使用了錯誤,但我仍然無法弄清楚我做錯了什麼。
下面是代碼:
public class Company {
static String[] validDeptNames = {
"Accounting", "Human Resources", "Information Systems", "Marketing"
};
static Department accounting = new Department("Accounting");
static Department marketing = new Department("Marketing");
static Department infoSys = new Department("Information Systems");
static Department humanRes = new Department("Human Resources");
public static void main(String[] args) {
}
}
import java.util.ArrayList;
public class Department {
Department department;
ArrayList<Employee> employees;
Department(String deptName){
employees = new ArrayList<Employee>();
}
static Employee countingGuru = new Employee("Counting Guru", 55);
static Employee countingPro = new Employee("Counting Pro", 45);
static Employee countingSavvy = new Employee("Counting Savvy", 40);
static Employee countingNovice = new Employee("Counting Novice", 25);
static Employee salesGuru = new Employee("Sales Guru", 50);
static Employee salesPro = new Employee("Sales Pro", 48);
static Employee salesSavvy = new Employee("Sales Savvy", 38);
static Employee hiringGuru = new Employee("Hiring Guru", 58);
static Employee hiringPro = new Employee("Hiring Pro", 47);
static Employee hackingPro = new Employee("Hacking Pro", 46);
static Employee hackingGuru = new Employee("Hacking Guru", 51);
static Employee hackingSavvy = new Employee("Hacking Savvy", 38);
static Employee hackingNovice = new Employee("Hacking Novice", 23);
public void addEmployee(Employee employee){
employee.setDepartment(this);
employees.add(employee);
}
accounting.addEmployee(countingGuru);
}
public class Employee implements Comparable<Employee> {
String empName;
int empAge;
Department department;
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
String name;
int age;
public Employee(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return empName;
}
public void setName(String name) {
this.empName = name;
}
public int getAge() {
return empAge;
}
public void setAge(int age) {
this.empAge = age;
}
@Override
public int compareTo(Employee arg0) {
return 0;
}
}
只是一個普遍的說法,你有領域和getters領域,但他們沒有被宣佈爲私人。除非明確聲明,Java字段默認爲包訪問。我知道一些語言不同,特別是Objective-C是相反的(默認情況下是私有的)。讓公共/受保護領域的制定者和獲取者當然是多餘的。 – Radiodef
你的代碼是一團糟。你應該先閱讀教程。 –
@Radiodef謝謝你,我會解決這個問題。 – thatpaintingelephant