while (n-- > 0) 的用法

本文详细介绍了while(n-->0)和while(--n>=0)的用法,对比了它们与for循环的区别,并通过示例展示了如何在Java中实现递减计数的循环。同时讨论了与while(n!=0)的不同之处。
摘要由CSDN通过智能技术生成

while (n-- > 0) 的用法

今天下午做题时遇到了,写篇文章记录一下

while(n- - > 0) 使用后缀递减运算符,它的意思是循环n次,除了最常用的 for (int i = 0; i < n; ++i) {...} 之外,还可以写 while (n- - > 0) {...} 和 while (- -n >= 0) {...}

eg:

public class demo {
    public static void main(String[] args) {
        int n = 4;
        while (n-- > 0){
            System.out.println(n);
        }
    }
}

或者:

public class dem02 {
    public static void main(String[] args) {
        int n = 4;
        while (--n >= 0){
            System.out.println(n);
        }
    }
}

result:

 3
 2
 1
 0

顺便提一下:Java 中“while (n- ->0)” 和 “while (n! =0)”区别

  • “While(n- ->0)” 是从 n-1 到 0
  • while(n!=0) 是从n 到1

eg:

public class demo6 {
    public static void main(String[] args) {
        int n = 4;
        while (n != 0) {
            System.out.println(n);
            n--;
        }

        System.out.println("==================");
        int n2 = 4;
        while (n2-- > 0){
            System.out.println(n2);
        }
    }
    }

result:

4
3
2
1
==================
3
2
1
0

在这里插入图片描述

拜拜咯👏👏👏👏👏👏

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王同学要努力

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值