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.
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 ;)
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();
}
}
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);
}
I'm in 9th grade in AP computer science and we were given a project to make a game. I picked a simple Game of Chi thing that my teacher had suggested. But what I cannot figure out is how to make alternating turns between the computer and the player.
import java.util.Scanner;
/**
* Game of Chi .. see main for gameplay
*
* #author .....
*/
public class GameOfChi {
private static int numStonesLeft = 0;
public static void main(String[] args) {
numStonesLeft = (int) (Math.random() * 16) + 15;// btw 15 & 30 stones
System.out.println("This is the Game of Chi.");
System.out.println("There is a pile of " + numStonesLeft
+ " stones between us.");
System.out.println("We alternate taking either 1,2 or 3 stones.");
System.out.println("The person who takes the last stone loses");
// Write a loop to alternate computerTurn() and playerTurn()
// checking after each turn see if there is a winner to print
// and to break the loop ... then output the winner
computerTurn(); // invoke the computerTurn() method
playerTurn(); // invoke the playerTurn() method
while (numStonesLeft> 0);
}
/**
* The computerTurn method chooses a random number from 1 to 3 if
* numStonesLeft is greater than or equal to 3, otherwise chooses a random
* number from 1 to numStonesLeft.
*
* Then decrements numStonesLeft appropriately and prints the turn.
*/
public static void computerTurn() {
int stonesChosen = 1 + (int) (Math.random() * Math
.min(3, numStonesLeft));
numStonesLeft -= stonesChosen;
System.out.println("\nI took " + stonesChosen + " stones.");
System.out.println("There are " + numStonesLeft + " stones left.");
}
/**
* The playerTurn method prompts the user for a valid number of stones to
* choose and reads an int value from the user and will repeat this action
* while the user input is invalid. (i.e. user must choose 1, 2 or 3 AND
* their choice must be less than or equal to numStonesLeft.)
*
* Also decrements numStonesLeft appropriately and prints the turn.
*/
public static void playerTurn() {
Scanner keyboard = new Scanner(System.in);
System.out.println("Number of stones you take this turn:");
int stonesChosen = 0;
stonesChosen = keyboard.nextInt();
while (stonesChosen > 3 || stonesChosen < 1) {
;
System.out.println("That is an invalid number of stones.");
stonesChosen = keyboard.nextInt();
}
if (stonesChosen <= 3 || stonesChosen >= 1)
;
{
System.out.println("\nYou took " + stonesChosen + " stones.");
System.out.println("There are " + (numStonesLeft - stonesChosen)
+ " stones left.");
}
stonesChosen = keyboard.nextInt();
}
}
in your main method create some form of while loop that checks if the game is over.
while(!gameEnded)
{
playerTurn();
computerTurn();
}
unless you are asking how to make it the computer plays first then next turn player plays first.
in that case add a counter to track who went last.
while(!gameEnded)
{
if(counter%2 = 0)
{
playerTurn();
computerTurn();
}
if(counter%2 = 1)
{
computerTurn();
playerTurn();
}
couter++;
}
To randomly select the player that goes first on turn one you can initialize the counter with an odd or even number.
int counter = Math.random()*2;
do {
//
// Other code from above as required.
// ...
//
computerTurn(); // invoke the computerTurn() method
//
// Can numStonesLeft be 0 after the computer turn?
// If so, perhaps you need an extra check...
//
playerTurn(); // invoke the playerTurn() method
} while (numStonesLeft> 0);
Hi guys this is my program ive been using java for about 3 weeks. I have achieved to do this simple game, has taken me long, but what i would like to do is how to include a code that randomly chooses who goes first in the game, some advice would be great, (bare in mind im very amateur if not less)
This isnt homework, or an assignment or work... just something im learning next week in class thought id learn it earlier and be ahead... (slighly a neek haha)
Thanks to anyone who helps
import java.util.Scanner;
/**
* The simple NIM game.
* There are 21 matches in the pile. On each move, each user take turns picking
* up 1, 2, or 3 matches until there are no more matches left.
* The one who picks up the last match loses.
*/
public class SimpleNIM {
private int matchesLeft = 21;
private String player = "A";
/**
* Starts and runs the game
*/
public void start() {
Scanner input= new Scanner(System.in);
while (true) {
int pickmatches = 0;
do {
System.out.print(
"Player " + player + ": How many matches do want to pick? (1, 2, or 3) ");
pickmatches = input.nextInt();
if (validMove(pickmatches)) {
break;
}
System.out.println(
matchesLeft - pickmatches < 0
? "You can't pick "
+ pickmatches
+ " matches as only "
+ matchesLeft
+ " matches left"
: "That's an illegal move. "
+ "Choose 1, 2, or 3 matches.");
}
while (true);
updateMatchesLeft(pickmatches);
System.out.println(
"Player "
+ player
+ " takes "
+ pickmatches
+ ( (pickmatches == 1) ? " match, " : " matches, ")
+ "leaving "
+ matchesLeft
+ '\n');
player = otherPlayer(player);
if (gameOver()) {
System.out.println("Player " + player + " wins the game!");
break;
}
}
}
/**
* Update the number of matches left in pile.
* pickmatches No. of matches picked
*/
private void updateMatchesLeft(int pickmatches) {
matchesLeft = matchLeft - pickmatches;
}
/**
* Game Over?
* true if game is over.
*/
private boolean gameOver() {
}
/**
* Returns the other player
* The current player ("B" or "A")
* The other player ("A" or "B")
*/
private String otherPlayer(String p) {
// YOUR CODE GOES HERE
}
/**
* Valid move?
* numMatches The number of matches picked
* true if there are enough matches left and numMatches is between 1 and 3
*/
private boolean validMove(int numMatches) {
}
/**
* Plays the game
* args ignored
*/
public static void main(String[] args) {
SimpleNIM pickUpMatches = new SimpleNIM();
welcome();
pickUpMatches.start();
}
/**
* Displays the startup information banner.
*/
private static void welcome() {
System.out.println("WELCOME TO THE SIMPLE NIM GAME: 21 MATCHES IN PILE");
}
}
new Random().nextInt(n) gives you a random number between 0 and n-1, so you can do
Player[] players = ...
playerToStart = players[new Random().nextInt(players.length)];
to randomly choose one.
If you plan to pick multiple players consider reusing Random instance.
You could do something like:
public void start() {
Scanner input = new Scanner(System.in);
player = Math.random() < 0.5 ? "A" :"B";
do {
But please learn something about Java in general before.
Inside your welcome method add the lines:
if(new java.util.Random().nextBoolean())
player = "A";
else
player = "B";
Have a look at the documentation for Random class.
Add this line to your libraries
import java.util.Random;
Then this line adds a new random number generator, kind of like Scanner.
Random generator = new Random();
Use this resource for more information.
Random rand = new Random();
int result = rand.nextInt(2); // a random number, either 0 or 1, see http://docs.oracle.com/javase/6/docs/api/java/util/Random.html#nextInt(int)
if (result == 0) {
// Player 1 goes first
}
else {
// Player 2 goes first
}