0

I am making a number guessing game in Java, where the program displays a number, in a 1 to 10 range, and you have to either guess if the next number will be lower or higher than the current one. But there seems to be an issue when i get it correct i am supposed to get a point added to my score but instead it just does the method for when I get the guess wrong.

class csjava
{
    public static void main(String[] args)
    {
        Random dom = new Random();
        Random dom2 = new Random();
        Scanner input = new Scanner(System.in);
        int score = 0;
        System.out.println("Guess if next number will be higher or lower                        Score:" + score);
        int rnd = dom.nextInt();
        int rnd2 = dom2.nextInt();
        String  lo = "lower";
        String hi = "higher";
        if(score ==10)
        {
            System.out.println("You win!");
        }
        while(score != 10)
        {
            System.out.println(dom.nextInt(10-1)+1);
            String in = input.nextLine();
            if(in == lo)
            {
                System.out.println(dom2.nextInt(10-1)+1);
                if(rnd2 < rnd)
                {
                    score = score + 1;
                }
            }
            else
            {
                System.out.println("Nope, try again.");
            }
            if(in == hi)
            {
                System.out.println(dom2.nextInt(10-1)+1);
                if(rnd2 > rnd)
                {
                    score = score + 1 ;
                }
            else
            {
                System.out.println("Nope, try again."); 
            }
        }
    }
}
JNYRanger
  • 6,829
  • 12
  • 53
  • 81
kevin
  • 31
  • 5

2 Answers2

1

You are equating Strings using ==. This only works for equating the value for primitives. Check out this post for a clearer understanding.

== is a reference comparison, i.e. both objects point to the same memory location

.equals() evaluates to the comparison of values in the objects

Instead of

if(in == lo)

You want

if(in.equals(lo))
Community
  • 1
  • 1
Java Devil
  • 10,629
  • 7
  • 33
  • 48
0

Your String comparisons are using the == operator which checks for object equality. You want to use the equals method instead which checks for value equality.

Replace

if(in == lo)

with

if(in.equals(lo))

Same applies to

if(in == hi) // should be if(in.equals(hi))
JamesB
  • 7,774
  • 2
  • 22
  • 21