How to make alternating turns in Java? - java

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);

Related

why is my program displaying the array wrong?

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 ;)

Why does my code exit and not accept the "yes" pulled in with a Scanner or the one hardcoded in? [duplicate]

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"

Why does the second while loop cancel both while loops?

Why does the second while loop while (numberOfTries < 2) cancel both while loops? It runs perfect if there is no incorrect answer. But let's say I select 4 problems to be made, and I am only on the first problem. I give the incorrect answer 2 times so the program should say Incorrect two times and then give me a new question because while (numberOfTries < 2) should force it to break from that loop. But it doesn't, it just quits the whole thing. I know it has to be a logic issue, so what am I missing?
import java.util.Random;
import java.util.Scanner;
public class Howthe {
public static void main(String[] args) {
// Open Scanner
Scanner scan = new Scanner(System.in);
// Ask user to choose number of problems to be made.
// Can only choose 4, 9, or 16
System.out.print("Choose a number of problems to be made (4, 9, 16): ");
int userChoiceOfProblems = scan.nextInt();
// Ask user to choose a number between 0 and 12
System.out.print("\nChoose a number between 0 and 12: ");
int userNumberBetween0and12 = scan.nextInt();
// Ask user to choose between add/sub or multiply/divide
System.out.println("\nChoose to:"
+ "\n0: add/sub your chosen number"
+ " and the randomly generated number: "
+ "\n1: multiply/divide your chosen number"
+ " and the randomly generated number: ");
int userArithmeticChoice = scan.nextInt();
int counter = 0;
String equationString;
int equationAnswer;
int numberOfAnswersRight = 0;
int numberOfTries = 0;
int userAnswerToQuestion;
if (userArithmeticChoice == 0){
while (counter < userChoiceOfProblems){
// Create random number to decide if add or sub used.
// add is equal to 0 and sub is equal to 1
Random rand = new Random();
int randomNumberBetween0and1 = rand.nextInt(1) + 0;
// Create random number that is multiplied by userNumberBetween0and12
int randomNumberBetween0and12 = rand.nextInt(12) + 0;
// Add and increase counter by 1
if (randomNumberBetween0and1 == 0){
// If numberOfTries is more than 2, then display answer.
while (numberOfTries < 2){
// Compute the right answer (addition).
equationAnswer = userNumberBetween0and12 + randomNumberBetween0and12;
// Produce string of equation, then display string (addition).
equationString = userNumberBetween0and12 + " + "
+ randomNumberBetween0and12;
System.out.println(equationString);
userAnswerToQuestion = scan.nextInt();
// If answer is right, increase numberOfAnswersRight.
if (userAnswerToQuestion == equationAnswer){
numberOfAnswersRight++;
System.out.println("Correct!");
break;
}
// If answer is wrong, continue loop and increase numberOfTries
else if (userAnswerToQuestion != equationAnswer){
numberOfTries++;
System.out.println("Incorrect");
}
} // end of while (numberOfTries < 2 && !quit)
counter++;
}
} System.out.println("Yout got " + numberOfAnswersRight + " problem(s) right!");
}
}
}
numberOfTries is initialized outside of your loops. Once you try twice, it never gets set back to 0 which causes the loops to skip and finish on the next question because numberOfTries is already 2.

Guessing Game errors (mostly scanner)

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 need a short code to include in my program about the system to determine randomly who goes first in java

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
}

Categories

Resources