0

Never enters the if statement. Always the else statement. Just need help to find out why the if statement is being ignored.. is something wrong with my if statement?

import java.util.Random;
import java.util.*;
public class WordGameRandom {

    public static void main(String[] args) 
{
    //sets the number of arraies and their values
   String[] words = {"Cat", "Pig", "Dog", "Rat"};
   int Max = 4;
   int x = 1;
   String guess;
   Scanner input = new Scanner(System.in);

   do{
   System.out.print("Please guess a three letter animal: ");
   guess = input.nextLine();
   System.out.println("Your word:" + guess);

   Random random = new Random();
   System.out.println("The computers word: " + 
           words[random.nextInt(words.length)]);

   if(guess == words[random.nextInt(words.length)])
   {
       System.out.println("Congrats!");
       ++x;
   }
   else
   {
       System.out.println("Fail");
   } 
   }
   while(x != 2);

}  
}
  • 1
    https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ – David Feb 20 '17 at 01:09
  • Look up the string `equals` function. – Scovetta Feb 20 '17 at 01:10
  • 2
    Don't compare Strings using `==` or `!=`. Use the `equals(...)` or the `equalsIgnoreCase(...)` method instead. Understand that `==` checks if the two *object references* are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. – Hovercraft Full Of Eels Feb 20 '17 at 01:10
  • Not related to your question, but the sentinel variable `x` is a waste. Just use a `break` to get out of the loop. Also, if you insist on retaining `x`, use an inequality check such as `while(x < 2)` rather than `while(x != 2)`. Otherwise, somebody (possibly you) will someday modify the code to update `x` in an entirely different way and you'll find yourself stuck in an infinite loop. – pjs Feb 20 '17 at 01:21
  • I tried the equals function and I still have the same problem. Still skips the if statement. – Blake Morgan Feb 21 '17 at 15:09

0 Answers0