java | 练习题(八)

列了一些幼稚园水平的 while 循环练习题

Posted by Haauleon on September 23, 2020

笔记

一、循环结构的四要素
1.初始化条件
2.循环条件 –> 是 boolean 类型
3.循环体
4.迭代条件


二、while 循环的结构

1
2
3
4
5
①
while(②){
    ③;
    ④;
}

执行过程:① - ② - ③ - ④ - ② - ③ - ④ - … - ②


三、说明
1.写 while 循环时千万不要丢了迭代条件,一旦丢了,就可能导致死循环!
2.写程序时要避免出现死循环。
3.for 循环和 while 循环是可以相互转换的!



复习题

1.写一个 while 循环打印1至5。


1
2
3
4
5
6
7
8
9
10
class WhileTest{
    public static void main(String[] args) {
        int i = 1;
        while(i<=5){
            System.out.println(i);
            i++;
        }
        System.out.println("out of while, i = " + i); // 编译通过,i = 6
    }
}



2.从键盘读入个数不确定的整数,并判断读入的正数和负数的个数,输入为0时结束程序。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/*
就是写个循环输入嘛 while(true) 一生推

说明:
1.不在循环条件部分限制次数的结构: for(;;) 或 while(true)
2.结束循环有几种方式?
    方式一:循环条件部分返回 false
    方式二:在循环体中,执行 break
*/

import java.util.Scanner;

class WhileTest{
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int countPositive = 0; 
        int countNegative = 0;
        while(true){
            System.out.print("please input: ");
            int num = scan.nextInt();
            if(num > 0){
                countPositive++;
            }else if(num < 0){
                countNegative++;
            }else{
                break;
            }
        }
        System.out.println("countPositive = " + countPositive);
        System.out.println("countNegative = " + countNegative);
    }
}