A while loop is required to continuously detect the state of a sensor and adjust the robot's posture.
However, this while loop needs to be run regularly and automatically jumps out after about 10 seconds of running.
After searching for a long time on the Internet, I still did not find any available solutions.
After studying the problem, I used date to calculate the time difference and solved the problem.
While is the most basic loop. Its structure is:
While (Boolean expression ){
// Loop content
}
As long as the Boolean expression is true, the loop continues to execute.
Source code
// Initialize the variable
Date before = new Date ();
Date now = new Date ();
// Timed cycle
While (t <= 10 // cycle time ){
// Calculate the total cycle duration
Now = new Date ();
T = (now. getTime ()-before. getTime ()/1000;
// Loop content
}
Analysis
Before defines the previous time
Now is the current time after each loop
T is the time difference, in seconds
Example
Instance
Public class Test {
Public static void main (String args []) {
Int x = 10;
While (x <20 ){
System. out. print ("value of x:" + x );
X ++;
System. out. print ("\ n ");
}
}
}
The above example compilation and running results are as follows:
Value of x: 10
Value of x: 11
Value of x: 12
Value of x: 13
Value of x: 14
Value of x: 15
Value of x: 16
Value of x: 17
Value of x: 18
Value of x: 19