-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumberGuessingGame.java
More file actions
69 lines (60 loc) · 2.46 KB
/
Copy pathNumberGuessingGame.java
File metadata and controls
69 lines (60 loc) · 2.46 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/*******************************************
* NumberGuessingGame.java
* Asks user to guess a number between 1-100
* checks that guess against randomly generated
* number and gives feedback until 7 tries or
* the user guesses the number correctly
********************************************/
import java.util.Scanner;
public class NumberGuessingGame
{
public static void main (String[] args) //start main method
{
Scanner stdIn = new Scanner(System.in);
int generatedRandomNum = randomNumGen(); //store random num
int count = 1; //initialize count
System.out.print("Guess a number between 1 and 100. \n\nWhat's your guess? "); //input first user guess
int intGuess = stdIn.nextInt();
while (intGuess != generatedRandomNum && count <= 7) //while guess not correct && guess count <= 7
{
System.out.print(findGeneratedNum(intGuess, generatedRandomNum, count)); //inform user high/low
count++;
if (count <= 7)
{
System.out.print("What's your guess? "); //input next user guess
intGuess = stdIn.nextInt();
}
}
if (intGuess == generatedRandomNum && count <= 7) //if user guesses correct && guess count <= 7
{
System.out.print(findGeneratedNum(intGuess, generatedRandomNum, count));
}
else
{
System.out.print("Too bad so sad\n\n"); //else user guess count > 7 inform user
}
} //end main method
//**********************************************
//This method calculates a random # from 1-100
public static int randomNumGen()
{
return (int) (Math.random() * 100) + 1; //generate random num from 1-100
}
//**********************************************
//**********************************************
//This method tracks and compares user input to
//generatedRandomNum()
public static String findGeneratedNum(int guess, int randomNum, int count)
{
if (guess < randomNum) //test if user guess lower than random num
{
return "\nThat's too low\n\n"; //return msg
}
else if (guess > randomNum) //test if user guesss higher than random num
{
return "\nThat's too high!\n\n"; //return msg
}
return "\nWow, you guessed it in " + count + " tries.\n\n"; //if user guess not higher or lower return msg
}
//**********************************************
}//end class