0

I want to count the number of attempts the user tried to guess the correct guess. How would i do that?
like

I have thought of a number.
Try to guess it Take a guess: 5
Your guess is higher than mine
Take a guess: 3
Your guess is lower than mine
Take a guess: 4
Good job! You guessed the number in 3 tries.

import java.util.*;
class task3344
{
    public static void main (String [] args)
    {
        Scanner scan = new Scanner (System.in);

            int random = 1 + (int)(Math.random() * 9);
            System.out.println (random);

            int guess = 0;



            do
            {
                System.out.println ("Take guess: ");
                guess = scan.nextInt();

                if (guess > random)
                {
                    System.out.println ("your guess is high");
                }
                else if (guess < random)
                {
                    System.out.println ("your guess ins low");
                }
                else 
                {
                    System.out.println ("good! you guessed correct");
                }
            }
            while (guess != random);




    }
}
2
Contributors
2
Replies
15
Views
4 Years
Discussion Span
Last Post by hashim5003
1

Just add a counter of type int and add it to both the if and else if statements. Once in place, add a print line to your final "else" when the user gets it right which will output the counter. I would offer you code but this looks like an assignment and we get our hands slapped when we post solutions to assignments.

Here's the last print lines, you should be able to figure out the rest I think

System.out.println ("good! you guessed correct");
counter +=1;
System.out.println("It took you " + counter + " tries.");
0

Thankx!
this is not the the assignment. its just the program from lab class for practice.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.