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:
"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
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