I am supposed to write a program that selects a random number between user given constraints, and asks the user to input guesses as to what this number is. The program gives feedback to the user as to whether or not the number is higher or lower than the user's guesses. The number of guesses, the number of games, the total guesses used throughout all of the games, and the lowest number of guesses used in one game are recorded.
These results are printed. The functions that responsible for running the game (playGame()) and the functions responsible for printing these results (getGameResults()) must be in two separate methods.
My problem is, I am not sure how to get the local variables that are modified throughout the course of the method playGame() to the getGameResults() method.
getGameResults() is intended to be called in another method, continuePlayTest(), which tests the user's input to determine whether or not they wish to continue playing the game, so I don't think that calling getGameResults() will work, otherwise this test will not work either. Unless I call continuePlayTest() in playGame(), but continuePlayTest() calls playGame() in its code so that would complicate things.
We can use ONLY the concepts that we've learned. We cannot use any concepts ahead.
So far, we've learned how to use static methods, for loops, while loops, if/else statements and variables. Global variables are bad style, so they cannot be used.
CODE:
public class Guess {
public static int MAXIMUM = 100;
public static void main(String[] args) {
boolean whileTest = false;
gameIntroduction();
Scanner console = new Scanner(System.in);
playGame(console);
}
// Prints the instructions for the game.
public static void gameIntroduction() {
System.out.println("This process allows you to play a guessing game.");
System.out.println("I will think of a number between 1 and");
System.out.println(MAXIMUM + " and will allow you to guess until");
System.out.println("you get it. For each guess, I will tell you");
System.out.println("whether the right answer is higher or lower");
System.out.println("than your guess.");
System.out.println();
}
//Takes the user's input and compares it to a randomly selected number.
public static void playGame(Scanner console) {
int guesses = 0;
boolean playTest = false;
boolean gameTest = false;
int lastGameGuesses = guesses;
int numberGuess = 0;
int totalGuesses = 0;
int bestGame = 0;
int games = 0;
guesses = 0;
games++;
System.out.println("I'm thinking of a number between 1 and " + MAXIMUM + "...");
Random number = new Random();
int randomNumber = number.nextInt(MAXIMUM) + 1;
while (!(gameTest)){
System.out.print("Your guess? ");
numberGuess = console.nextInt();
guesses++;
if (randomNumber < numberGuess){
System.out.println("It's lower.");
} else if (randomNumber > numberGuess){
System.out.println("It's higher.");
} else {
gameTest = true;
}
bestGame = guesses;
if (guesses < lastGameGuesses) {
bestGame = guesses;
}
}
System.out.println("You got it right in " + guesses + " guesses");
totalGuesses += guesses;
continueTest(playTest, console, games, totalGuesses, guesses, bestGame);
}
public static void continueTest(boolean test, Scanner console, int games, int totalGuesses, int guesses, int bestGame) {
while (!(test)){
System.out.print("Do you want to play again? ");
String inputTest = (console.next()).toUpperCase();
if (inputTest.contains("Y")){
playGame(console);
} else if (inputTest.contains("N")){
test = true;
}
}
getGameResults(games, totalGuesses, guesses, bestGame);
}
// Prints the results of the game, in terms of the total number
// of games, total guesses, average guesses per game and best game.
public static void getGameResults(int games, int totalGuesses, int guesses, int bestGame) {
System.out.println("Overall results:");
System.out.println("\ttotal games = " + games);
System.out.println("\ttotal guesses = " + totalGuesses);
System.out.println("\tguesses/games = " + ((double)Math.round(guesses/games) * 100)/100);
System.out.println("\tbest game = " + bestGame);
}
}
If you cannot use "global" variables, I guess your only option is passing parameters when calling the method. If you don't know how to declare and use methods with parameters, I don't know another answer.
EDIT/ADD
After you specified your question, circumstances and posted your code I got a working solution including comments.
public class Guess {
public static int MAXIMUM = 100;
public static void main(String[] args) {
boolean play = true; // true while we want to play, gets false when we quit
int totalGuesses = 0; // how many guesses at all
int bestGame = Integer.MAX_VALUE; // the best games gets the maximum value. so every game would be better than this
int totalGames = 0; // how many games played in total
Scanner console = new Scanner(System.in); // our scanner which we pass
gameIntroduction(); // show the instructions
while (play) { // while we want to play
int lastGame = playGame(console); // run playGame(console) which returns the guesses needed in that round
totalGames++; // We played a game, so we increase our counter
if (lastGame < bestGame) bestGame = lastGame; // if we needed less guesses last round than in our best game we have a new bestgame
totalGuesses += lastGame; // our last guesses are added to totalGuesses (totalGuesses += lastGame equals totalGuesses + totalGuesses + lastGame)
play = checkPlayNextGame(console); // play saves if we want to play another round or not, whats "calculated" and returned by checkPlayNextGame(console)
}
getGameResults(totalGames, totalGuesses, bestGame); // print our final results when we are done
}
// Prints the instructions for the game.
public static void gameIntroduction() {
System.out.println("This process allows you to play a guessing game.");
System.out.println("I will think of a number between 1 and");
System.out.println(MAXIMUM + " and will allow you to guess until");
System.out.println("you get it. For each guess, I will tell you");
System.out.println("whether the right answer is higher or lower");
System.out.println("than your guess.");
System.out.println();
}
// Takes the user's input and compares it to a randomly selected number.
public static int playGame(Scanner console) {
int guesses = 0; // how many guesses we needed
int guess = 0; // make it zero, so it cant be automatic correct
System.out.println("I'm thinking of a number between 1 and " + MAXIMUM + "...");
int randomNumber = (int) (Math.random() * MAXIMUM + 1); // make our random number. we don't need the Random class with its object for that task
while (guess != randomNumber) { // while the guess isnt the random number we ask for new guesses
System.out.print("Your guess? ");
guess = console.nextInt(); // read the guess
guesses++; // increase guesses
// check if the guess is lower or higher than the number
if (randomNumber < guess)
System.out.println("It's lower.");
else if (randomNumber > guess)
System.out.println("It's higher.");
}
System.out.println("You got it right in " + guesses + " guesses"); // Say how much guesses we needed
return guesses; // this round is over, we return the number of guesses needed
}
public static boolean checkPlayNextGame(Scanner console) {
// check if we want to play another round
System.out.print("Do you want to play again? ");
String input = (console.next()).toUpperCase(); // read the input
if (input.contains("Y")) return true; // if the input contains Y return true: we want play another round (hint: don't use contains. use equals("yes") for example)
else return false; // otherwise return false: we finished and dont want to play another round
}
// Prints the results of the game, in terms of the total number
// of games, total guesses, average guesses per game and best game.
public static void getGameResults(int totalGames, int totalGuesses, int bestGame) {
// here you passed the total guesses twice. that isnt necessary.
System.out.println("Overall results:");
System.out.println("\ttotal games = " + totalGames);
System.out.println("\ttotal guesses = " + totalGuesses);
System.out.println("\tguesses/games = " + ((double) (totalGuesses) / (double) (totalGames))); // cast the numbers to double to get a double result. not the best way, but it works :D
System.out.println("\tbest game = " + bestGame);
}
}
Hope I could help.
Is it a problem passing the variables between functions? ex:
public static void getGameResults(int games, int totalGuesses, int guesses, int bestGame) {
// implementation
}
Another option, assuming this is all in one class, is using private static memeber variables. They aren't global. Then again, they might be considered 'global' by your teacher for this assignment.
Given that you've only learnt how to use static methods, your only option is to pass the information from function to function via its arguments.
Related
I am having a problem with my program. When I compile and run my program everything runs great until it's time to display the guesses back to the user. when that happens the last guess always gets displayed as 0.
My assignment is to develop a program that simulates the high-low game. For each execution of the program, the game will generate a random number in the inclusive range of 1 to 100. The user will have up to 10 chances to guess the value. The program will keep track of all the user’s guesses in an array. For each guess, the program will tell the user if his/her guess was too high or too low. If the user is successful, the program will stop asking for guesses, display the list of guesses, and show a congratulatory message stating how many guesses he/she took. If the user does not guess the correct answer within 10 tries, the program will display the list of guesses and show him/her the correct value with a message stating that he/she was not successful. Regardless of the outcome, the program will give the user a chance to run the program again with a new random number.
This is what I have so far:
import java.util.Random;
import java.util.Scanner;
/**
*
* #author jose
*/
public class Assignment7
{
/*
*/
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int number;
String again = "y";
while (again.equalsIgnoreCase("y"))
{
int[] guesses = new int[10];
int tries = 0;
number = GetRandomNumber(1, 100);
System.out.println(number); // delete before submitting
int userGuess = GetUserGuess(1,100);
while (userGuess != number && tries < guesses.length - 1 )
{
guesses[tries] = userGuess;
LowOrHigh(number, userGuess);
userGuess = GetUserGuess(1, 100);
tries++;
}
if (tries != 10)
{
userGuess = guesses[tries];
tries++;
System.out.println("Congratulations! You were able to guess the correct number");
}
else
{
System.out.println("Sorry! You were not able to guess the correct number");
}
if (tries == 10)
{
System.out.println("Your guesses were incorrect");
System.out.print("You guessed: ");
for ( int i = 0; i < 10 ; i++)
{
System.out.print(guesses[i] + ", ");
}
System.out.println("The random number generated was " + number);
}
else
{
System.out.println("Well done! You were able to guess the "
+ "correct number in under 10 tries");
System.out.print("You guessed: ");
for ( int i = 0; i < tries; i++)
{
System.out.print(guesses[i] + " ");
}
System.out.println("The random number generated was "
+ number + ", it only took you " + tries + " tries.");
}
System.out.println("");
System.out.print("Do you wish to try again with a different "
+ "number? (Enter y or n ): ");
again = input.next();
System.out.println("");
}
}
/*
METHOD 1
Description
A method that generates the random number to be guessed returns the
random number to main. Two parameters are the two numbers needed to generate
the random number (1 and 100 in this case).
*/
public static int GetRandomNumber (int rangeLow, int rangeHigh)
{
Random gen = new Random();
int number;
number = gen.nextInt(rangeHigh) + rangeLow;
return number;
}
/*
METHOD 2
This method tells the user if the guess is too low or too high. It will have
2 parameters one for the random number and the second is the user guess.
*/
public static void LowOrHigh (int number, int userGuess )
{
if (userGuess > number )
{
System.out.println("The value that you guessed is too high, "
+"Try guessing a lower number. ");
System.out.println("");
}
else if (userGuess < number )
{
System.out.println("The value that you guessed is too low, "
+"Try guessing a higher number. ");
System.out.println("");
}
}
/*
METHOD 3
This method will get the user guess. It has 2 parameters which will be the
valid range the user should guess between (in this case 1 and 100). It will
return the users guess as an integer. This method should validate that the
users guess is between the two parameters.
*/
public static int GetUserGuess(int rangeLow, int rangeHigh)
{
Scanner scan = new Scanner(System.in);
int userGuess;
System.out.print("Enter a number between " + rangeLow + " and " + rangeHigh + ": ");
userGuess = scan.nextInt();
while (userGuess > rangeHigh || userGuess < rangeLow)
{
System.out.println("The number given was not within the range, Try again ");
System.out.println("");
System.out.print("Enter a number between " + rangeLow + " and " + rangeHigh + ": ");
userGuess = scan.nextInt();
}
return userGuess;
}
}
I'm sorry if its obvious im still pretty new to programming.
Whenever you store a guess, you always store it in guesses[tries], and then immediately afterwards, you increment tries. Your while condition then checks if tries is less than guess.length - 1.
More generally, to program you need to know how to debug. Debugging is generally the act of following along with the code and checking what it actually does vs. what you wanted it to do. You can use a debugger for this, alternatively, you can add a boatload of System.out statements to follow along.
Do that, and you'll find the error in your logic. I've already given you quite a sizable hint in the first paragraph ;)
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
It looks like the Scanner is being used correctly here and being assigned to a variable correctly but I Cannot figure out what is going on. When I play this game in the code, the INT gets pulled in just fine. The strings will not get pulled in for some reason and even if I hardcode "yes" for the string it still exits the code.
package testTraining;
import java.util.Scanner;
public class GuessingGame {
static int gamesPlayed; // The number of games played.
static int gamesWon; // The number of games won.
public static void main(String[] args) {
gamesPlayed = 0;
gamesWon = 0; // This is actually redundant, since 0 is
// the default initial value.
System.out.println("Let's play a game. I'll pick a number between");
System.out.println("1 and 100, and you try to guess it.");
String yesno = "yes";
Scanner yesScan = new Scanner(System.in);
do {
playGame(); // call subroutine to play one game
System.out.print("Would you like to play again? ");
yesno = yesScan.next();
} while (yesno == "yes");
System.out.println();
System.out.println("You played " + gamesPlayed + " games,");
System.out.println("and you won " + gamesWon + " of those games.");
System.out.println("Thanks for playing. Goodbye.");
} // end of main()
static void playGame() {
Scanner guessScan = new Scanner(System.in);
int computersNumber; // A random number picked by the computer.
int usersGuess; // A number entered by user as a guess.
int guessCount; // Number of guesses the user has made.
gamesPlayed++; // Count this game.
computersNumber = (int)(100 * Math.random()) + 1;
// The value assigned to computersNumber is a randomly
// chosen integer between 1 and 100, inclusive.
guessCount = 0;
System.out.println();
System.out.print("What is your first guess? ");
while (true) {
usersGuess = guessScan.nextInt(); // Get the user's guess.
guessCount++;
if (usersGuess == computersNumber) {
System.out.println("You got it in " + guessCount
+ " guesses! My number was " + computersNumber);
gamesWon++; // Count this win.
break; // The game is over; the user has won.
}
if (guessCount == 6) {
System.out.println("You didn't get the number in 6 guesses.");
System.out.println("You lose. My number was " + computersNumber);
break; // The game is over; the user has lost.
}
// If we get to this point, the game continues.
// Tell the user if the guess was too high or too low.
if (usersGuess < computersNumber)
System.out.print("That's too low. Try again: ");
else if (usersGuess > computersNumber)
System.out.print("That's too high. Try again: ");
}
System.out.println();
} // end of playGame()
} // end of class GuessingGame
You need to compare strings with .equals("yes") instead of == "yes"
I'm generally new to programming and just started programming in Java a few days ago so I'm not sure if what I'm trying to accomplish is even possible with the way my program is coded.
I'm basically writing a program that asks for a "Strength" value between 0 and 9. It asks you to choose a weapon ((1) Knife is the only one available). It takes that information and generates a random damage ratio between 1-3 plus what ever number your strength is and is supposed to keep subtracting that value from 20 until it hit 0 then quits.
The problem is that I'm stuck in a loop. It subtracts the value from 20, but starts over and keeps subtracting from 20 again rather than storing the subtracted number.
Does anyone have any advice on how something like this would be accomplished? Any help is very much appreciated. This is my code so far....
package untitledgame;
import java.util.Random;
import java.util.Scanner;
public class UntitledGame {
public static void main(String[] args){
int pStrength, wKnife, damage, enemyDamage;
Scanner in = new Scanner(System.in); //used for next to int inputs
System.out.println("Choose Your Strength (0-9)");
pStrength = in.nextInt();
System.out.println("Your Strength Is "+pStrength);
System.out.println("Choose Your Weapon; (1)Knife");
wKnife = in.nextInt();
System.out.println("Press ENTER to battle...");
Scanner scanner = new Scanner(System.in); //waits for users to continue
scanner.nextLine();
if (wKnife == 1){
do {
int enemyHP = 20;
Random rn = new Random(); //Random generator
wKnife = rn.nextInt(3) + 1; //Randomly generates knife damage
damage = wKnife + pStrength; //Damage logic
System.out.println("Attack with knife has done: " ); //Knife damage
System.out.print(+damage);
System.out.print(" damage." );
System.out.println("");
enemyDamage = enemyHP - damage; // Remaing HP
System.out.println("Enemy has ");
System.out.print(+enemyDamage);
System.out.print(" HP left.");
System.out.println("");
System.out.println("Press Enter to Attack...");
scanner.nextLine();
}
while (enemyDamage > 0);
System.out.println("Enemy has been defeated.");
}
}
}
Declare this int enemyHP = 20; outside the do-while loop. Right now, you're resetting enemyHP to 20 every single time you iterate through the loop.
Also, you should not recreate your Random within the do-while loop. Do that before entering the do block.
There are other issues with the logic that Jonah Haney deals with in his answer.
You'll want to initialize your enemyHP variable OUTSIDE of the do-while loop, or it will reset enemyHP back to 20 every time it loops.
Declare int enemyHP = 20 before the beginning of the loop. Then your loop is missing the following line:
enemyHP = enemyHP - damage;
Also, it seems that you want the loop to keep running until the enemy has been defeated. If that is the case, then your condition should check to see if enemyHP has been drained all the way, like this:
}
while (enemyHP > 0); //instead of while (enemyDamage > 0);
EDIT
This is what your code SHOULD look like. I am not saying you should copy it straight into your project. I am saying that you should take a look at the differences and it will help you see the logic problems in your own code:
public static void main(String[] args){
int pStrength, wKnife, damage, enemyDamage;
Scanner in = new Scanner(System.in); //used for next to int inputs
System.out.println("Choose Your Strength (0-9)");
pStrength = in.nextInt();
System.out.println("Your Strength Is " + pStrength);
System.out.println("Choose Your Weapon; (1)Knife");
wKnife = in.nextInt();
System.out.println("Press ENTER to battle...");
in.nextLine();
in.nextLine();
Random rn = new Random(); //Random generator
int enemyHP = 20;
if (wKnife == 1){
do {
System.out.println("Press Enter to Attack...");
in.nextLine();
wKnife = rn.nextInt(3) + 1; //Randomly generates knife damage
damage = wKnife + pStrength; //Damage logic
System.out.println("Attack with knife has done: " + damage + " damage."); //Knife damage
enemyHP -= damage; // Calculate Remaining HP
System.out.println("Enemy has " + enemyHP + " HP left.");
} while (enemyHP > 0);
System.out.println("Enemy has been defeated.");
in.close();
}
}
import java.util.*;
public class Guess {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
Random r = new Random();
intro();
int numGames = 0;
int numGuesses = game(console, r);
int max = max(numGuesses);
String again = "y";
do {
game(console, r);
System.out.println("Do you want to play again?");
again = console.next();
System.out.println();
numGames++;
} while (again.startsWith("y") || again.startsWith("Y"));
stats(numGames, numGuesses, max);
}
public static void intro() {...}
public static int game(Scanner console, Random r) {
System.out.println("I'm thinking of a number between 1 and 100...");
int answer = r.nextInt(100) + 1;
System.out.println("answer = " + answer);
int guess = -1;
int numGuesses = 0;
while (answer != guess) {
System.out.print("Your guess? ");
guess = console.nextInt();
numGuesses++;
if (guess > answer) {
System.out.println("It's lower.");
} else if (guess < answer) {
System.out.println("It's higher.");
} else {
System.out.println("You got it right in " + numGuesses + " guesses");
}
max(numGuesses);
}
return numGuesses;
}
public static int max(int numGuesses) {
int max = numGuesses;
if (max > numGuesses) {
max = numGuesses;
}
return max;
}
public static void stats(int numGames, int numGuesses, int max) {
System.out.println("Overall results:");
System.out.println(" total games = " + numGames);
System.out.println(" total guesses = " + numGuesses);
System.out.println(" guesses/game = " + numGuesses / numGames / 1.0);
System.out.println(" best game = " + max);
}
}
So this is a small part of my program and the problem I'm having is that my initial int for numGuesses (int numGuesses = game(console, r);) is executing the game method shown below.
All I want from the game method is the return value of numGuesses so that I can forward the value into a different method called stats(numGames, numGuesses, max); . How do I make it so that the initial value isn't executing the method and only the do/while loop is?
Is the way I produce a return statement wrong? Also, my return values aren't saving in my stats method so when I run it, I get the wrong answers.
Then you should put the code that's responsible of generating numGuesses in another method that you will use on both main and game, for example:
public static int game(Scanner console, Random r) {
int numGuesses = getNumberOfGuesses(..);
//continue implementation here
}
public static void main(String[] args) {
int numGuesses = getNumberOfGuesses(..);
//use value
}
You should get familiar with class variables. At the top of your class, you can declare a variable and also give it a value. That is what you should do with numGuesses if you want to access it from different methods in your class. Here is the Foobar example:
class Foo {
private int bar = 0;
private void foobar(int arg) {...}
}
You just need to watch out that you don't do int numGuesses somewehere in a method as that would create a second local variable. The class variable can be accessed via just the name.
Next, you want to keep track of the total games played and the total guesses. You can guess now (hahaha), that you need to use class variables as well. If you need to keep track of the total guesses even when the program is restarted you will need to store these values in a file, but that will be for another time.
Finally, two more little things.
1.) The method max. I do not know what max should do, but at the moment it is just returning the value passed to it. Also the if statement will never execute (x can't be higher than x).
2.) You should maybe consider not making everything static. It obviously works that way, but that is not, what is called object-oriented programming.
I am trying to code a number guessing class and client.
The issue/problems I am having with this class/client is that my number guess either ends up too high or too low and in top of that it loops the number twice when it should once.
Number generated from 0 to 100. Wanna take a guess(enter 0 to give up)
Let's take a guess:
50
40
Your guess is too low
What possible change can I make to improve the overall loop or change.
Here is my code for anyone that wants to look at it.
import java.util.Random;
public class NumberGuess
{
private Random generator;
private int Number;
int intGuess= (1 + (int)(Math.random()*100));
int numGuess=0;
boolean isGuessCorrect=false;
public NumberGuess(){
}
int numguess;
public int guess(int guessIn){
int numguess=guessIn;
if(numguess>intGuess){
return 1;
}else if(isGuessCorrect){
return 0;
}else{
return -1;
}
}
public int getNumberofGuesses(){
return numGuess;
}
public boolean gameIsComplete(){
if(isGuessCorrect){
return true;
}else{
return false;
}
}
public void reset(){
intGuess=(1 + (int)(Math.random()*100));
numGuess=0;
isGuessCorrect=false;
}
}
Client class
import java.util.Scanner;
public class NumberGuessclient{
public static void main(String[] args){
NumberGuess game1=new NumberGuess();
Scanner scan = new Scanner(System.in);
int quit=1;
while(quit != 0) {
System.out.println("Number generated from 0 to 100. Wanna take a guess(enter 0 to give up)");
System.out.println("Let's take a guess: ");
int guess1= scan.nextInt();
while((guess1 != 0)||(!game1.gameIsComplete())) {
guess1 = scan.nextInt();
if (game1.guess(guess1)==1){
System.out.println("Your guess is too high");
}
else if(game1.guess(guess1)==-1) {
System.out.println("Your guess is too low");
}
else { System.out.println("guessed in " + game1.getNumberofGuesses() + " tries");
}
}
System.out.println("Enter 1 for new game, 0 to quit: ");
quit = scan.nextInt();
if(quit==1){
game1.reset();
}
}
}
}
source code for more ELABORATION if not clarified above.
NumberGuess Class:
The NumberGuess class will facilitate a number guessing game. The constructor should generate a random number, saving the number in a private class field. The class should also define a method which accepts a "guess", compares the "guess" to the randomly generated number, and returns one of the following:
• -1 the guess was less than the secret number
• 0 the guess matched the secret number
• 1 the guess was higher than the secret number
Determine whether other methods, constructors or otherwise, would be useful for this class.
The Java API defines a Random class for generating random numbers. The class can be reviewed in the API or in your textbook beginning on page 250. Consider limiting the range of the random number. For instance, a number between 0 and 100.
Client Application:
The client application allows the end-user to play the number guessing game. Below is a sample run. Your application does not need to match.
I'm thinking of a number between 0 and 100. Can you guess it?
Take a guess: 50
Your guess is too high
Another guess? (Y or N): y
Take a guess: 25
Your guess is too high
Another guess? (Y or N): y
Take a guess: 10
Your guess is too low
Another guess? (Y or N): y
Take a guess: 15
Your guess is too low
Another guess? (Y or N): y
Take a guess: 18
Your guess is too low
Another guess? (Y or N): y
Take a guess: 20
Congratulations! You correctly guessed the secret number in 6 tries.
There are quite a bit of things that you can change, for instance:
There's no need to call game1.guess(guess1) more than once every loop.
The completion method is quite long...
You should call scan.nextInt() before entering the while loop...
I'm assumming the last output was manually generated, because you never increment numguess
The guess(int) method doesn't work...
I'm not usually one to do homework... but (I'm having a good day...!):
import java.util.Random;
import java.util.Scanner;
public class NumberGuessclient {
private static final String[] ANS = {
"Your guess is too low\n",
"guessed in %d tries\n",
"Your guess is too high\n"
};
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (true) {
NumberGuess game = new NumberGuess();
System.out.println("Number generated from 0 to 100. Wanna take a guess(enter 0 to give up)");
System.out.println("Let's take a guess: ");
while (!game.isGameComplete()) {
System.out.format(ANS[game.guess(scan.nextInt())+1], game.getNumberofGuesses());
}
System.out.println("Enter 1 for new game, 0 to quit: ");
if (scan.nextInt() != 1) {
System.out.println("Bye!");
System.exit(0);
}
}
}
}
class NumberGuess {
private static final Random RAND_GENERATOR = new Random(System.nanoTime());
int intGuess = RAND_GENERATOR.nextInt(101);
int numGuess = 0;
boolean isGuessCorrect = false;
public int guess(int guessIn) {
numGuess++;
if (guessIn > intGuess) {
return 1;
} else if (guessIn == intGuess) {
isGuessCorrect = true;
return 0;
} else {
return -1;
}
}
public int getNumberofGuesses() {
return numGuess;
}
public boolean isGameComplete() {
return isGuessCorrect;
}
}
Now one comment: as I recall the "fun" of this game was that you should always "guess" the number in at the very most 10 tries, you could implement that...