Home > Enterprise >  How Can I get a While loop with an If statement in Java to stop after a certain number of loops?
How Can I get a While loop with an If statement in Java to stop after a certain number of loops?

Time:08-09

Below is my code and I would like to know how I can get it to stop after a certain number of loops.

Scanner scanner = new Scanner(System.in);
int height_requirement = 50;
while(true) {
    System.out.print("Enter height -> ");
    int height = scanner.nextInt();     
    if (height < height_requirement) {
        System.out.println("You are too short to ride the ride the roller coaster.");
    }
    System.out.println("You can ride the roller coaster");
}

CodePudding user response:

Use a for loop:

int maxLoops = 5;

Scanner scanner = new Scanner(System.in)
int height_requirement = 50;
for (int i = 0; i < maxLoops; i  ) {
    System.out.print("Enter height -> ");
    int height = scanner.nextInt();     
    if (height < height_requirement) {
        System.out.println("You are too short to ride the ride the roller coaster.");
    } else {
        System.out.println("You can ride the roller coaster");
    }
}

Also there was a small mistake at the very end of the loop.

CodePudding user response:

Normally there is for with index which you can easy control until what number to go.

If you want the solution with while try this:

Scanner scanner = new Scanner(System.in);
int height_requirement = 50;
int count = 5; // give start number
while(count > 0) { // check if count is bigger then 0
    count--; // remove -1 each time. This way while will do 5 iterations
   
    System.out.print("Enter height -> ");
    int height = scanner.nextInt();     
    if (height < height_requirement) {
        System.out.println("You are too short to ride the ride the roller coaster.");
    }
    else // put "You can ride the roller coaster" in else not to be printed every time
    { 
        System.out.println("You can ride the roller coaster");
    }
}

CodePudding user response:

You can use break statement to end the while loop so that the while statement will work only once

    Scanner scanner = new Scanner(System.in);
    int height_requirement = 50;
    while (true) {
        System.out.print("Enter height -> ");
        int height = scanner.nextInt();
        if (height < height_requirement) {
            System.out.println("You are too short to ride the ride the roller coaster.");
            break;        // To break the loop
        } else{
            System.out.println("You can ride the roller coaster");
            break;        // To break the loop 
        }

    }
  • Related