Tristan K.
Tristan K.

Reputation: 41

Java For each loop every instance from class

I start with OOP And i have following problem: I made a new class Then I made ainstance from this class Now, for every instance I want to do something I tried it with a for each loop but it doesn't work... There are some syntax problems

This is the class:

package main;

public class command
{
    String call;
    String execute;
}

And this from the Main class:

 private static void load() {
        command greeting = new command();

        greeting.call = "hello";
        greeting.execute = "Hello Sir";


        for (command c: command) {
            System.out.println("Another command...");
        }

    }

I don't know how to make the loop or is there another way to do it?

Upvotes: 0

Views: 691

Answers (2)

Idle_Mind
Idle_Mind

Reputation: 39142

You can create a static list inside class command that the instances get added to in the constructor(s). Then you'll always have references to whatever instances are created.

Here's an example:

import java.util.List;
import java.util.ArrayList;
public class command
{

    String call;
    String execute;

    public static List<command> commands = new ArrayList<>();

    public command() {
        commands.add(this);
    }

    public command(String call, String execute)
    {
        this.call = call;
        this.execute = execute;
        commands.add(this);
    }

    public String toString() 
    { 
        return "call: " + call + " | execute: " + execute;
    } 

}

Driver class:

public class driver
{
    public static void main(String[] args)
    {
        for(int i = 1; i <=10; i++)
        {
            command c = new command("call" + i, "execute" + i);
        }

        for(command cmd: command.commands)
        {
            System.out.println(cmd);
        }
    }
}   

Output:

enter image description here

Upvotes: 1

bastantoine
bastantoine

Reputation: 592

The syntax you are using in your for loop must use a instance of a class that implements the Iterable interface. For example you can use implementations of the List interface.

For example, you can try:

private static void load() {
    command greeting = new command();

    greeting.call = "hello";
    greeting.execute = "Hello Sir";

    List<command> listOfCommands = new ArrayList<>();
    listOfCommands.add(greeting);

    for (command c: listOfCommands) {
        System.out.println("Another command...");
    }

}

Upvotes: 0

Related Questions