1. 程式人生 > 其它 >while迴圈語句

while迴圈語句

迴圈語句--------while迴圈語句

while迴圈語句的格式:

  while(迴圈的條件){

  迴圈的語句

}

while語句要注意的事項:

  1,while語句一般是通過一個變數去控制它迴圈的次數

   2,while迴圈語句的迴圈體程式碼如果只有一個語句的時候,那麼可以省略大括號、但是不建議去省略的。

  3,while迴圈語句後面不能加分號,不然會影響輸出的結果。

需求1:列印一串數字

程式碼:(加上了鍵盤錄入的效果)

import java.util.Scanner;public class Demo08 {

    public static void main(String[] args) {
System.out.println("shuruyigeshu: ");
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
System.out.println("lirudeshuju:"+num);

while (num>0){
System.out.println("hello word!");
num--;
}
}
}

結果:

需求2:計算1+2+3+......100的總合。

程式碼:

import java.util.Scanner;
public class Demo08 {
public static void main(String[] args) {
System.out.println("輸入一個數: ");
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
System.out.println("lirudeshuju:"+num);
int sum = 0;
while (num<=100){
sum = sum+num;
System.out.println("sun ="+sum);
num++;
}
}
}

結果:

需求3:計算1-100,7的倍數。

需求4:實現猜數字遊戲。

如何產生一個隨機數。

步驟:

  1,建立 一個隨機數物件

  2,建立一個隨機數物件的nextInt方法

  3,導包

//建立一個隨機數物件  Random ramdom = new Random();

//呼叫隨機數物件的nextInt方法,產生一個隨機數  int num(定義一個num用來接收隨機數)= random.nextInt((括號裡用來輸入隨機數的範圍));

  System.out.println("隨機數 = "+num);

需求3:

程式碼:

public class Demo04 {
public static void main(String[] args) {
int num = 1;
int sum = 0;
while (num<=100){
if (num%7==0){
sum = sum+num;
}
num++;
}
System.out.println("總合是:"+sum);
}
}
結果:

需求4:實現一個猜數字遊戲,猜錯了可以繼續猜,猜到了結束程式。

程式碼:

import java.util.Random;
import java.util.Scanner;

public class Demo09 {
public static void main(String[] args) {
//建立一個隨機數物件
Random random = new Random();
//呼叫隨機數物件的nextInt方法產生一個隨機數
int num = random.nextInt(20)+1;
//建立一個掃描器物件
Scanner scanner = new Scanner(System.in);
boolean flang = true;
while (flang) {
System.out.println("請輸入你猜的數:");
int sum = scanner.nextInt();
if (num > sum) {
System.out.println("你猜小了");
} else if (num < sum) {
System.out.println("你猜大了");
} else {
System.out.println("恭喜你猜對了");
flang = false;
}
}
}
}

結果:

控制流程語句-------do while迴圈語句

格式:

  do{

}while(判斷條件);

需求:在控制檯上列印五個hello word!。

程式碼:

public class Demo06 {
public static void main(String[] args) {
int num = 0;
while (num<5){
System.out.println("hello word");
num++;
}
}
}
結果:

while迴圈語句與do while迴圈語句的區別:

  while迴圈語句是先判斷再執行迴圈語句的,do-while迴圈語句是先執行,後判斷的。不管條件是否滿足都會執行一次的、

do-while迴圈語句:

    int num = 0;
do {
System.out.println("hello word");
num++;
}while (num<5);
}
}
結果:

需求:需要使用do-while迴圈語句算出1~100之間的偶數總合。

程式碼:

int num = 1;
int sum = 0;
do {
if (num%2==0){
sum = sum+num;
}
num++;
}while (num<101);
System.out.println("sum = "+sum);
結果: