package edu.blastermind.model;
import java.util.Random;
/**
* A NumberGuessingGame represents the rules of a simple "guess the number" type game.
*
* #author
*
*/
public class GuessTheNumberGame {
private int highest;
private int secret;
/**
* Creates a new NumberGuessingGame with a secret number between 0 and highest.
*
* #param highest the highest possible number for this game. Must be > 0.
*/
public GuessTheNumberGame(int highest) {
// TODO 1: perform a precondition check on the parameter highest
if (highest <= 0) {
throw new IllegalArgumentException
("highest number must be at least 1");
}
this.highest = highest;
Random rng = new Random();
this.secret = rng.nextInt(highest + 1);
}
/**
* Checks to see if we've guessed correctly.
*
* #param guess our guess (must be between 0 and getHighest())
* #return true if the guess was correct, false otherwise
*/
public boolean isGuessCorrect(int guess) {
// TODO 2: perform a precondition check on the variable guess
if (guess > this.highest || guess < 0) {
throw new IllegalArgumentException
("Guess must be between 1 and 100");
}
return this.secret == guess;
}
/**
* Checks to see if our guess is higher than the secret.
*
* #param guess our guess (must be between 0 and getHighest())
* #return true if our guess is higher than the secret, false otherwise
*/
public boolean isGuessHigher(int guess) {
// TODO 3: perform a precondition check on the variable guess
if (guess > this.highest || guess < 0) {
throw new IllegalArgumentException
("Guess must be between 1 and 100");
}
return this.secret < guess;
}
/**
* Returns the highest value in the range of valid guesses.
*
* #return the highest value in the range of valid guesses
*/
public int getHighest() {
return this.highest;
}
}
package edu.blastermind.controllers;
import java.util.Scanner;
import edu.westga.blastermind.model.GuessTheNumberGame;
public class GuessTheNumber {
public static void main(String[] args) {
GuessTheNumberGame game = new GuessTheNumberGame(100);
int turns = 1;
Scanner kb = new Scanner(System.in);
System.out.println("Guess a nummber between 0 and 100");
int guess = kb.nextInt();
// TODO 4: loop as long as the guess is not correct
while (!game.isGuessCorrect(guess)) {
guess++;
if (game.isGuessHigher(guess)){
System.out.println("You guessed too high!");
turns++;
}
else if (!game.isGuessCorrect(guess)){
System.out.println("You guessed too low!");
}
int GuessTheNumber = kb.nextInt();
}
turns++;
// TODO 5: in the loop, check guesses and give hints
System.out.printf("You guessed the number in %d turns\n", turns);
}
}
Hey everyone> I am writing a guess the secret number program in java and I am having some problems. I keep getting that my guess is too high when I run the program the first time and after I terminate the program and run it again it says my guess is too low. In the while loop it is suppose to loop as long as the guess is the wrong number which I believe it is doing but I am obviously doing something wrong. Any help is appreciated, thanks in advance.
Your loop checks the correctness of guess. And if guess is incorrect, you read a new value from the command line and assign it to GuessTheNumber, instead of assigning it to guess.
I also don't understand why you're doing guess++. It doesn't make sense.
Fixing your main method. You missed a little bit the variables, adding one to guess. And you were always checking on the first input by the user.
public static void main(String[] args) {
GuessTheNumberGame game = new GuessTheNumberGame(100);
int turns = 0;
Scanner kb = new Scanner(System.in);
// TODO 4: loop as long as the guess is not correct
while (true) {
System.out.println("Guess a nummber between 0 and 100");
int guess = kb.nextInt();
if (game.isGuessHigher(guess)) {
System.out.println("You guessed too high!");
} else if (!game.isGuessCorrect(guess)) {
System.out.println("You guessed too low!");
}
turns++;
if (game.isGuessCorrect(guess)) break;
}
// TODO 5: in the loop, check guesses and give hints
System.out.printf("You guessed the number in %d turns\n", turns);
}
Related
I'm creating a high/low guessing game as part of a study assignment, and the part im stuck at is getting the amount of guesses returned to the main method. We have specifically been told that the main method has to print the number of guesses, while the method "playGame" actually does the playing.
There's more to the code, a method called giveReponse that checks if the number is correct or too high/low, but it works as intended. I get "Cannot find symbol" when trying to print how many guesses it took to complete the game.
If it wasn't so important to print it in the main method I'd print the amount in the method playGame, but thats a no-go. What am I doing wrong?
The code looks like this:
public class HiLo {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Welcome to classic guessing game of high/low!");
String difficulty = scan.next();
if (difficulty.equals("easy")) {
playGame(10);
} else if (difficulty.equals("medium")) {
playGame(100);
} else if (difficulty.equals("hard")) {
playGame(1000);
}
System.out.println("You won in" + guesses + "attempts.");
}//EndsMain
public static int playGame(int maxNumber) {
Scanner scan = new Scanner(System.in);
int rannr = (int)(Math.random() * maxNumber) +1;
int answer = rannr;
int guess = 0;
int guesses = 0;
System.out.println("Game is starting...");
do {
guess = scan.nextInt();
guesses ++;
giveResponse(answer, guess);
if (answer == guess) {
break;
}
} while (answer != guess);
return guesses;
} //Ends playGame
Your method playGame( ) is returning a value but since is not assigned to no variable, those returns are getting lost...
additional to that it looks like the code is not complete:
this statement is not going to let you compile:
System.out.println("You won in" + guesses + "attempts.");
because the only guesses variable I see in there is scoped in the playGame method....
do instead something like:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Welcome to classic guessing game of high/low!");
int guesses = 0;
String difficulty = scan.next();
if (difficulty.equals("easy")) {
guesses = playGame(10);
} else if (difficulty.equals("medium")) {
guesses = playGame(100);
} else if (difficulty.equals("hard")) {
guesses = playGame(1000);
}
The problem is at:
System.out.println("You won in" + guesses + "attempts.");
Since the variable guesses is not defined in the main method, the compiler doesn't know what you are referencing to with that symbol.
But since playGame() returns the number of guesses, I'd recommend something like this:
if (difficulty.equals("easy")) {
System.out.println("You won in" +playGame(10)+ "attempts.");
} else if (difficulty.equals("medium")) {
System.out.println("You won in" +playGame(100)+ "attempts.");
} else if (difficulty.equals("hard")) {
System.out.println("You won in" +playGame(1000)+ "attempts.");
}
Here's a solution that shows how easy it would be to restrict guesses. Not much extra effort or thought:
package games;
import java.util.Random;
import java.util.Scanner;
/**
* HiLo guessing game
* Created by Michael
* Creation date 4/9/2016.
* #link https://stackoverflow.com/questions/36522303/java-creating-hi-low-game-using-multiple-methods-stuck-at-returning-no-of-gu
*/
public class HiLo {
public static void main(String [] args) {
int maxValue = (args.length > 0) ? Integer.parseInt(args[0]) : 100;
int maxGuesses = (args.length > 1) ? Integer.parseInt(args[1]) : 5;
Scanner scanner = new Scanner(System.in);
String answer = "Y";
do {
play(scanner, maxValue, maxGuesses);
System.out.println("Play again? [Y/N]: ");
answer = scanner.next();
System.out.println(String.format("You answered %s; let's play again!", answer));
} while ("Y".equalsIgnoreCase(answer));
}
private static void play(Scanner scanner, int maxValue, int maxGuesses) {
int value = new Random().nextInt(maxValue) + 1;
int numGuesses = 0;
boolean match = false;
do {
System.out.println(String.format("Guess a value between 1 and %d: ", maxValue));
int guess = Integer.parseInt(scanner.next());
if (guess < value) {
System.out.println(String.format("Too low; guess again. (%d guesses left)", (maxGuesses-numGuesses-1)));
} else if (guess > value) {
System.out.println(String.format("Too high; guess again (%d guesses left)", (maxGuesses-numGuesses-1)));
} else {
match = true;
System.out.println(String.format("You got it right in %d guesses! ", numGuesses+1));
break;
}
} while (!match && ++numGuesses < maxGuesses);
if (!match) {
System.out.println(String.format("The correct answer was %d; you're only allowed %d guesses. Better luck next time!", value, maxGuesses));
}
}
}
First, yes I have researched this question. Yes, I have seen similar things, and have had no problem with that, but this is an added twist and I'm a bit confused. So this is what I'm trying to do:
For each iteration of the loop, toss all coins. If a coin comes up
heads then add the value of the coin to the balance. If a coin comes
up tails then subtract the value of the coin from the balance. After
all iterations, display the balance and the number of seconds it took
to execute the loop formatted to three decimal places.
Coin.java class
import java.util.Random;
public class Coin
{
private String sideUp;
private Random headORtail = new Random();
public Coin() //no-arg constructor to determine what side of the coin is facing up
{
toss(); //calls the toss method
}
public Coin(String whatSide) //parameterized constructor to set initial side of coin
{
sideUp = whatSide;
}
public void toss() //simulates coin toss
{
int num = headORtail.nextInt(2); //random number in the range of 0 - 1
if(num == 0)
{
sideUp = "Heads"; //0 for heads
}
else
{
sideUp = "Tails"; //1 for tails
}
}
public String getSideUp() //returns value of sideUp
{
return sideUp;
}
}
CoinDemo.java
import java.util.Scanner;
public class CoinDemo
{
public static void main(String[] args)
{
//uses parameterized constructor to allow the programmer to set the initial sideUp
Coin penny = new Coin("Tails");
//uses no-arg constructor to create coin objects
Coin nickel = new Coin();
Coin dime = new Coin();
Coin quarter = new Coin();
Coin half = new Coin();
Scanner keyboard = new Scanner(System.in); //Creates a new scanner to allow user to enter input
System.out.println("Please enter the the number of coin flips to be performed.\nMust be greater than 0: ");
int numFlips = keyboard.nextInt(); //Stores the user input into numFlips
//Validation loop checks value entered
while (numFlips <= 0)
{
System.out.println("\n\t~~~ERROR~~~");
System.out.println("The number entered must be greater than 0, please try again.");
System.out.println("\t~~~~~~~~~~~\n");
System.out.println("Please enter the the number of coin flips to be performed. Must be greater than 0: ");
numFlips = keyboard.nextInt(); //stores the user input into numFlips
}
long totalTime = System.currentTimeMillis(); //Once valid number is entered start the timer
double totalCoin;
for (int i = 0; i < numFlips; i++) //for loop to increment until equal to user entered numFlips
{
//calls the Coin object's toss method and stores result in their respective instance variables
penny.toss();
nickel.toss();
dime.toss();
quarter.toss();
half.toss();
}
}
}
My understanding is that after for example penny.toss(); executes in the loop it will either store the string "Heads" or "Tails" in the instance variable penny. So I tried to use
if (penny == "Heads")
{
totalCoin += 0.01;
}
else
{
totalCoin -= 0.01;
}
I'm not sure how else to go about this. I'm fairly new to programming, so please understand I'm trying to learn. That's why I'm here asking for help to understand how to do this.
First thing i saw, when you compare strings, you should do
if (penny.getSideUp().equals("Heads"))
instead of using ==.
Also, you need to compare the sideUp variable, not your class.
I am working on a project where you make a code that has the computer guess a random number, and then the user says if that number is higher or lower. Then the computer is supposed to change its parameters based on what the user says. For example if it guesses 33 and you say too low and it says 74 and it says too high, then the next number generated will be between 33 and 74. My problem is, I can make the range get higher with using the rFinder variable and such when UserAnswer=2 in the RepeatedGuess method. But, though trying many things, I can't get a range that is dynamic or that changes throughout the code. Am I approaching this completely the wrong way? Any suggestions would be helpful.
import java.util.Scanner;
import java.util.Random;
public class Proj72 {
private static int UserAnswer;
private static int maximum = 100;
private static int minimum = 0;
private static int rFinder;
private static Random generator = new Random();
private static Scanner reader = new Scanner(System.in);
private static int guess = generator.nextInt(100);
public static void main(String[] args) {
FirstGuess();
RepeatedGuesses();
Correct();
}
private static void FirstGuess() {
System.out.print(guess + ": Is this your number? Enter 1 For Yes or enter 2 for Too Low or enter 3 for Too High:");
}
private static void RepeatedGuesses() {
while (1 != UserAnswer) {
UserAnswer = reader.nextInt();
if (2 == UserAnswer) {
rFinder = (int)(generator.nextInt(100 - guess));
guess = rFinder + guess;
System.out.print(guess + ": Is this your number? Enter Yes or enter Higher or enter Lower:");
} else if (3 == UserAnswer)
break;
}
}
private static void Correct() {
if (1 == UserAnswer) {
System.out.print("I got it!");
}
}
}
Keep track of the range of values that the guess could be. Call these min and max. Min is equal to 0 and max is equal to 100 at the beginning.
Guess a random int between the min and max
After each guess:
if the number is above the guess, set the min to the guess
if the number is below the guess, set the max to the guess
To progress further, instead of choosing a random guess each time, guess the value in the middle of the min and max values, e.g. 50 for the first guess.
This is then a binary search with O(log(N)) worst and average time!
private static void RepeatedGuesses() {
while (1 != UserAnswer) {
UserAnswer = reader.nextInt();
if (2 == UserAnswer) {
rFinder = (int) (generator.nextInt(100 - guess));
guess = rFinder + guess;
System.out.print(guess + ": Is this your number? Enter Yes or enter Higher or enter Lower:");
} else if (3 == UserAnswer){
break;
}
//change it
FirstGuess();
UserAnswer = reader.nextInt();
}
}
edit 1 - I changed all sc.nextInt to Integer.parseInt(sc.nextLine()) and I now have some errors but less
edit 2 - It now runs but I am something getting things printed 2x, the game does not end at the end of round 10 and I'm missing a total wins line at the end. I think the error occurs after a win.
edit 3 - 2x cold/hot printing fixed. fixed the 2x header (repeat line left in wins method). New (and hopefully last error) - first round the game only allows 3 tries, other rounds 4. sample run:
I will choose a number between 1 and 10
You have 3 tries to get it right
Round 1
Enter a new guess: 5
Cold
5
Cold
5
You lose!
You have won 0 out of 1 rounds.
Round 2
Enter a new guess: 5
Cold
5
Cold
5
Cold
5
You lose!
You have won 0 out of 2 rounds.
Round 3
Enter a new guess: 5
Cold
5
Cold
5
Cold
5
You lose!
You have won 0 out of 3 rounds.
class 1:
import java.util.Scanner;
public class GuessRunner
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("I will choose a number between 1 and 10" +
'\n' + "You have 3 tries to get it right" + '\n');
GuessCalc game = new GuessCalc();
while (game.getRounds() <= 10)
{
System.out.println('\n' + "Round " + game.getRounds() + '\n');
System.out.print("Enter a new guess: ");
int guess = Integer.parseInt(sc.nextLine());
do
{
game.rounds(guess);
guess = Integer.parseInt(sc.nextLine());
}
while (game.roundOver == false);
System.out.println(game.wins());
}
sc.close();
}
}
class 2:
public class GuessCalc
{
private int wins;
private int rounds = 1;
private int num = (int) (1 + Math.random() * 10);
private int tries = 0;
public boolean roundOver;
/**
* Runs the rounds and determines if they win
* #return outcome the boolean true if they won or false if they lost
*/
public String rounds(int guess)
{
if (guess == num) //player won
{
wins++;
rounds++;
tries = 0;
System.out.println("You win!");
num = (int) (1 + Math.random() * 10); //new number
roundOver = true;
}
else if (tries == 3) //out of tries
{
rounds++;
tries = 0;
System.out.println("You lose!");
num = (int) (1 + Math.random() * 10); //new number
roundOver = true;
}
else
{
hotOrCold(guess);
roundOver = false;
}
}
/**
* Tells the player if they are hot or cold
*/
public void hotOrCold(int guess)
{
if (guess == num - 1 || guess == num + 1) //if they are off by 1
System.out.println("Hot");
else // if they are further than 1 away
System.out.println("Cold");
tries++;
}
/**
* Returns the number of wins and makes a new header
* #return the String with the number of wins and new header
*/
public String wins()
{return("You have won " + wins + " out of " + (rounds - 1) + " rounds.");}
/**
* Returns the number of rounds played
* #return rounds the number of rounds
*/
public int getRounds()
{return rounds;}
}
try adding
sc.nextLine(); after sc.nextInt(); which will consume the new line character
The thing with Scanner is that Scanner is very, very strange. I've been using it for years and she hates that I use her for only fast and dirty input. I don't even want to begin to describe the bizarre things that happen, but the explanation is usually around how non-nextLine() methods deal with newline characters (whether they consume/ignore them or not)
My advice with scanner is to only ever use its hasNextLine() and nextLine() methods. They are the only methods I found were every human using them can predict the method's behaviour. You can then check if it is a number (matches("[1-9]+[0-9]*")) or just be wild and do Integer.parseInt() directly.
Seeing
game = new GuessCalc(guess);
is a loop looks strange in class 1. That looks like an error since rounds will be reset constantly.
Edit 1:
If your code is not suppose to reset the random number every single round and reset the 'tries' count every round (the code threw away the current game every round) the below code may help you:
import java.util.Scanner;
public class GuessRunner {
public static void main(String[] args) throws InterruptedException {
System.out.print("I will choose a number between 1 and 10" + '\n'
+ "You have 3 tries to get it right" + '\n');
GuessCalc game = new GuessCalc();
while (game.getRounds() <= 10) {
game.playRound();
System.out.println(game.wins());
}
}
}
Second class:
import java.util.Scanner;
public class GuessCalc {
private int wins, rounds = 0, num = (int) (1 + Math.random() * 10);
private int tries = 0;
private Scanner sc=new Scanner(System.in);
/**
* Constructs the game
*
* #param guess
* the player's guess
*/
public GuessCalc() {
}
/**
* Runs the rounds and determines if they win
*
* #return outcome if they won (true) or lost (false);
*/
public boolean playRound() {
startNewRound();
System.out.printf("Round %d \n\n", this.getRounds());
while(true){
System.out.println("Enter a new guess: ");
int guess = Integer.parseInt(sc.nextLine());
printHotOrCold(guess);
if (guess == num) {
wins++;
System.out.println("Jackpot! Setting a new random number");
return true;
}else if(tries==3){
System.out.println("Oops, didn't succeed. Better luck next time. The number was "+num);
return false;//ran out of tries
}else{
//got it wrong but still has guesses left
}
}
}
public final void startNewRound() {
rounds++;
tries = 0;
num = (int) (1 + Math.random() * 10);// set a new random number
}
/**
* Tells the player if they are hot or cold
*/
public void printHotOrCold(int guess) {
int offBy = guess - num;
if (offBy == 1 || offBy == -1) {// if they are over or under by 1
System.out.println("Hot");
} else if (guess != num) {// if they are further than 1 away
System.out.println("Cold");
}
tries++;
}
/**
* Returns the number of wins and makes a new header
*
* #return the String with the number of wins and new header
*/
public String wins() {
String record = String.format("You have won %d out of %d rounds. \n\n",wins,rounds);
return record;
}
/**
* Returns the number of rounds played
*
* #return rounds the number of rounds
*/
public int getRounds() {
return rounds;
}
}
Your code was malformed (couldn't compile) and I don't 100% know your intent (ex unknown if it is 10 rounds to get as many random numbers correct as possible or they have 3 guesses in 10 rounds). Good luck.
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...