while

while ,第1张

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

拜拜咯👏👏👏👏👏👏

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/724764.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-26
下一篇 2022-04-26

发表评论

登录后才能评论

评论列表(0条)

保存