Aker
Aker

Reputation: 59

Java, list of objects, change values in a loop

My program has 4 Computer objects with different values, from Make, Model, Productnumber, Amount, and Shelfnumber. They are coming from a class Computer which extends from class Product. I add the objects to an object list, now I need to get the Shelfnumbers (the last value in the objects) from each object and add a different amount to them depending on what the values are.

The question I have is, is there any way to go through each of the objects in a loop. The current loop only does it for the first computer object, t1. Now I would need it to get the Shelfnumber for t2, t3 and t4 in the same loop.

I.e., get t1's Shelfnumber -> check what the value is -> add to it -> get t2's Shelfnumber and do the same.

public class Main {

    public void computers() {
        ArrayList<Object> computers = new ArrayList<Object>();
        Computer t1 = new Computer("Razer", "Blade 15", "65732", 3, 12); computers.add(t1);
        Computer t2 = new Computer("Apple", "MacBook Pro", "8732", 21, 15); computers.add(t2);
        Computer t3 = new Computer("Asus", "Aspire 5", "7532", 5, 2); computers.add(t3);
        Computer t4 = new Computer("Lenovo", "Legion 5", "3437", 2, 150); computers.add(t4);
        int shelfNumber = 0;

        for (int i = 0; i < computers.size(); i++) {
            shelfNumber = t1.getShelfnumber();
            if (shelfNumber < 10) {
                shelfNumber = shelfNumber + 10;
            } else if (shelfNumber > 10 && shelfNumber < 100) {
                shelfNumber = shelfNumber + 30;
            } else {
                shelfNumber = shelfNumber + 500;
            }
        }
        System.out.println(shelfNumber);

        System.out.println(t1.toString());
        System.out.println(t2.toString());
        System.out.println(t3.toString());
        System.out.println(t4.toString());
    }

    public static void main(String[] args) {
        Main ohj = new Main();
        ohj.computers();
    }
}

Upvotes: 1

Views: 2625

Answers (1)

Mureinik
Mureinik

Reputation: 311393

You need to refer to the objects in the list, and not to t1 directly:

for (Computer t : computers) {
    shelfNumber = t.getShelfnumber();
    if (shelfNumber < 10) {
        shelfNumber = shelfNumber + 10;
    } else if (shelfNumber > 10 && shelfNumber < 100) {
        shelfNumber = shelfNumber + 30;
    } else {
        shelfNumber = shelfNumber + 500;
    }
}

EDIT:
As noted in the comment, you should define computers as a List<Computer>, not a List<Object>.

Upvotes: 4

Related Questions