Ben
Ben

Reputation: 153

How to stop a for loop from running?

So i have created a method that uses multiple for loop and I am looking for a way in which I can get the previous for loop to stop running so that I can start using the next one. Here is my code:

public void timePasses()
    {
        House callgo = new House();

        System.out.println("Shower usage:\n");    
        for (int x = 0; x < 4; x++) 
        {
        callgo.goShower();

  //Need to stop here, System.out.println("Cooker usage:\n"); only needs to print once.

        System.out.println("Cooker usage:\n");
        for (int z = 0; z < 4; z++) 
        {
        callgo.goCooker();
        }

      //this method is called as part of the simulation to trigger a new fifteen minute period
      //in the house. When it is called, it will in turn call timePasses() on all the Appliances in the House.

    }
    }

I know that it would be possible to just use multiple methods but for the specification, I need to print out all of the data within one timePasses() method so I was wondering if there is a way that I could stop the previous for loop running, print out my statement and start the next one? Any help is appreciated, thanks.

Upvotes: 0

Views: 90

Answers (2)

Gurwinder Singh
Gurwinder Singh

Reputation: 39477

I think you want this:

public void timePasses()
{
    House callgo = new House();

    System.out.println("Shower usage:\n");    
    for (int x = 0; x < 4; x++) 
    {
    callgo.goShower();

    //Need to stop here, System.out.println("Cooker usage:\n"); only needs to print once.
    }
    System.out.println("Cooker usage:\n");
    for (int z = 0; z < 4; z++) 
    {
    callgo.goCooker();
    }

  //this method is called as part of the simulation to trigger a new fifteen minute period
  //in the house. When it is called, it will in turn call timePasses() on all the Appliances in the House.
}

Upvotes: 1

Mr. Suryaa Jha
Mr. Suryaa Jha

Reputation: 1582

You can stop a for loop by using break statement. Call this break statement after callgo.goShower() and the loop will break causing to execute next statement after for loop closing brace ( } ) callgo.goShower() ; break ;

Upvotes: 0

Related Questions