首页 > java > 如何用另一种方法停止运行方法?

如何用另一种方法停止运行方法? (How to stop a running method with another method?)

问题

所以这是我的大学任务,我完成了很多事情。它应该使用方法覆盖,我必须从我的类SafeRidingMower(将在解释之后插入代码)中进行,这从我的教授的类(我不能改变一件事)RidingMower延伸。

RidingMower类:

    import java.util.*;

/**
 * The riding mower class developed by the engineering department. Contains all the functionality needed
 * for a working riding mower.
 *
 */
public class RidingMower {

    private boolean rider_in_seat = false;

    private boolean is_engine_on = false;

    private boolean is_mower_enabled = false;

    private Random rn = new Random();

    /**
     * Constructor for Riding Mower which automatically launches the main menu.
     */
    public RidingMower()
    {
        mainMenu();
    }

    /** Starts the engine of the riding mower (ignition start) */
    public void start_engine()
    {
        System.out.println("<<< Starting riding mower >>>");

        is_engine_on = true;
    }

    /** Method that randomly seats and unseats a driver */
    private void sit_rider()
    {

        int random = rn.nextInt(5);

        if ( random<=1 )
             rider_in_seat = true;
        else rider_in_seat = false;       

        System.out.print("\t=>Seated? " + rider_in_seat + "\n");
    }

    /** Seat sensor. Returns true if there is a driver seated on the mower or false
     * if no driver is sitting on the mower.
     * @return 
     */
    public boolean check_seat_sensor()
    {   
        return rider_in_seat;
    }

    /** Method that engages the mower blades and begins mowing if the ignition is turned on */
    public void mow()
    {
        start_mowing();
    }

    /** Primary method that handles the mowing. Checks to see if the ignition is on then the 
      mowing starts otherwise the cutting blades are lowered and ready to mow upon engine start
      */
    private void start_mowing()
    {

        is_mower_enabled = true;

        System.out.println("Mower blade ready to mow");

        if ( !is_engine_on ) return;

        int i=1;

        while (true)
        {
            mowing(i++);

        }
    }

    /** Mower fully functioning here and blades are spinning. Simulates a rider being thrown off 
     the mower at step 50,000 */
    private void mowing(int i)
    {
        System.out.println( "Mowing..." + i);

        if ( i>50000 ) rider_in_seat = false;

        if ( rider_in_seat == false )
            System.out.println("\tOMG Mower is moving without a driver?!");

        mowing_hook();
    }

    /** Hook/Stub function called while the mower is mowing. Other departments divisions can override */
    public void mowing_hook()
    {

    }

    /** Turns off the ignition. Stops the mower if running. */
    public void stop_mower()
    {
        System.out.println("Stopping the mower.");
        System.exit(0);
    }

    /** Main menu of the mower simulation. Asks user to check/seat a driver, start the mower, 
     * begn mowing the lawn, or exiting the simulation. Method is private and can not be 
     * overriden.
     */
    private void mainMenu()
    {
        Scanner sc = new Scanner( System.in );
        int option;

        do
        {
            System.out.println();
            System.out.println("1. Is driver seated? (" + rider_in_seat +")" );
            System.out.println("2. Start mower");
            System.out.println("3. Mow the lawn");
            System.out.println("4. Stop mower (if running) and Exit.");
            System.out.println();
            System.out.println("CHOOSE 1-4");

            option = sc.nextInt();

            switch ( option )
            {        
                case 1: sit_rider();
                        break;

                case 2: start_engine();
                        if ( is_mower_enabled ) mow();
                        break;

                case 3: mow();
                        break;

                case 4: stop_mower();
                        break;
            }

        } while ( true ); // Infinite loop here. Select option #4 to exit the program.
    }
}

SafeRidingMower类:

public class SafeRidingMower extends RidingMower 
{

    @Override
    public void start_engine() {
        if (check_seat_sensor() == true)
            super.start_engine();
        else
            System.out.println("Seat sensor does not detect a driver."
                    + "Engine will not start.");
    }

    @Override
    public boolean check_seat_sensor() {
        return super.check_seat_sensor();
    }

    @Override
    public void mow() {
        if (check_seat_sensor() == true)
            super.mow();
        else if (check_seat_sensor() == false)
            System.out.println("Seat sensor does not detect a driver."
                    + " Mower will not start.");
        else
            System.out.println("Engine is not on. Cannot start mowing.");
    }

    @Override
    public void mowing_hook() {

    }
}

而驱动程序,我认为它与我所遇到的具体问题无关,但无论如何它都在这里。

public class TheLawnMowerManDriver {

public static void main(String[] args)
{

    RidingMower mower = new SafeRidingMower();

}

}

我需要做的是:在RidingMower类中,有一个我无法覆盖的方法mowing(),但是我可以覆盖mowing()方法结束时调用的方法mowing_hook()。我应该做的是当变量i = 50000时阻止割草机运行,但我不知道该怎么做。我尝试将super关键字与变量一起使用,但它不起作用(我不知道它是否应该工作,我只是在几个类之前引入了super关键字)。

有没有人知道一种方法,我可以阻止割草机/停止变量i从重写mowing_hook()方法计数?

解决方法

我找到了解决这个问题的方法。

正如我所说的,我相信或者您错过了解问题,或者您的教授正在欺骗您。

无论如何,如果我们观察mowing()方法执行,就可以停止执行indirectly

我们的想法是包装System.out并记录打印的最后一个字符串。因此,在mowing_hook()我们可以看到手表被打印并在必要时停止。

你可以在这里找到一个有效的例子:jdoodle.com/a/12KZ

综上所述:

将此类添加到您的代码中

class SystemOutWrapper extends PrintStream{
    String lastLine;

    public SystemOutWrapper(OutputStream out){
        super(out);
    }

    @Override
    public void println (String str){
        this.lastLine = str;
        super.println(str);
    }

    public String getLastLine(){
        return lastLine;
    }
}

并以这种方式覆盖方法

@Override
public void mowing_hook() {

    if (! (System.out instanceof SystemOutWrapper)){
        System.setOut(new SystemOutWrapper(System.out));
    }

    //I used 100 as the online editor limitation. But you should change to 50000
    if ("Mowing...100".equals( ((SystemOutWrapper) System.out).getLastLine())){
        System.out.println("Limite reached! Should stop now!");
        stop_mower();
    }
}

问题

So this is my university assignment which I got pretty much everything done. It is supposed to use method overriding, which I have to do from my class SafeRidingMower (will insert code after explanation) which extends from my professor's class (which I CANNOT change a single thing) RidingMower.

RidingMower Class:

    import java.util.*;

/**
 * The riding mower class developed by the engineering department. Contains all the functionality needed
 * for a working riding mower.
 *
 */
public class RidingMower {

    private boolean rider_in_seat = false;

    private boolean is_engine_on = false;

    private boolean is_mower_enabled = false;

    private Random rn = new Random();

    /**
     * Constructor for Riding Mower which automatically launches the main menu.
     */
    public RidingMower()
    {
        mainMenu();
    }

    /** Starts the engine of the riding mower (ignition start) */
    public void start_engine()
    {
        System.out.println("<<< Starting riding mower >>>");

        is_engine_on = true;
    }

    /** Method that randomly seats and unseats a driver */
    private void sit_rider()
    {

        int random = rn.nextInt(5);

        if ( random<=1 )
             rider_in_seat = true;
        else rider_in_seat = false;       

        System.out.print("\t=>Seated? " + rider_in_seat + "\n");
    }

    /** Seat sensor. Returns true if there is a driver seated on the mower or false
     * if no driver is sitting on the mower.
     * @return 
     */
    public boolean check_seat_sensor()
    {   
        return rider_in_seat;
    }

    /** Method that engages the mower blades and begins mowing if the ignition is turned on */
    public void mow()
    {
        start_mowing();
    }

    /** Primary method that handles the mowing. Checks to see if the ignition is on then the 
      mowing starts otherwise the cutting blades are lowered and ready to mow upon engine start
      */
    private void start_mowing()
    {

        is_mower_enabled = true;

        System.out.println("Mower blade ready to mow");

        if ( !is_engine_on ) return;

        int i=1;

        while (true)
        {
            mowing(i++);

        }
    }

    /** Mower fully functioning here and blades are spinning. Simulates a rider being thrown off 
     the mower at step 50,000 */
    private void mowing(int i)
    {
        System.out.println( "Mowing..." + i);

        if ( i>50000 ) rider_in_seat = false;

        if ( rider_in_seat == false )
            System.out.println("\tOMG Mower is moving without a driver?!");

        mowing_hook();
    }

    /** Hook/Stub function called while the mower is mowing. Other departments divisions can override */
    public void mowing_hook()
    {

    }

    /** Turns off the ignition. Stops the mower if running. */
    public void stop_mower()
    {
        System.out.println("Stopping the mower.");
        System.exit(0);
    }

    /** Main menu of the mower simulation. Asks user to check/seat a driver, start the mower, 
     * begn mowing the lawn, or exiting the simulation. Method is private and can not be 
     * overriden.
     */
    private void mainMenu()
    {
        Scanner sc = new Scanner( System.in );
        int option;

        do
        {
            System.out.println();
            System.out.println("1. Is driver seated? (" + rider_in_seat +")" );
            System.out.println("2. Start mower");
            System.out.println("3. Mow the lawn");
            System.out.println("4. Stop mower (if running) and Exit.");
            System.out.println();
            System.out.println("CHOOSE 1-4");

            option = sc.nextInt();

            switch ( option )
            {        
                case 1: sit_rider();
                        break;

                case 2: start_engine();
                        if ( is_mower_enabled ) mow();
                        break;

                case 3: mow();
                        break;

                case 4: stop_mower();
                        break;
            }

        } while ( true ); // Infinite loop here. Select option #4 to exit the program.
    }
}

SafeRidingMower Class:

public class SafeRidingMower extends RidingMower 
{

    @Override
    public void start_engine() {
        if (check_seat_sensor() == true)
            super.start_engine();
        else
            System.out.println("Seat sensor does not detect a driver."
                    + "Engine will not start.");
    }

    @Override
    public boolean check_seat_sensor() {
        return super.check_seat_sensor();
    }

    @Override
    public void mow() {
        if (check_seat_sensor() == true)
            super.mow();
        else if (check_seat_sensor() == false)
            System.out.println("Seat sensor does not detect a driver."
                    + " Mower will not start.");
        else
            System.out.println("Engine is not on. Cannot start mowing.");
    }

    @Override
    public void mowing_hook() {

    }
}

And the Driver, which I assume it's not relevant for the specific issue I'm having, but here it is anyway.

public class TheLawnMowerManDriver {

public static void main(String[] args)
{

    RidingMower mower = new SafeRidingMower();

}

}

What I need to do: in the RidingMower class, there is the method mowing() which I cannot override, but I can override the method mowing_hook() which is called at the end of the method mowing(). What I'm supposed to do is to stop the lawnmower from running when the variable i = 50000, but I have no idea how to do so. I tried using the super keyword with the variable, but it didn't work (I don't know if it was supposed to work or not, I was only introduced to the super keyword a few classes ago).

Does anyone know a way that I can stop the lawnmower/stop the variable i from counting from overriding the mowing_hook() method?

解决方法

I found a solution for this problem.

As I said, I believe that or you missunderstood the problem or your professor is tricking you.

Anyway, it is possible to stop the execution if we watch the mowing() method execution indirectly.

The idea is to wrapper the System.out and record the last string that was printed. So, in mowing_hook() we can see watch was printed and stop when necessary.

You can find a working example here: jdoodle.com/a/12KZ

In summary:

Add this class to you code

class SystemOutWrapper extends PrintStream{
    String lastLine;

    public SystemOutWrapper(OutputStream out){
        super(out);
    }

    @Override
    public void println (String str){
        this.lastLine = str;
        super.println(str);
    }

    public String getLastLine(){
        return lastLine;
    }
}

And override the method this way

@Override
public void mowing_hook() {

    if (! (System.out instanceof SystemOutWrapper)){
        System.setOut(new SystemOutWrapper(System.out));
    }

    //I used 100 as the online editor limitation. But you should change to 50000
    if ("Mowing...100".equals( ((SystemOutWrapper) System.out).getLastLine())){
        System.out.println("Limite reached! Should stop now!");
        stop_mower();
    }
}
相似信息