-4

I am writing a program for a school assignment to create one string array of 3 riddles and another string array of 3 answers to each riddle. However when I input the correct answer to the riddle it keeps on showing the else part of the if-else statement. Here's my code:

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] + ".");}
} 
} 
}
Roman C
  • 49,761
  • 33
  • 66
  • 176

1 Answers1

0

never compare strings with ==

you should always use .equals( )

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

you should also try to have the constant value (the one that will always exist) on the left of these, to prevent possible NullPointerExceptions.

M21B8
  • 1,867
  • 10
  • 20