Java Tutorial/Statement Control/While Loop — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
 
м (1 версия)
 
(нет различий)

Текущая версия на 08:19, 1 июня 2010

Java"s "labeled while" loop

   <source lang="java">

public class MainClass {

 public static void main(String[] args) {
   int i = 0;
   outer: while (true) {
     System.out.println("Outer while loop");
     while (true) {
       i++;
       System.out.println("i = " + i);
       if (i == 1) {
         System.out.println("continue");
         continue;
       }
       if (i == 3) {
         System.out.println("continue outer");
         continue outer;
       }
       if (i == 5) {
         System.out.println("break");
         break;
       }
       if (i == 7) {
         System.out.println("break outer");
         break outer;
       }
     }
   }
 }

}</source>



Outer while loop
i = 1
continue
i = 2
i = 3
continue outer
Outer while loop
i = 4
i = 5
break
Outer while loop
i = 6
i = 7
break outer


The while Statement

  1. One way to create a loop is by using the while statement.
  2. Another way is to use the for statement

The while statement has the following syntax.



   <source lang="java">

while (booleanExpression) {

   statement (s)

}</source>





Using the while loop to calculate sum

   <source lang="java">

public class MainClass {

 public static void main(String[] args) {
   int limit = 20;
   int sum = 0;
   int i = 1;
   while (i <= limit) {
     sum += i++;
   }
   System.out.println("sum = " + sum);
 }

}</source>



sum = 210


While loop with double value

   <source lang="java">

public class MainClass {

 public static void main(String[] args) {
   double r = 0;
   while(r < 0.99d) {
     r = Math.random();
     System.out.println(r);
   }
 }

}</source>



0.4377278997305387
0.2688654455422754
0.36392537297385574
0.15254413511361042
0.6688621030424611
0.143156733550304
0.3867695752401421
0.6348496031126075
0.8262243996358971
0.057290108917235516
0.48887104413122007
0.9181002018325309
0.03580026338719999
0.6915245271034702
0.06281957479185263
0.7484170566879976
0.08309381253696246
0.7708638307798187
0.6586973690207539
0.3606321940413979
0.17404632324149583
0.1007512703731156
0.7971297767971545
0.4461084890266951
0.8627269068871244
0.04984737498714209
0.2597921665157922
0.5410470601800582
0.5779541886682865
0.1847556794086489
0.32127067165147705
0.12266607697656651
0.62729812639505
0.12191275953517977
0.72308829958122
0.5766115831015479
0.03444891261877858
0.3034596140603594
0.058872682884219985
0.85618745813345
0.07472991871327217
0.32676415639620604
0.6390549075075913
0.09246846051500635
0.9135703200463736
0.661365290176903
0.834153688687532
0.6340862529502882
0.3240420706550172
0.07246065490188025
0.35761285323105796
0.9964556875646731