Krzysztof Ibisz Krzysztof Ibisz - 9 months ago 27
Java Question

How'd I refer to list size?

It's my first time on stackoverflow, forgive me my terrible formating I swear I tried everything...

So I got this exercise:

I want to add employee objects of class Employee to my list and print it's content using method. In class Company at the loop

for(int i=0; i<employeeList.size(); i++)
I got unexpected token at
for
, cannot resolve symbol 'size' at
employeeList.size();
and unknown class:'i', identifier expected, unexpected token at
i++
. In run
company.showEmployees
cannot resolve symbol 'company.

It makes me feel bad but I have absolutely no idea what to do with that...

public class Employee {

protected String name;
protected String surname;
protected int dateOfBirth;
protected int experience;

public Employee(String name, String surname, int dateOfBirth, int experience) {
this.name = name;
this.surname = surname;
this.dateOfBirth = dateOfBirth;
this.experience = experience;
}
}

import java.util.ArrayList;
import java.util.List;

public class Company {

public Company(List<Employee> employeeList) {
this.employeeList = employeeList;
}

public static List<Employee> employeeList = new ArrayList<Employee>();

Company company = new Company(employeeList);

for(int i=0; i<employeeList.size(); i++) {
employeeList.add(new Employee("Mariusz "," Kowalski ",1996,5));
employeeList.add(new Employee("Krzysztof ", " Nowak ", 1990, 5));
employeeList.add(new Employee("Robert ", " Klimczyk ", 1985, 10));
}

public static void showEmployees() {
for(int i=0; i<employeeList.size(); i++)
System.out.println(employeeList.get(i));
}
}


public class Run {

public static void main (final String[] args) {

company.showEmployees();

}

}

Answer Source

You cannot have statements (such as a for loop) outside of a method.

Maybe it should go into the constructor in your case? Or into the main method?

And why is the employeeList static? That would mean that all companies share the same group of employees.