java:有没有可以做到这一点的循环?

时间:2012-05-26 17:03:43

标签: java loops

我在java中制作游戏并且需要能够创建一个类似这样的循环:

首先通过循环:

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

第二遍:

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

以及每次添加另一个example.print()。

为了使程序正常工作,每个“example.print()”必须在物理上存在代码。 有什么想法吗?

6 个答案:

答案 0 :(得分:5)

听起来像是想要嵌套循环:

for (int i = 0; i < 5; i++) {
    for (int j = 0; j < 5; j++) {
        example.print(i + j); // This will need adjusting
    }
}

注意:

  • 您需要根据需要调整i + j部分以获得所需的输出。你没有说我们超过前五个会发生什么。 : - )
  • 你没有说你想要多少次传球,所以我假设5.如果你想减少,可能会更改i循环(外部循环)的上限。

答案 1 :(得分:2)

int loopCounter = 0;

for(int i=0;i<5;i++)
{
    for(int k=0; k<loopCounter; k++)example.print(k);
    loopCounter++;
}

答案 2 :(得分:1)

我的版本:

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

答案 3 :(得分:0)

这是任何人猜你的意思是“身体在那里”,但我会试一试:

final Example example = new Example();
for (int i = 0; i < 5; i++)
  switch (i) {
    case 4: example.print(i-4);
    case 3: example.print(i-3);
    case 2: example.print(i-2);
    case 1: example.print(i-1);
    case 0: example.print(i-0);
  }

答案 4 :(得分:0)

试试这个。

for (int x = 0,y = 0; x < 100; x++,y++) {

        example.print(x + y); // You will need to tweak these values
    }

100是这里的假设值,循环将迭代的次数。

答案 5 :(得分:0)

这是我的看法,*考虑到您打印方法的参数是您想要打印的参数

int n=3; //n is the highest param value you want your print method to receive, 
         //here it's just 3

for (int i=0; i<n; i++) {
    for (int j=0; j<(i+1)*5; j++) {
        example.print(j/5);
    }
}