我正在尝试编写一个简单的命令行"猜字游戏"一系列颜色。问题是,即使选择了正确的颜色,它也不会使用我当前的IF语句中断do / while循环。
import java.util.Random;
import java.util.Scanner;
public class ColorGuess {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] colors = { "red", "blue", "green", "yellow", "purple",
"pink", "white", "black", "brown", "orange", "grey" };
String colorGuess;
Random rand = new Random();
int randColor = rand.nextInt(colors.length);
String color = colors[randColor];
System.out.printf("Guess the color: ");
do {
colorGuess = input.nextLine();
if (color == colorGuess) {
break;
} else {
System.out.printf("Sorry, try again: ");
}
} while (colorGuess != color);
System.out.println("You got it! The color was indeed " + color + ".");
}
}