gpt4 book ai didi

Java For every 循环类中的每个实例

转载 作者:行者123 更新时间:2023-12-02 05:04:31 25 4
gpt4 key购买 nike

我从面向对象编程开始我有以下问题:我开了一个新课然后我就从这门课开始现在,对于每个实例我想做一些事情我用 foreach 循环尝试过,但它不起作用......存在一些语法问题

这是类(class):

package main;

public class command
{
String call;
String execute;
}

这是来自主类的:

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

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


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

}

我不知道如何制作循环,或者还有其他方法吗?

最佳答案

您可以在类命令内创建一个静态列表,实例将添加到构造函数中。然后您将始终拥有对创建的任何实例的引用。

这是一个例子:

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;
}

}

驱动程序类别:

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);
}
}
}

输出:

enter image description here

关于Java For every 循环类中的每个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56361998/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com