2017-05-24 374 views
1

我必须调用它5次才能打印。如何通过循环连续调用方法?

运行:

我会调用这个例程5倍等等...

public class Method2 { 

    public static void main(String[] args) { 
     call(); 
    } 
    static void call(){ 
     System.out.println("I will call this routine 5 times"); 
     for (int = i = 1; i<5; i++); //I don't know what I'm doing here. 
    } 
} 

我新的方法,我可以打电话,但我不知道如何把它放在一个循环。 在此先感谢!

+0

这是一个Java循环...只看教程:https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html 这些只是非常基础。 –

回答

0

println呼叫必须发生内部循环:

static void call(){ 
    for (int i=1; i<=5; i++) { 
     System.out.println("I will call this routine 5 times"); 
    } 
} 

你的代码设置的初始条件(i=1);每次运行循环必须满足的条件(i<=5);以及在循环的每次运行结束时发生的操作(i++)。

循环内部(由{}分隔)是println调用,发生五次。

还有一个文体注:大多数程序员会写循环从0开始,并上升到(但不包括)5,像这样:

for (int i=0; i<5; i++) { ... } 

这是因为对于大多数的计算任务只是它的如果事物的编号从0而不是从1开始更有用。但这里没有多大关系,因为除了循环之外,您并没有使用i的值。

还有一个额外的考虑:你说五次调用例程。如果你的意思是你想整个call()方法被调用五次,那么你会希望你的循环坐在main()方法调用它,像这里面:

public static void main(String[] args) { 
    for (int i=1; i<=5; i++) { 
     call(); 
    } 
} 
static void call(){ 
    System.out.println("I will call this routine 5 times"); 
} 
1

那怎么for循环工程..

for (initialization; condition; increment/decrement) { 
    statement(s) //block of statements 
} 

所以你实际上需要将您的打印语句{}

static void call() { 
     for (int i = 0; i < 5; i++) { 
      System.out.println("I will call this routine 5 times"); 
     } 
} 

如果你要打印你的发言5次,您可能需要启动循环

从0到5(不包括),如

for (int i = 0; i < 5; i++){ 

} 

或从1至5(含)

for (int i = 1; i <= 5; i++){ 

} 
0

以及在C#它看起来像这样具有用于:

for (int i = 0; i < 5; i++) 
     { 
      Console.WriteLine("Here is the text 5 times"); 
     } 
     Console.ReadLine(); 

,这将是同一时间:

static void Main(string[] args) 
     { 
      int i=0; 
      do 
      { 
       Console.WriteLine("Here is the text 5 times"); 
       i++; 
      } 
      while (i < 5); 
      Console.ReadLine(); 
     }