我正在为一个学校作业编写一个程序来创建一个包含3个谜语的字符串数组,并为每个谜语创建另一个3个答案的字符串数组。但是当我输入正确的答案时,它会继续显示if-else语句的else部分。这是我的代码:
import java.util.Scanner;
import java.util.Random;
public class riddleProgram {
public static void main (String[]args) {
Scanner input = new Scanner(System.in);
Random rand = new Random();
int index;
int chosenRiddles = rand.nextInt(2);
//declares the riddles in the program as well as choosing a random riddle from the three presented
String[]riddle = new String[3];
riddle[0] = "What starts with a T, ends with a T, and has T in it?";
riddle[1] = "The day before two days after the day before tommorrow is Saturday. What day is it today?";
riddle[2] = "What grows up while growing down?";
//declares the answers to the riddles
String[]answer = new String[3];
answer[0] = ("teapot");
answer[1] = ("friday");
answer[2] = ("goose");
//asks user to enter guessed answer for the randomly presented riddle
for (index=0; index<3; index++); {
System.out.println(riddle[chosenRiddles]);
System.out.print("Enter your answer for the presented riddle (lowercase): ");
String inputtedAnswer = input.nextLine();
//if user inputs right answer, congratulates user
//if user inputs incorrect answer, tells user the correct answer
if (inputtedAnswer == answer[chosenRiddles]) {
System.out.println("Congratulations, you have gotten the right answer!"); }
else {
System.out.println("Sorry you had the wrong answer. The right answer is " + answer[chosenRiddles] + ".");}
}
}
}
答案 0 :(得分:0)
永远不要将字符串与==
进行比较你应该总是使用.equals()
if (answer[chosenRiddles].equals(inputtedAnswer)) {
您还应该尝试在这些值的左侧使用常量值(将始终存在的值),以防止可能的NullPointerExceptions。