Lexi Hudson
Lexi Hudson

Reputation: 11

Color guessing game in Java

I am trying to create a color guessing game in Java. I have created a loop, but I cannot figure out how to create a correct answer. It is incorrect every time. Could someone help figure out what the issue in my code is? Thank you in advance.

import java.util.*;
public class Guess_The_Color
{
  public static void main(String[] args)
  {
    Scanner cin = new Scanner(System.in);
    Random ran = new Random();

    String sAgain;
    String sGuess;
    int iColor;

    do
    {
      iColor = ran.nextInt(5);
      String sColor;

      if (iColor == 0)
        sColor = "Red";
      else if (iColor == 1)
        sColor = "Blue";
      else if (iColor == 2)
        sColor = "Green";
      else if (iColor == 3)
        sColor = "Yellow";
      else if (iColor == 4)
        sColor = "Orange";
      else
        sColor = "Pink";

      System.out.println("Guess what color I am thinking of... ");
      sGuess = cin.next();

      if (sGuess.toUpperCase().equals(iColor))
      {
        System.out.println("Correct!" + sColor);
        sAgain = "n";
      }
      else
      {
        System.out.println("Incorrect, would you like to try again? (y/n)?" + iColor);
      sAgain = cin.next();
      }

    }
      while (sAgain.equals("y"));
    }
  }

Upvotes: 1

Views: 2078

Answers (2)

Devon
Devon

Reputation: 160

You are comparing a string to an int in the line

sGuess.toUpperCase().equals(iColor)

That will be false every time. Make sure you only compare variables with the same type. I think you meant to compare with sColor instead of iColor.

sGuess.toUpperCase().equals(sColor.toUpperCase()) //making them both uppercase or lowercase will work here. 
//You want to make sure both are lowercase or both are uppercase

Or (Suggestion from Maarten Bodewes):

sGuess.equalsIgnoreCase(sColor)

Upvotes: 1

checknov
checknov

Reputation: 11

I believe the problem is here - sGuess.toUpperCase().equals(iColor)

you comparing ORANGE to Orange (for example)

EDIT: and yes, you comparing String to int)

for this type of thing you can always use the debug to see the variables

Upvotes: 0

Related Questions