Problem: 3.06


 Question 3.06: Write a program that generates a random number and asks the user to guess what the number is. If the user's guess is higher than the random number, the program should display "Too high, try again." If the user's guess is lower than the random number, the program should display "Too low, try again." The program should use a loop that repeats until the user correctly guesses the random number. 


Solution:


package com.company;

import java.util.Scanner;
import java.util.Random;

public class Lab03Problem6{
    public static void main(String [] args)
    {

        Scanner kb = new Scanner(System.in);

        Random rand = new Random();
        int num = rand.nextInt(100) + 1;
        int guess = 0;
        int count = 0;
        int guesses = 0;

        do
        {
            System.out.println("Guess what number I have (1-100)? ");
            guess = kb.nextInt();
            guesses ++;

            if(num > guess) {
                System.out.println("Too high, try again.");
            } else if(num < guess) {
                System.out.println("Too low, try again.");
            } else {
                System.out.println("You're right, the number is" + num);
                System.out.println("You guessed" + guesses + "times");
            }
        }
        while(guess!=num);
    }
}

Previous Post Next Post