简体   繁体   中英

Instead of using for loop, how do I make a loop where you tell it the amount of times you want it to loop?

How would I create a loop where it has a condition, but in addition you can decide how many times you want it to loop. I know that the for loop does this, but what if I want a specific integer to determine how many times it will loop?

Example

//for loop below
  for(int x = 0; x < 10; x++)
       {

       }

Instead of doing the for loop (above), is there a way to choose a specific number of times you want it to loop, so that you can enter an integer variable in a properly which will tell it how many times you want it to loop?

There's a few choices. The simplest is to replace 10 with a variable,

int length = 10;
for(int x = 0; x < length; x++)

Alternatively, you could use a while loop,

int length = 10;
int x = 0;
while (x < length) {
 // ...
 x++;
}

Or a do {} while like

int length = 10;
int x = 0;
do {
 // ...
} while (x++ < length);

Every loop can be made to satisfy your constraints. A while loop might be most apt one in this case.

int count;
while (count-- != 0) {
    //statements
}

Will execute the loop body count number of times.

int amount = 50;

for(int x = 0; x < amount; x++) {
   // This will loop 50 times.
}

The integer after x < is the amount of times that it will loop.

If you want to avoid using a loop, you can use Java 8 features :

IntStream.range(0,n).forEach(i -> {
    //someCode
});

This will run a block of code n times.

just do this

 System.out.println("enter amount of time you want the loop to run");
Scanner scanner=new Scanner(System.in);
int amount=scanner.nextInt();
for(int i=1;i<=amount;i++){
System.out.println("Hii");
}

This program will ask you how may times you want to execute the loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM