java中如何从10数到1

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26732846/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 03:11:32  来源:igfitidea点击:

How to count from 10 to 1 in java

javafor-loopdecrement

提问by Sempliciotto

For a simple Java program where I want to make the program count from 10 to 1 by incrementing of 2 or 3 or 4 how would I change this code?

对于一个简单的 Java 程序,我想通过增加 2 或 3 或 4 来使程序从 10 计数到 1,我将如何更改此代码?

public class ExampleFor {

    public static void main(String[] args) {
        // 
        for(int i = 10; i > 0; i--){
            System.out.println("i = " + i);
        }

    }
}

回答by cн?dk

Just use this method and give it the number to decrement with in param:

只需使用此方法并在参数中为其提供要递减的数字:

public static void count(int counter) {

  for(int i = 10; i > 0; i-=counter){
        System.out.println("i = " + i);
  }
}

For exmaple to decrement by 2use:

例如通过2使用递减:

count(2);

And your main will be like this:

你的主要内容将是这样的:

public static void main(String[] args) {

    count(2);// to decrement by 2
    count(3);// to decrement by 3
    count(4);// to decrement by 4

}

回答by vefthym

change the forloop to:

for循环更改为:

for (int i=10; i>0; i-=2) {
    System.out.println("i= "+i);
}

i-=2is an abbreviation for i = i-2
It means that the new value of iwill be the old value of iminus 2.
i--is an abbreviation for i = i-1, which can be also written as i-=1

i-=2是 的缩写i = i-2
表示新的值i将是旧值的i负 2。
i--是 的缩写i = i-1,也可以写成i-=1