Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a java program that guess a number. You inputs numbers until it matched wi

ID: 3807367 • Letter: W

Question

Write a java program that guess a number. You inputs numbers until it matched with randomly generated number. The program keeps ask a user to input numbers between 1 to 6. Once a user input his/her guessed number, then it compares with number that is randomly generated. If it matches with randomly generated number, it display a message "Congratulation! You got it!!" and also displays how many times he/she guessed the number. Then, the program is terminated. Otherwise, the program asks a user to input another number. The output of the program should be like following:

******************

Guess a number between 1 to 6:

5

Guess a number between 1 to 6:

3

Guess a number between 1 to 6:

1

Guess a number between 1 to 6:

6

Guess a number between 1 to 6:

2

Congratulation! you got it!! you guessed it 5 times.

******************

******************

Guess a number between 1 to 6:

3

Congratulation! you got it!! you guessed it 1 times.

******************

Explanation / Answer

PROGRAM CODE:

package simple;

import java.util.Random;

import java.util.Scanner;

public class GuessTheNumber {

   public static void main(String[] args) {

      

       Scanner keyboard = new Scanner(System.in);

       Random rand = new Random();

       int number = rand.nextInt(6) + 1;

       int guess = 0;

       int chances = 0;

       System.out.println("******************");

       while(true)

       {

           System.out.println("Guess a number between 1 to 6: ");

           guess = keyboard.nextInt();

           if(guess == number)

           {

               System.out.println("Congratulation! you got it!! you guessed it " + (chances+1) + " times.");

               break;

           }

           else chances++;

       }

       System.out.println("******************");

   }

}

OUTPUT:

******************

Guess a number between 1 to 6:

1

Guess a number between 1 to 6:

2

Guess a number between 1 to 6:

3

Guess a number between 1 to 6:

4

Congratulation! you got it!! you guessed it 4 times.

******************

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote