-
Notifications
You must be signed in to change notification settings - Fork 7.9k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #873 from Uzma-Shaikh/master
added a guessing game
- Loading branch information
Showing
1 changed file
with
40 additions
and
0 deletions.
There are no files selected for viewing
40 changes: 40 additions & 0 deletions
40
Program's_Contributed_By_Contributors/Java_Programs/Misc/GuessingGame.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
package guessinggame; | ||
* Java game “Guess a Number” that allows user to guess a random number that has been generated. | ||
*/ | ||
import javax.swing.*; | ||
|
||
public class GuessingGame { | ||
public static void main(String[] args) { | ||
int computerNumber = (int) (Math.random()*100 + 1); | ||
int userAnswer = 0; | ||
System.out.println("The correct guess would be " + computerNumber); | ||
int count = 1; | ||
|
||
while (userAnswer != computerNumber) | ||
{ | ||
String response = JOptionPane.showInputDialog(null, | ||
"Enter a guess between 1 and 100", "Guessing Game", 3); | ||
userAnswer = Integer.parseInt(response); | ||
JOptionPane.showMessageDialog(null, ""+ determineGuess(userAnswer, computerNumber, count)); | ||
count++; | ||
} | ||
} | ||
|
||
public static String determineGuess(int userAnswer, int computerNumber, int count){ | ||
if (userAnswer <=0 || userAnswer >100) { | ||
return "Your guess is invalid"; | ||
} | ||
else if (userAnswer == computerNumber ){ | ||
return "Correct!\nTotal Guesses: " + count; | ||
} | ||
else if (userAnswer > computerNumber) { | ||
return "Your guess is too high, try again.\nTry Number: " + count; | ||
} | ||
else if (userAnswer < computerNumber) { | ||
return "Your guess is too low, try again.\nTry Number: " + count; | ||
} | ||
else { | ||
return "Your guess is incorrect\nTry Number: " + count; | ||
} | ||
} | ||
} |