Method for running the while loop in JAVA

Source: Internet
Author: User


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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.