Search code examples
javaassignment-operatorcomparison-operators

Print String Variable altered in If statement


I'd like to preface this with that I've only started learning Java earlier at the beginning of this year, so I appreciate all your help! I'm currently working on a Shadowrun (3rd Edition) program that turns Decking into a Command Prompt. I'd like the user to be able to enter Blue, Green, Orange, or Red to start with a Host Color, but also give a Random option as well.

  Scanner user_input = new Scanner(System.in);
  String HostColor;
  System.out.println("What is the color of the Host? (Blue, Green, Orange, Red, Random)"); //Get the Host's Color
  HostColor = user_input.nextLine();
  Random rand = new Random();
while ((!HostColor.equals("Blue")) || (!HostColor.equals("Green")) || (!HostColor.equals("Orange")) || (!HostColor.equals("Red"))) { 
  if (HostColor.equals("Blue")) {
    ...
    break;
  }
  else if (HostColor.equals("Green")) {
    ...
    break;
  }
  else if (HostColor.equals("Orange")) {
    ...
    break;
  }
  else if (HostColor.equals("Red")) {
    ...
    break;
  }
  else if (HostColor.equals("Random")) {
    int RandomHost = (rand.nextInt(4));
      if (RandomHost == 0) {
      HostColor.equals("Blue");
      ...
      break;
      }
      else if (RandomHost == 1) {
      HostColor.equals("Green");
      ...
      break;
      }
      else if (RandomHost == 2) {
      HostColor.equals("Orange");
      ...
      break;
      }
      else if (RandomHost == 3) {
      HostColor.equals("Red");
      ...
      break;
      }
  }
  else {
    System.out.println("Invalid Command");
    System.out.println("What is the color of the Host? (Blue, Green, Orange, Red, Random)");
    HostColor = user_input.nextLine();
  }
  }
System.out.println("Host is a " + HostColor + "...");

The code works just fine when specifying a particular color. However, when choosing the Random option and then printing the overall results, rather than printing one of the four colors, my code says the HostColor is Random. I appreciate any input to help solve this problem - thanks in advance!


Solution

  • HostColor.equals() is not assignment, equals() is comparision method which checks whether two strings are equals or not in this case.

    else if (HostColor.equals("Random")) {
    int RandomHost = (rand.nextInt(4));
      if (RandomHost == 0) {
      HostColor = "Blue";
      }
      else if (RandomHost == 1) {
      HostColor = "Green";
      }
      else if (RandomHost == 2) {
      HostColor = "Orange";
      }
      else if (RandomHost == 3) {
      HostColor = "Red" ;
      }
    }
    

    I would recommend you to use Switch statements for comparing string instead of if-elseif. Switch appears to be more clean way of writing such conditional codes.