我正在创建一个带有do-while循环的脚本,该循环随机选择6种颜色之间的颜色。然后它要求该人猜测颜色。
如果他们弄错了,则表示不正确并询问他们是否想再试一次。
如果他们这样做会选择一种新的颜色(这种情况发生了,但是我希望它不会,但那不是问题)然后他们再次猜测。
问题出现时,他们猜测颜色正确,它仍然输出说他们是不正确的。我无法弄清楚为什么会发生并需要帮助。
我的代码如下:
import java.util.Random;
import java.util.Scanner;
public class MCassignment11 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
Random rng = new Random();
String again, guess;
do {
int colorchoice = rng.nextInt(5);
String color;
if (colorchoice == 0)
color = "RED";
else if (colorchoice == 1)
color = "BLUE";
else if (colorchoice == 2)
color = "GREEN";
else if (colorchoice == 3)
color = "YELLOW";
else if (colorchoice == 4)
color = "ORANGE";
else
color = "PINK";
System.out.println("Guess my favorite color. There are 6 options.");
guess = keyboard.next();
if (guess.equals(colorchoice))
System.out.println("Correct my favorite color is " + color);
else
System.out.println("Incorrect. Would you like to try again? (y/n)" + colorchoice);
again = keyboard.next();
} while (again.equals("y"));
}
}
答案 0 :(得分:3)
此处的一个问题是您的比较区分大小写,这意味着如果用户输入的内容如Red
,red
或rEd
或类似内容,则会被视为不正确。 (从技术上讲,Red
和RED
不是相等的字符串。)
一种选择是使用toUpperCase() method来确保将用户输入视为用大写字母书写,如下所示:
if (guess.toUpperCase().equals(color))
正如@OHGODSPIDERS在评论中指出的那样,Java字符串也有equalsIgnoresCase() method,你也可以在这里使用。要么工作。
另外,正如@Alessandro指出的那样,您应该将guess
与color
进行比较,而不是colorchoice
。
另一点:
if (guess.equals(colorchoice))
System.out.println("Correct my favorite color is " + color);
else
System.out.println("Incorrect. Would you like to try again? (y/n)" + colorchoice);
again = keyboard.next();
为确保您不提示用户继续猜测,您应该执行以下操作:
if (guess.toUpperCase().equals(color))
{
System.out.println("Correct my favorite color is " + color);
// Explicitly set "again" to "n" so that we won't loop again
again = "n";
}
else
// Add brackets so that it only prompts the user for input if they had a wrong answer
{
System.out.println("Incorrect. Would you like to try again? (y/n)" + colorchoice);
again = keyboard.next();
}
答案 1 :(得分:0)
您正在将String
与int
进行比较:
if (guess.equals(colorchoice))
所以你应该把一种类型转换成另一种类型。
您可以使用Integer.parseInt()
转换字符串,或将其连接到""
。
请参阅以下内容:
public static void main(String[] args) {
String a = "1";
int b = 1;
System.out.println(a.equals(b)); //Prints false
System.out.println(a.equals("" + b)); //Prints true
System.out.println(Integer.parseInt(a)==b); //Prints true
}