Search code examples
javaarraylistprintingprogram-entry-point

How do I print the values that have been increased within an arraylist?


I have this code which is intended to take values of type double from an arraylist and increase them by a percentage amount.

public class Company {
static ArrayList<Employee> employees;

public Company() {
    Company.employees = new ArrayList<Employee>();
}


    public ArrayList<Employee> getEmployees() {
        return employees;
    }

    public void setEmployees(ArrayList<Employee> employees) {
        Company.employees = employees;
    }

        public void increaseSalaries(double rate) {
            if (rate <= 0.0) {
                throw new IllegalArgumentException();
            } else {
            for (int i = 0 ; i < employees.size() ; i++) {
                employees.get(i).increaseSalaries(rate);
                }
            }
        }

    public static void main(String[] args) {
        Company businesstown = new Company();
        HourlyEmployee george;
        MonthlyEmployee ambrose;
        george = new HourlyEmployee("George", "McClellan", "1537", 1.04);
        ambrose = new MonthlyEmployee("Ambrose", "Burnside", "1536", 741.0);
        businesstown.getEmployees().add(george);
        businesstown.getEmployees().add(ambrose);
        double increase = 20.0;
        System.out.println(businesstown);
        businesstown.increaseSalaries(increase);
        System.out.println(businesstown);

    } 

}

I want to print out the objects within the arraylist before and after the increase but I'm unsure how. The current print commands are placeholder as I know they're incorrect. I have tried other methods such as

for (Object[] array : list) {
    System.out.println(Arrays.toString(array));
}

but this hasn't worked. What would work in this instance?


Solution

  • You can use a for each loop to print out all the contents of an Array:

    for(Employee e: employees){
        System.out.println(e.getSalary());
    }