Java Else if语句在计算字符串时工作不正常

Java Else if语句在计算字符串时工作不正常,java,if-statement,Java,If Statement,我正在为学校作业编写一个程序,创建一个由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

我正在为学校作业编写一个程序,创建一个由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] + ".");}
} 
} 
}
import java.util.Scanner;
导入java.util.Random;
公共班级计划{
公共静态void main(字符串[]args){
扫描仪输入=新扫描仪(System.in);
Random rand=新的Random();
整数指数;
int chosenridles=rand.nextInt(2);
//声明程序中的谜语,并从所呈现的三个谜语中随机选择一个谜语
字符串[]谜语=新字符串[3];
谜语[0]=“什么东西以T开头,以T结尾,里面有T?”;
riddle[1]=“前一天的前两天是星期六。今天是星期几?”;
谜语[2]=“什么在成长的同时又在成长?”;
//宣布谜语的答案
字符串[]答案=新字符串[3];
答案[0]=(“茶壶”);
答复[1]=(“星期五”);
答案[2]=(“鹅”);
//要求用户输入随机出现的谜语的猜测答案

对于(index=0;index切勿将字符串与==

您应该始终使用.equals()

您还应该尝试将常量值(始终存在的常量值)放在这些值的左侧,以防止可能的NullPointerException

if (answer[chosenRiddles].equals(inputtedAnswer)) {