简体   繁体   中英

How to cancel a print statement if a method is called with a certain parameter?

I'm not sure if the question is very clear, maybe the code will help.

This is part of the constructor of SpaceGame

   player.setPlanets(planets); //set Planets for player

   enemy.setPlanets(planets); //set Planets for enemy

And this is part of the setPlanets method

public void setPlanets (ArrayList<Planet> planets) {
    for (int i = 0; i < planets.size(); i++) //Iterate through the ArrayList of Planets
        {
            System.out.println(planets.get(i)); //Prints the info of each planet
        }

When the game begins, planets are printed twice. Is there a way to cancel it if I use enemy.setPlanets?

You can use a boolean as a condition

public void setPlanets (ArrayList<Planet> planets, boolean print) {
    for (int i = 0; i < planets.size(); i++) //Iterate through the ArrayList of Planets
        {
           if (print) {
              System.out.println(planets.get(i)); //Prints the info of each planet
           }
        }


player.setPlanets(planets, true); //set Planets for player

enemy.setPlanets(planets, false); //set Planets for enemy

And more you can overload setPlanets

public void setPlanets (ArrayList<Planet> planets) {
    setPlanets(planets, false); // don't print by default
}

Then for enemy,

enemy.setPlanets(planets);

is enough.

I see there's two different info you will print. once for player and another for enemy so where is the problem it's different info, so if you want to print just one info when start the game you should write:

if (gameStarted){
     player.setPlanets(planets); //set Planets for player        
}else{
     player.setPlanets(planets); //set Planets for player        
     enemy.setPlanets(planets); //set Planets for enemy
}

or viceversa.

I think bejond's answer is quite good, but it will check the print condition for each element of your loop. You could check the condition before entering the loop to obtain better performances.

player.setPlanets(planets, true); //set Planets for player
enemy.setPlanets(planets, false); //set Planets for enemy

Your function should now look like that

public void setPlanets (ArrayList<Planet> planets, boolean isPrinted) 
{

        if (isPrinted) 
        {
           for (int i = 0; i < planets.size(); i++) //Iterate through the ArrayList of Planets
           {
              System.out.println(planets.get(i)); //Prints the info of each planet
           }
        }

        //your code...
}

If you wish, you could also overload your function, like bejond suggested.

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