打印 If 语句中更改的字符串变量

Print String Variable altered in If statement

首先我想在今年年初开始学习 Java,非常感谢您的帮助!我目前正在开发一个将 Decking 变成命令提示符的 Shadowrun(第 3 版)程序。我希望用户能够输入蓝色、绿色、橙色或红色以开始使用主机颜色,但也可以提供随机选项。

  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 + "...");

代码在指定特定颜色时工作正常。 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.感谢任何有助于解决此问题的意见 - 提前致谢!

HostColor.equals()不是赋值,equals()是比较方法,在这种情况下检查两个字符串是否相等。

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" ;
  }
}

我建议您使用 Switch statements 来比较 string 而不是 if-elseif。 Switch 似乎是编写此类条件代码的更简洁的方式。