forked from TimSongCoder/LearnJavaForAndroid
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGuess.java
More file actions
38 lines (35 loc) · 1.19 KB
/
Copy pathGuess.java
File metadata and controls
38 lines (35 loc) · 1.19 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
import java.util.Random;
import java.io.IOException;
/**
* 1. Use Random to generate a integer from 0 to 25, both inclusively.
* 2. Repeatedly ask the user to guess the integer by entering a letter from a to z.
* 3. Compare the user entered letter with the random integer, the offset by lowercase letter a(0-25),
* output message if user guess right or wrong, low or high.
*/
public class Guess{
public static void main(String[] args){
Random random = new Random();
int number = random.nextInt(26);
number += 'a';
System.out.println("Please Guess the hidden number in the black box, using lowercase letter a-z representing 0-25:");
int userGuess = -1;
do{
try{
userGuess = System.in.read();
}catch(IOException ioe){
ioe.printStackTrace();
System.out.println("Error, try again.");
continue;
}
if(userGuess == '\r' || userGuess == '\n'){
continue;
}
if(userGuess > number){
System.out.println("Too high, guess again:");
}else if( userGuess < number){
System.out.println("Too low, guess again:");
}
}while(userGuess != number );
System.out.println("Congratulations, you are right :) The number in the box is: " + (userGuess - 'a'));
}
}