在If语句

时间:2017-01-10 12:50:32

标签: java assignment-operator comparison-operators

我想在今年早些时候开始学习Java,所以我感谢你的帮助!我目前正在开发一个Shadowrun(第3版)程序,它将Decking转变为命令提示符。我希望用户能够输入蓝色,绿色,橙色或红色以开始使用主机颜色,同时也提供随机选项。

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

在指定特定颜色时,代码可以正常工作。但是,当选择Random选项然后打印整体结果时,我的代码表示HostColor是Random,而不是打印四种颜色中的一种。我感谢任何帮助解决这个问题的意见 - 提前感谢!

1 个答案:

答案 0 :(得分:2)

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。切换似乎是编写此类条件代码的更干净的方式。