How to execute 1 command x times in java

情到浓时终转凉″ 提交于 2020-05-09 17:29:01

问题


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

for example this code

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

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

Thank You

Regards Wilhelmus


回答1:


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




回答2:


With Java 8 Streams you could do it like that

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



回答3:


You would use a for loop.

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



回答4:


Try like this :

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



回答5:


Try this

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



回答6:


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

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




回答7:


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:

    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.



来源:https://stackoverflow.com/questions/32687538/how-to-execute-1-command-x-times-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!