0

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.

2
  • 1
    is it because you enclosed the second loop in the first one? Commented Dec 4, 2016 at 5:03
  • It was because of that yeah. Commented Dec 4, 2016 at 5:14

2 Answers 2

1

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.
}
Sign up to request clarification or add additional context in comments.

Comments

0

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 ;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.