0

I have a java code that runs an endless loop, over and over again, and under certain conditions, I want to insert an additional step / function call into the loop.

I defined these variables outside of the loop:

static boolean wait_activate = false; 
static long wait_tmr = -1; 
static int wait_delay = 6; 

Then, in my endless loop, when I want to enable the additional code:

if (some-condition) { 
    wait_activate = true; 
    System.out.println("activate"); 
    wait_tmr = (System.currentTimeMillis() / 1000L); 
}

And at the beginning of the loop, I have two checks to insert the additional code:

if (wait_activate && (wait_tmr + wait_delay) < (System.currentTimeMillis() / 1000L)) {
    // if wait period isn't over
    do_additional_stuff(); 
}

if (wait_activate && (wait_tmr + wait_delay) > (System.currentTimeMillis() / 1000L)) {
    // wait time is over: 
    System.out.println("Reset time: " + wait_delay); 
    System.out.println("Stored time: " + wait_tmr); 
    System.out.println("Current time: " + (System.currentTimeMillis() / 1000L)); 
    wait_activate = false; 
    wait_tmr = -1; 
}

Now, the time values are all in seconds / unixtime. (currentTimeMillis / 1000 = seconds). wait_delay is 6. That would mean, the two printlns should only be executed about 6 seconds after activating (with wait_activate = true).

However, the output is this:

activate
Reset time: 6
Stored time: 946685043
Current time: 946685045

I don't understand why. It should wait 6 seconds, according to wait_delay. However, the difference between the stored time and the current time is only 2 seconds. Even if I increase the wait_delay. Am I doing something wrong? Is this a bug in Java or in the weird JRE version I (have to) use (running this on LeJOS 0.9.0-beta on a LEGO EV3)?

Am I making a complete "beginner mistake" and just don't see it? Or is something else broken there?

4

2 回答 2

1

It looks like the problem is with comparison operators, the first if condition should have > instead of <, while the second if condition should contain < instead of >. You may also turn the second "if" condition into an "else" of first "if" condition to avoid any further confusion.

于 2018-02-09T09:22:55.177 回答
0

You may not want below assignment to happen over & over inside your endless loop while the wait_activate is ON. Maybe wrapping this assignment in right if condition will help.

wait_tmr = (System.currentTimeMillis() / 1000L);

于 2018-02-09T07:25:31.653 回答