如何从一个单独的类调用一个方法java

如何从一个单独的类调用一个方法java

本文介绍了如何从一个单独的类调用一个方法java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从一个单独的类中调用一个方法,但它似乎不工作,或者我做错了。我想实现的是调用我的 Race 方法,在 RacingEvent 类中我的主程序(检查

I'm trying to call a method from a separate class in java but it doesn't seem to work, or I'm doing something wrong. What I want to achieve is to call my Race method which is in the RacingEvent class to my main program (Check the comment in the main program).

以下是类:

import java.util.Random;

public class RacingEvent {
    private SimpleWindow w;
    private RaceTrack track;
    private Turtle t1 = new Turtle(w, 200, 400);
    private Turtle t2 = new Turtle(w, 300, 400);

    public RacingEvent(RaceTrack track, Turtle t1, Turtle t2) {
        this.t1 = t1;
        this.t2 = t2;
        this.track = track;
 }

    public void Race() {
        t1.penDown();
        t2.penDown();
        Random rand = new Random();

        Turtle t1 = new Turtle(w, 200, 400);
        Turtle t2 = new Turtle(w, 300, 400);

        while (t1.getY() > track.getyFinish() && t2.getY() > track.getyFinish()) {
            int turtle1 = rand.nextInt(3);
            int turtle2 = rand.nextInt(3);
            t1.forward(turtle1);
            t2.forward(turtle2);

            SimpleWindow.delay(10);
        }


        int diff1 = t1.getY() - track.getyFinish();
        int diff2 = t2.getY() - track.getyFinish();

        SimpleWindow w = new SimpleWindow(200, 100, "Winner");

        if (t1.getY() <= track.getyFinish()) {
            w.moveTo(20, 40);
            w.writeText("T1 won with a " + diff2 + " step(s) lead!");
        } else if (t2.getY() <= track.getyFinish()) {
            w.moveTo(20, 40);
            w.writeText("T2 won with a " + diff1 + " step(s) lead!");
        }
    }
}

我需要调用该方法:

public class TurtleRace {
    public static void main(String[] args) {
        SimpleWindow w = new SimpleWindow(600, 600, "TurtleRace");
        int yStart = 400;
        int yFinish = 100;

        RaceTrack track = new RaceTrack(w, yStart, yFinish);
        ColorTurtle t1 = new ColorTurtle(w, 250, yStart, java.awt.Color.RED);
        ColorTurtle t2 = new ColorTurtle(w, 350, yStart, java.awt.Color.BLUE);

        track.draw(w);
        w.waitForMouseClick();

        RacingEvent event = new RacingEvent(track, t1, t2);
        /*Call Race Method*/
    }
}


推荐答案

当你这样做

RacingEvent event = new RacingEvent(track, t1, t2);

您只是创建和实例化RacingEvent类的对象。

You are just creating and instantiating an object of the RacingEvent class.

函数调用尚未完成。

你应该写这个函数来调用函数。

You should write this to call the function.

event.Race();

希望它解决问题。

这篇关于如何从一个单独的类调用一个方法java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 23:44