Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a boolean true for x seconds when condition is met, then reverting it to false

Tags:

java

boolean

I'm making a boolean so if a certain condition is met, it will return true for 3 seconds, but after that it will return false again.

So it's like

private boolean timedBoolean() {

         if(//condition to set boolean true){ 
            return true;
         }

        //if condition isn't met for 3 seconds
         return false;
     }

Been thinking about this for an hour now. Researched SO before I asked.

like image 978
Matt Smith Avatar asked Dec 03 '13 08:12

Matt Smith


People also ask

How do you change a boolean from true to false?

To toggle a boolean, use the strict inequality (! ==) operator to compare the boolean to true , e.g. bool !== true . The comparison will return false if the boolean value is equal to true and vice versa, effectively toggling the boolean.

Does boolean return true or false?

In the boolean type, there are only two possible values: true and false. We can have variables and expressions of type boolean, just has we have variables and expressions of type int and double. A boolean variable is only capable of storing either the value true or the value false.

How do you make a boolean true?

boolean user = true; So instead of typing int or double or string, you just type boolean (with a lower case "b"). After the name of you variable, you can assign a value of either true or false. Notice that the assignment operator is a single equals sign ( = ).


1 Answers

Remember the moment at which your 3-second period started:

private volatile long start;

and have the method check the elapsed time:

private boolean timedBoolean() {
    if (conditionMet()) {
      start = System.nanoTime();
      return true;
    }
    return System.nanoTime()-start < TimeUnit.SECONDS.toNanos(3);
}
like image 170
Marko Topolnik Avatar answered Oct 11 '22 15:10

Marko Topolnik