How do I determine if the method was executed just before as a condition of an if statement?

Asked 1 years ago, Updated 1 years ago, 70 views

As a condition of if, I would like to create a program in which if the method before it is executed, I will do what is written in if.Specifically, the following code is available:

Please.

import java.util.Scanner;

public class Main
{
    public static void q()
    {
        System.out.println("You typed1");
    }

    public static voider()
    {
        System.out.println("You typed2");
    }

    public static void main (String[]args)
    {
        Scanner in = new Scanner (System.in);
        System.out.println("Type one or two:");
                inta=in.nextInt();

        if(a==1)
        {
            q();
        }
        else
        {
            r();
        }

        // I want to write an if statement like if q() was running here.
    }
}

java

2022-09-30 21:45

2 Answers

Isn't this easy?

boolean exec=false;   
if(a==1)
{
   q();
   exec = true;
}
else
{
    r();
}
if(exec==true)
{
   xxxx
}


2022-09-30 21:45

Java does not have the ability to easily determine if a particular method was previously executed (even in most other major languages).

Therefore, you have to manage everything yourself.

import java.util.Scanner;

public class Main {
    /** Variable that manages if q() is running */
    private static boolean isQExecuted=false;

    public static void q() {
        System.out.println("You typed1");
        isQExecuted=true;//<- Manage on your own
    }

    public static voider() {
        System.out.println("You typed2");
    }

    public static void main(String[]args) {
        Scanner in = new Scanner (System.in);
        System.out.println("Type one or two:");
        inta=in.nextInt();

        isQExecuted=false;
        if(a==1){
            q();
        } else{
            r();
        }

        // I want to write an if statement like if q() was executed here.
        if(isQExecuted){
            What to do if //q() is running?
            //...
        } else{
            // Action if not performed
            //...
        }
    }
}

However, I wonder why you wanted to make such a decision.What did you really want to judge?

What is XY Problem? Read the thread carefully in and reconsider if you are into XY Problem.Depending on the actual problem, there may be a much better solution.


2022-09-30 21:45

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.