Creating a Guessing Game in Java

Problem:

Write a class GuessingGame that simulates a simple guessing game. Initially, your program should generate a random integer between 1 and 1000 and print the following: "Guess the number between 1 and 1000" (without the quotes). Then, the user is asked to guess the number generated. If the user is correct, the program prints:
"Congratulations" (without the quotes).
Otherwise, if the number entered by the user is less than the generated number you print "Too cold" and when the number is above you print "Too hot". The game does not stop until the user has made a correct guess. Sample program output:

Output:

Guess the number between 1 and 1000

500

Too Cold

750

Too Hot
600
Congratulations

Solution:

import java.util.*;
public class Problem1
{
    public static void main (String args[])
    {
 Random random = new Random();
 int a = random.nextInt(1000) + 1;
 Scanner scan = new Scanner(System.in);
 int guess = 0;
 while (a != guess)
 {
            System.out.println("Guess the number between 1 and 1000:");
            guess = scan.nextInt();
            if (guess < a)
  System.out.println("Too cold!");
            else
  System.out.println("Too hot!");
 }
 if (a == guess)
            System.out.println("Congratulations!");
   
    }
}


No comments :

Post a Comment

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact