user1419268
user1419268

Reputation: 11

java: is there a loop that can do this?

Im making a game in java and need to be able to make a loop that does something like this:

first pass through loop:

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

second pass:

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

and so on with another example.print() added each time.

In order for the program to work correctly, each "example.print()" has to physically be there is the code. Any ideas?

Upvotes: 1

Views: 146

Answers (6)

Marko Topolnik
Marko Topolnik

Reputation: 200168

It's anybody's guess what you mean by "physically there", but I'll give it a shot:

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);
  }

Upvotes: 0

svarog
svarog

Reputation: 9839

here's my take, *considering the parameter your sending to the print method is what you want it to print

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);
    }
}

Upvotes: 0

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33534

Try this.

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

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

100 is an assumed value here, for the nos of times the loop will iterate.

Upvotes: 0

TeaOverflow
TeaOverflow

Reputation: 2578

My version:

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

Upvotes: 1

sithereal
sithereal

Reputation: 1686

int loopCounter = 0;

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

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1074495

Sounds like you want nested loops:

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

Notes:

  • You'll want to adjust the i + j part as necessary to get the desired output. You didn't say what should happen when we got past the first five. :-)
  • You didn't say how many passes you wanted, so I assumed 5. If you want fewer, change the upper limit of the i loop (the outer one), probably.

Upvotes: 5

Related Questions