java 如何在java中执行1条命令x次

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32687538/
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-11-02 20:36:56  来源:igfitidea点击:

How to execute 1 command x times in java

javaloops

提问by Wilhelmus

I'd like to ask how to execute 1 command multiple times

我想问一下如何多次执行1个命令

for example this code

例如这个代码

System.out.println("Hello World!");

I want to run it 500 times how do i do it ?

我想运行它 500 次,我该怎么做?

Thank You

谢谢

Regards Wilhelmus

问候威廉姆斯

回答by teh.fonsi

With Java 8 Streams you could do it like that

使用 Java 8 Streams 你可以这样做

IntStream.range(0, 500).forEach(i -> System.out.println("Hello World!"));

回答by Mohammad Ghazanfar

Use a loop,

使用循环,

for(int i = 0; i < 500; ++i)
    System.out.println("Hello World!");


Please go through a basic Java tutorial. One can be found here

请阅读基本的 Java 教程。一个可以在这里找到

回答by Arthur

You would use a for loop.

您将使用 for 循环。

for(int i = 0; i < 500; i++)
     //the code you would like to loop here

回答by soorapadman

Try like this :

像这样尝试:

class ForDemo {
    public static void main(String[] args){
         for(int i=0; i<500; i++){
              System.out.println("Hello world");
         }
    }
}

回答by JoSSte

for(int x=0;x<500;x++){
     System.out.println("Hello World!");
}

You should really read about control structures. This is programming 101

您应该真正阅读有关控制结构的信息。这是编程101

回答by JoSSte

Try this

试试这个

public static void main(String[] args){
     for(int j=0; j<500; j++){
          System.out.println("Hello world");
     }

回答by Cristian Botiza

I googled this because I think it is more expressive if one can say:

我在谷歌上搜索了这个,因为我认为如果有人可以说:

Integer.times(500).execute(i -> System.out.println("Hello world"))

We should really not bother with indexes in such a case. I think the question is legit.

在这种情况下,我们真的不应该打扰索引。我认为这个问题是合法的。

groovy, for example, has incorporated this in the language:

例如,groovy 已将其纳入语言:

    500.times {
      println "Hello world"
    }

Would be nice to have this addition to Java as well. And of course you can currently use the IntStream approach, as explained in previous comments.

将这个添加到 Java 中也会很好。当然,您目前可以使用 IntStream 方法,如之前的评论中所述。