-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGuessNumber.java
More file actions
43 lines (42 loc) · 1.21 KB
/
GuessNumber.java
File metadata and controls
43 lines (42 loc) · 1.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import java.util.Random;
import java.util.Scanner;
public class GuessNumber{
// instance variables
int numberToGuess;
int counts=0;
int maxNumber=9;
int minNumber=1;
// constructor
public GuessNumber(){
Random random = new Random();
numberToGuess=random.nextInt(maxNumber)+minNumber;
}
// compare method
public void compare(int guess){
counts++;
if(guess<numberToGuess){
System.out.println("Too small! Try again.");
}else if(guess>numberToGuess){
System.out.println("Too big! Try again.");
}else{
System.out.println("Congratulations! You've guessed the number "+numberToGuess+" in "+counts+" tries.");
}
}
// play method
public void play(){
Scanner scanner = new Scanner(System.in);
int guess=-1;
while(guess!=numberToGuess){
System.out.print("Enter your guess ("+minNumber+"-"+maxNumber+"): ");
guess=scanner.nextInt();
counts++;
compare(guess);
}
scanner.close();
}
// main method
public static void main(String[] args){
GuessNumber game1 = new GuessNumber();
game1.play();
}
}