for while循环结构

循环结构
while循环
while循环格式
while(boolean){
循环内容
}
例:输入一个整数,从一开始,到他自己

public class Test {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int s = scanner.nextInt();
        int i = 1;
        while (s>0) {

            System.out.println(i);
            i++;
            s--;
        }

    }
}
输入结果
请输入一个整数
5
1
2
3
4
5

注意while里的条件不要写成死循环

public class Test {
    public static void main(String[] args) {
        while (true) {
            System.out.println(1);
        }
        }
}

while特殊循环(do while循环)

public class Test {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入一个整数");
        int s = scanner.nextInt();
        int i = 1;
        do {

            System.out.println(i);
            i++;
            s--;
        }while (s>0);

    }
}
运算结果
请输入一个整数
5
1
2
3
4
5
public class Test {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入一个整数");
        int s = scanner.nextInt();
        int i = 1;
        do {
            i++;
            System.out.println(i);
            s--;
        }while (s>0);

    }
}
上面代码do while与上面代码有小改动,请注意
do while循环至少结果会运行一次
运行结果
请输入一个整数
-8
2

for循环结构
for循环格式
for(初始条件;判断语句;对初始化条件操作){
循环体
}
例:输入一个整数,从一开始,到他自己

public class Test {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入一个整数");
        int s = scanner.nextInt();
        for (int i = 1; i <=s; i++) {
            System.out.println(i);
        }
        }
}
运行结果
请输入一个整数
5
1
2
3
4
5
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值