while loops and do-while loop

while statement

  • The results of the conditional expression is a  boolean value , if true, the loop body is executed; if false, the cycle ends.
  • while loop is a code block, while loop can be nested and the other statements of. Including the while statement, for statement, if statement and so on.

while (conditional expression) {

  while loop

}

 

Problem: Using the while statement can be found on the n divisible number.

public  class FindNDiv {
     public  static  void main (String [] args) {
         // find the n may be divisible, if you want to find 10. 
        int n-= 10 ; 

        int dividend The = 100; // dividend 
        int divisor = 89; // divisor 

        int found = 0; // number found in 

        the while (found <n-) { // the number just found is less than 10 on the implementation of the following loop. 

            IF (% dividend The divisor == 0 ) { 
                found ++; // a find each time, to accumulate again. 
                System.out.println (dividend + "may be" + divisor + "divisible commercially as" + (dividend /divisor)); 
            } 

            dividend The ++; // Whether looking for was not found, the dividend should continue to accumulate. 
        } 
    } 
}

 

do-while statement (at least once)

  • do-while statement syntax (remember the last to add a semicolon )
  • Regardless of the result of the conditional expression of the while statement is true or false, do-while loop statement is executed at least once.

do {

  while loop

} While (conditional expression) ;

public class DoWhile {
    public static void main(String[] args) {
        do {
            System.out.println("执行一次");
        }while (false);
    }
}

Guess you like

Origin www.cnblogs.com/buildnewhomeland/p/12158227.html