Brock Hayes
Brock Hayes

Reputation: 3

How do I output a string if a boolean variable is true?

public class LordofTheRings {

public static void main(String[] args){

    boolean Gimli=false;
    boolean Boromir=false;
    boolean Aragorn=false;
    boolean Sam=false;
    boolean Frodo=false;
    boolean Legolas=false;
    boolean Merry=false;
    boolean Pippin=false;
    boolean Gandalf=false;


    int night1=1;

    while (!Gimli||!Boromir||!Aragorn||!Sam||!Frodo|!Legolas|!Merry|!Pippin|!Gandalf){

        Gimli=true;

    if (night1 % 2==0) 
        Boromir=true;
    else               
    {
        Boromir=false;
    }

    if (night1 % 3==0) 
        Aragorn=true;
    else               
    {
        Aragorn=false;
    }

    if (night1 % 4==0) 
        Sam=true;
    else               
    {
        Sam=false;
    }

    if (night1 % 5==0) 
        Frodo=true;
    else               
    {
        Frodo=false;
    }

    if (night1 % 6==0) 
        Legolas=true;
    else               
    {
        Legolas=false;
    }

    if (night1 % 7==0) 
        Merry=true;
    else               
    {
        Merry=false;
    }

    if (night1 % 8==0) 
        Pippin=true;
    else               
    {
        Pippin=false;
    }

    if (night1 % 9==0) 
        Gandalf=true;
    else               
    {
        Gandalf=false;
    }

    System.out.println("Night "+night1);
    System.out.println("=========================");
    System.out.println("LOTR characters at the tavern: " + Gimli + Boromir + Aragorn + Sam + Legolas + Merry + Pippin + Gandalf);
}
}

I need my program to print the character names when they are at the tavern instead of true/false when they are at the tavern. I would greatly appreciate any help. I'm a beginner to java so the switch statement hasn't been explained to me. I think we are going back to clean up this code later in my CSC 145 class.

Upvotes: 0

Views: 172

Answers (1)

dev8080
dev8080

Reputation: 4020

Try this:

  System.out.print("LOTR characters at the tavern: ");
  System.out.print(Gimli ? "Gimli " : "");
  System.out.print(Boromir ? "Boromir " : "");
  System.out.print(Aragorn ? "Aragorn " : "");
  System.out.print(Sam ? "Sam " : "");
  System.out.print(Legolas ? "Legolas " : "");
  System.out.print(Merry ? "Merry " : "");
  System.out.print(Pippin ? "Pippin " : "");
  System.out.print(Gandalf ? "Gandalf" : "");
  System.out.println();

But a HashMap would have been better.

Upvotes: 1

Related Questions