-4
while (x == 1) 
  {
       String[] riddles = new String[5] ;  
          riddles[0] = ("Hellowrite1") ;
          riddles[1] = ("write2") ;
          riddles[2] = ("write3") ;
          riddles[3] = ("write4") ;
          riddles[4] = ("write5") ; 

       String[] answers = new String [5] ;
          answers[0] = ("1") ;
          answers[1] = ("2") ;
          answers[2] = ("3") ;
          answers[3] = ("4") ;
          answers[4] = ("5") ; 
int riddlenumber;
   riddlenumber = rand.nextInt (5);
   System.out.println (riddles [riddlenumber]);
   String useranswer;
   useranswer = scan.next();
   if

how would I continue the if statement? I want the if statement to compare the user answer with the corresponding string from the answers String. Basically I want it to say, if the string useranswer = answer String #(riddlenumber, the number chosen with the random function), then system.out.println("yay"); else -----

2 Answers2

2

I'm nervous about the scan.next, but to answer your question:

if( answers[riddlenumber].equals(useranswer) ) {
    System.out.println("Yay, I guess");
} 
else {
    System.out.println("Not quite, try again...");
}

Minor point: I could also have said useranswer.equals(answers[riddlenumber]). But I'm being paranoid. I'm absolutely certain that the stored answer isn't null. I'm not absolutely certain useranswer won't be. By doing it in the order above, I avoid feeling I need to check for null first; you can safely call Object.equals(null), but you can't call null.equals(Object).

keshlam
  • 7,931
  • 2
  • 19
  • 33
  • The scan.next part actually works, no idea how or why but it does, haha. I originally had scan.nextLine but it would print out twice, and after searching, I found that. Thank you! I actually used what the other option, but I've changed it. :) – user3199471 Jan 17 '14 at 03:37
0

Use .equals on the string.

if (answer[0].equals(userAnswer))
{
   // Strings equal
}

Note that the == operator only checks if the strings are the same object. Not if the letters are the same. See - https://stackoverflow.com/questions/767372/java-string-equals-versus

ansible
  • 3,569
  • 2
  • 18
  • 29