有什么方法可以通过Java中的方法调用列表进行交互吗?

问题描述 投票:0回答:1

假设我想将可运行的这些方法调用(ahead()、turnLeft()、back() 等)放入集合列表或数组中,并且一个在另一个之后执行。这可以做到吗?顺便说一下,这是一个名为“RobotCode”的机器人游戏。 预先感谢。

import java.awt.*;
import java.util.ArrayList;

public class NeuBot extends Robot
{

    int rapidFire = 2;
    //RobotHit rbHit = new RobotHit(null);
    public String name;
    boolean firing = false;
    int trigger;
    int turnDirection = 2;
    final int MOVES = 5;
    boolean wasHit = true;
    int moveOne = 1;
    int moveTwo = 2;
    int moveThree = 3;

    ArrayList<Integer> moveLst = new ArrayList<Integer>();

    public void run()
    {

        while (true)
        {
            //Methods Defined within the Robot Class 
            ahead(100);
            back(200);
            turnLeft(180);
            turnRight(180);
            onScannedRobot(null);
            onHitRobot(null);
        }

    }

    //Robot Has Target
    public void onScannedRobot(ScannedRobotEvent e)
    {

        for (int i = 0; i < MOVES; ++i)
        {
            firing = true;
            fire(rapidFire);
            if (firing == true)
            {
                back(50);
                out.println("Moved Back"); //TestX
            }
        }
        turnRight(10);
        ahead(20);

    }

    //
    public void onHitRobot(HitRobotEvent e)
    {
        out.println("Hit");
        wasHit = true;
        if (wasHit == true)
        {
            //Move Ahead And Fire
            ahead(20);
            fire(rapidFire);
            out.print("Fired Again!");
        }

    }
}
java algorithm collections robot
1个回答
0
投票

简单的解决方案:使用

Runnable
列表,如下所示:

List<Runnable> commands = List.of(
    () -> ahead(100),
    () -> back(200),
    () -> turnLeft(180),
    () -> turnRight(180),
    () -> onScannedRobot(null),
    () -> onHitRobot(null)
);
上面创建了一个不可修改的列表,但是也可以像 in 和动态添加命令一样使用

usual 列表:

List<Runnable> commands = new ArrayList<>(): commands.add( () -> ahead(100) ); commands.add( () -> back(200) ); // ...
这些列表可以在 Java 8 Streams 中使用:

commands.forEach(Runnable::run);
或在

通常循环中:

for (Runnable command : commands) { command.run(); // additional statements, e.g. Thread.sleep(...) for some delay }
    
© www.soinside.com 2019 - 2024. All rights reserved.