Counter Issue in Java Dice Game - java

Assignment Instructions:
-Prompt the user in main() if he she want to play the game or not. Display a brief description of how the game should be played first.
-Code a method that allows the user to play
-Code a method for the computer throwing two dices.
-Code a method that displays the outcome by showing what the user entered, the user to play as many times as he.she wish...and each time, you must keep track of the number of wins and losses by the player.
-Code a method that display the statistics for all games played and as soon as the player chooses to abort the game. You must display the number of games played, how may were won, how many were lost, and the percentile for each
My problem is keeping track of the number of wins and losses by the player and displaying the correct amount of games that was played, won and loss after multiple turns at the game. (Specifically in the stats() method) I tried to add to the userwins and userloss with "++" but it doesn't remember the amount of games played when the user plays 1 to play another game. If the ++ doesn't work, I believe I should do a counter for it. However, I don't know if this counter should go in main or within the Stats() method.
public class DiceGame_
{
//declarations:
static int answer = 1;//1 to continue or 0 to quit
static Scanner get = new Scanner(System.in);
static int guess = 0;
static int dice1 = 0;
static int dice2 = 0;
static int dicesum = 0;
static int games = 0;
static int userWins = 0;
static int userLoss = 0;
static double percentW = 0;
static double percentL = 0;
static Random random = new Random();
public static void main(String[] args)
{
//Display the game's description and Prompt the user if they would like to play
System.out.println("In this game, you are playing against the computer. The computer will throw 2 dices"
+ " to randomly select 2 numbers between 1 and 6.\nYou will then guess a number between 2 and 12, if the number"
+ " you guess matches the sum of the two dices the computer throws,\nthen you win! Otherwise, the computer wins.");
//input:
while (answer != 0) //while will allow the user to play again
{
GuessNum(); //call GuessNum method
DiceThrow();//call DiceThrow method
//Output:
DispOutcome();//Display outcome method
//ask user if they would like to continue
System.out.println("Would you like to play again? Press 1 for yes or 0 for no: ");
answer = get.nextInt();
}//end while
Stats();//Stats Method (Display # of games played, won and loss, and percentiles of wins/losses)
}//end main
//==========================================================
public static void GuessNum() //The user guesses a number Method
{
System.out.println("Please enter a number between 2-12 for your guess.");
guess = get.nextInt();
while(guess < 2 || guess > 12) //will make sure the user is asked again if they enter a value greater than 12 or less than 2
{
System.out.println("You must select a number between 2 and 12! Please re-enter a guess: ");
guess = get.nextInt();
}//end while
}//end GuessNum method
//==========================================================
public static void DiceThrow() //The computer generates 2 numbers from dice rolls
{
dice1 = random.nextInt(6) + 1;
dice2 = random.nextInt(6) + 1;
dicesum = dice1 + dice2;
}//end DiceThrow method
//==========================================================
public static void DispOutcome() //Displays the outcome of what the user entered, the values of the 2 dice thrown and who won
{
System.out.println("Computer: Dice 1 = " + dice1 + " and Dice 2 = " + dice2);
System.out.println("Player: entered " + guess);
System.out.println("You played " + guess + " and the compuer threw " + dice1 + " and " + dice2 +
" for a total of " + dicesum + "....");
{
if(guess == dicesum)
System.out.println("You won!");
else if(guess != dicesum)
System.out.println("Sorry! You lost!");
}//end if
}//end DispOutcome method
//==========================================================
public static void Stats() //Displays the stats of the game (wins, losses, percentile of each)
{
{
if(guess == dicesum)
userWins ++; //adds 1 to the user's win count if the user wins a game
else if (guess != dicesum)
userLoss ++; //adds 1 to the user's loss count if the user losses the game
}
games = (userWins + userLoss); //total of games is the losses + wins
System.out.println("You've played: " + games + " games");
System.out.println("You've won: " + userWins + " games");
System.out.println("You've loss: " + userLoss + " games");
percentW = (userWins / games);
percentL = (userLoss / games);
System.out.println ( String.format("Your win percentage is %.2f", + (percentW * 100)) + "%");
System.out.println ( String.format("Your loss percentage is %.2f", + (percentL * 100)) + "%");
}//end Stats method
}//end class DiceGame_

You are only calling the Stats() method once, when done, so the userWins++ and userLoss++ statements are only called once. You should move those statements inside the DispOutcome() method so they get called for every game. You already have a check for (guess == dicesum) there, which is where they go.

I can see 2 problems:
Problem #1.
percentW = (userWins / games);
percentL = (userLoss / games);
The variables userWins, games and userLoss are all integers. So the divisions are going to be treated as integer arithmetic. That is going to cause percentW and percentL to be 0.0.
Hint: to force the division to be done using floating point, convert either or both operands to be double. Have you been taught how to convert from one primitive type to another?
Problem #2.
The incrementing of the variables happens in the Stats method. The Stats method is called only once. Therefore the variables only get incremented once.
Hint: if the purpose of Stats is to print out the stats, then you are incrementing the score in the wrong method.
By the way, there are a few problems with style and other things:
Method names should not start with an uppercase letter in Java.
The indentation is inconsistent. I suspect that you are using TAB characters in the source file. This causes problems if you cut-and-paste code into Markdown ... and in other contexts. For example Linux/Mac versus Windows!
It is better to configure your IDE to use SP characters for indentation.
There are issues with how you are using { ... }. For example:
{
if (guess == dicesum)
System.out.println("You won!");
else if (guess != dicesum)
System.out.println("Sorry! You lost!");
}
If you look at that, the braces serve no real purpose there.
In a statement like this:
GuessNum(); //call GuessNum method
the comment is (IMO) harmful. It says nothing that isn't totally obvious from the code. In fact, all it really does is distract the reader.
This code should be OO. You are relying heavily on static methods and static variables. (Maybe that is the next lesson ....)

Related

Hi-Lo Guessing Game - Limiting number of attempts from user input & play again logic

I'm new to Java programming and taking a college course where I have an assignment to create a Hi/Lo guessing game. The game provides up to 5 attempts for the user to input a number between 1 and 100 (inclusive). The program must provide the logic back of whether the answer is too low, too high or correct. The program must provide the option to play again after either winning or the 5 failed attempts.
I've recreated this program about 10 times :(. I cannot get he logic to work to follow the instructions above. I cannot stop the tries at 5 attempts... and I cannot get the program to execute a new game.
Any help is greatly appreciated. I've spent countless hours writing and re-writing this code with MANY different results - but not the intended ones.
This is my first time posting so, I apologize if the format to post is not correct.
I've looked through more forums and examples than I care to admit and none of code I've reviewed and tried implementing have given me the results of limiting the user input to 5 tries each time and ability to play again multiple times.
Here is my code:
public class HiLoGuessingGame {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
//Initialize scanner and random number gennerator
Scanner input = new Scanner(System.in);
Random generator = new Random();
//State the rules of the game
System.out.println("The Hi-Lo Guessing Game. Guess a number between 1-100");
System.out.println("You have 5 attempts!");
/* define the variable Guess (user iput)
define the variable Answer (random generator)
define the variable Counter (track number of tries and limit to 5)
define the variable PlayAgain (Y/N question)*/
int guess = 0;
int answer = generator.nextInt(100)+1;
int counter = 1;
String playAgain;
boolean gameOver = false;
//Ask the Hi-Lo question - pick number 1-100 (inclusive)
//Provide feedback answer too high, too low or you win!
//Limit number of tries in the game to 5
while (guess != answer) {
System.out.print("Enter your guess: ");
guess = input.nextInt();
counter++;
if (guess < answer) {
System.out.println("Your guess " + guess + " is too low. Try again");
System.out.println("This is attempt: " + counter);
} else if (guess > answer) {
System.out.println("Your guess " + guess + " is too high. Try again");
System.out.println("This is attempt: " + counter);
} else if (guess == answer) {
System.out.println("Your guess " + guess + " is correct! You win!");
System.out.println();
System.out.println("Would you like to play again (Y/N)?");
playAgain = input.next();
}
}
if (counter ==6) {
System.out.println("Sorry, you've reached your max atttempts.");
System.out.println("Would you like to play again (Y/N)?");
playAgain = input.next();
}
// Play again logic
boolean isValid;
do {
System.out.print("Would you like to play again (Y/N)?");
playAgain = input.next().toUpperCase();
isValid = playAgain.equals("Y") || playAgain.equals("N");
playAgain = input.next();
counter = 1;
if ( !isValid ) {
System.out.println("Error, please enter Y or N");
System.out.println();
}
} while (!isValid);
}
}
You can add an extra condition to your while-loop:
while (guess != answer && counter < 5) {
// ...
}
Alternatively, you can break the loop when you get a right answer:
while (counter < 5) {
// ...
if (answer == guess){
// ...
break;
}
}

Blackjack Program Always forcing user to 'Hit' even if they say 'Stay'

So i'm making a blackjack program. I've successfully made the game almost fully except one bug type thing. The user gets the option to 'hit' or 'stay' as you usually would in blackjack but when it tells them their total in the end it will add the 2 'hits' even if they said stay twice. For example if I got a 4 and a 6 for a total of 10. Then I just stay twice to keep the 10. The program rolls 2 more numbers anyway and at the end will say the total of like 20 instead of the 10 I initially got. You can run my program to see more if you want so here is the code;
/////////////////////////////////////
// Name: Mackenzie Cutler
// Class: CP 12
// Date: March 28th, 2018
/////////////////////////////////////
import java.util.Scanner;
import java.util.Random;
public class MCproject3
{
public static void main(String[] args)
{
Scanner k = new Scanner(System.in);
Random ran = new Random();
//Welcoming user & choosing their initial cards
System.out.println("Welcome to the Cutler Casino Program. Currently playing Blackjack!");
int a1 = ran.nextInt(11) + 1;
int a2 = ran.nextInt(10) + 1;
int a3 = ran.nextInt(11) + 1;
int a4 = ran.nextInt(11) + 1;
System.out.println ("\nYou get a " + a1 + " and a " + a2);
System.out.println ("Your total is " + (a1+a2));
//Choosing dealers initial cards and telling user
int b1 = ran.nextInt(11) + 1;
int b2 = ran.nextInt(10) + 1;
int b3 = ran.nextInt(11) + 1;
int b4 = ran.nextInt(11) + 1;
System.out.println("\nThe dealer has a " + b1 + " showing, and a hidden card.");
System.out.println("His total is hidden, too.");
//User chooses to 'Hit' or 'Stay'
System.out.print("\nWould you like to 'Hit' or 'Stay'?");
String choice = k.nextLine();
if(choice.equalsIgnoreCase ("hit"))
{
System.out.println("You drew a " + a3);
System.out.println("Your total is " + (a1+a2+a3));
if(a1+a2+a3 > 21)
{
System.out.println("You busted! Since you exceeded 21 the dealer wins, sorry.");
return;
}
}
else if(choice.equalsIgnoreCase ("stay"))
{
System.out.println(" ");
}
else
{
System.out.println("Error. Make sure you typed either 'Stay' or 'Hit'. Please re-run the program :)");
}
//Second time user chooses to 'Hit' or 'Stay'
System.out.print("\nWould you like to 'Hit' or 'Stay'?");
String choice2 = k.nextLine();
if(choice2.equalsIgnoreCase ("hit"))
{
System.out.println("You drew a " + a4);
System.out.println("Your total is " + (a1+a2+a3+a4));
if(a1+a2+a3+a4 > 21)
{
System.out.println("You busted! Since you exceeded 21 the dealer wins, sorry.");
return;
}
}
else if(choice2.equalsIgnoreCase ("stay"))
{
System.out.println(" ");
}
else
{
System.out.println("Error. Make sure you typed either 'Stay' or 'Hit'. Please re-run the program :)");
}
//Dealers reveal and is his turn to choose 'Hit' and 'Stay'
System.out.println("\nOkay, Dealers turn.");
System.out.println("His hidden card was " + b2);
System.out.println("His total was " + (b1+b2));
int dchoice = ran.nextInt(2) + 1;
if(dchoice == 1)
{
System.out.println("\nDealder chooses to hit.");
System.out.println("He draws a " + b3);
System.out.println("His total is now " + (b1+b2+b3));
if(b1+b2+b3 > 21)
{
System.out.println("Dealer busted! Since he exceeded 21 you WIN!!");
return;
}
}
else if(dchoice == 2)
{
System.out.println("\nDealer chooses to stay.");
}
else
{
System.out.println("Error 404. Program Failed, We are sorry. Please restart.");
}
//Dealers second 'Hit' or 'Stay' random choice
int dchoice2 = ran.nextInt(2) + 1;
if(dchoice2 == 1)
{
System.out.println("\nDealder chooses to hit.");
System.out.println("He draws a " + b4);
System.out.println("His total is now " + (b1+b2+b3+b4));
if(b1+b2+b3+b4 > 21)
{
System.out.println("Dealer busted! Since he exceeded 21 you WIN!!");
return;
}
}
else if(dchoice == 2)
{
System.out.println("\nDealer chooses to stay.");
}
else
{
System.out.println(" ");
}
//Ending
int totala = (a1+a2+a3+a4);
int totalb = (b1+b2+b3+b4);
System.out.println("\nDealers total is " + (b1+b2+b3+b4));
System.out.println("Your total is " + (a1+a2+a3+a4));
if(totala > totalb)
{
if(totala <= 21)
{
System.out.println("\nYou WIN!");
}
else if(totala > 21)
{
System.out.println("\nYou busted so you wont win :(");
}
}
else if(totala < totalb)
{
if(totalb <= 21)
{
System.out.println("\nSorry, Dealer Wins.");
}
else if(totalb > 21)
{
System.out.println("Dealer busted so you win!");
}
}
else
{
System.out.println("\nError 405. Program Failed, We are sorry. Please restart.");
}
}
}
I just want to know if you think there is anything I did wrong or should do differently to make it work correctly.
The problem is very simple yet elusive.
You have displayed a1+a2 for the first total. However, while displaying the results, you show a1+a2+a3+a4. Now, a3 and a4 are already initialized to some random numbers, therefore the final result will always be more than the initial, even if you 'stay' twice.
Solution -
To fix this, you can create a variable called int UserTotal = a1+a2, and add a3 to it if the user 'hits' the first time, and a4 to it if the user 'hits' the second time. Then, initialize totala to UserInput.
Or, you can set a3 and a4 to 0 at the very start of the program, and if the user 'hits' the first time, you can set a3 to a random value, and if user hits the second time, a4 can be set to a random value.
You are always calculating the totals like this:
int totala = (a1+a2+a3+a4);
int totalb = (b1+b2+b3+b4);
These variables a1, a2, etc. are assigned values at the very start of your main method like so:
int a1 = ran.nextInt(11) + 1;
int a2 = ran.nextInt(10) + 1; // is this correct?
int a3 = ran.nextInt(11) + 1;
int a4 = ran.nextInt(11) + 1;
So regardless of what the user inputs, it will always calculate the sum of the 4 values as the total.
To resolve this, give a3 and a4 initial values of 0, and only assign values if they "hit".
One alternative is to store the numbers in a List, that way the sum is just the total of the integers in the List, e.g.
List<Integer> playerCards = new ArrayList<>();
// Add initial cards...
playerCards.add(ran.nextInt(11) + 1);
playerCards.add(ran.nextInt(11) + 1);
if (playerHit) { // for example...
playerCards.add(ran.nextInt(11) + 1);
}
// Calculate player total
int playerTotal = 0;
for (int cardValue : playerCards) {
playerTotal += cardValue;
}
System.out.println("Player total is: " + playerTotal);
Additionally your code has a lot of repetition, you should consider refactoring it into smaller reusable methods.
You just need to set these two variables below when they actually do decide to hit and not automatically at the start. Otherwise you want these two variables to be zero at the start, so that way when they don't hit you add everything you get the correct result!
int a3 = ran.nextInt(11) + 1;
int a4 = ran.nextInt(11) + 1;

how to subtract from a for loop in java

i am making a rock paper scissors game in java for collage and was wondering how to subtract 1 from a for loop.
the full code works but if some one enters a invalid number (lower then 1 or higher then 3) my code asks them to reenter a number(1, 2, 3)
but the for loop counts it as a loop so i end up with less moves.
i need to change something in the last "else if" but i cant figure it out
could some one point me in the right direction?
thanks.
the full code is this:
import java.io.*;
import java.util.Random;
public class RockPaperScissors {
static int loss = 0;
static int win = 0;
static int tie = 0;
int draw;
static int playerHand;
static int compHand;
int gameLoop;
public void playerMoves() {
if ( playerHand == compHand ){ //if both hands (player and computer) are the same
System.out.println("Draw, your picked " + playerHand + " and the computer picked " + compHand );
tie++; // add 1 to tie score
}
else if (playerHand == 1 && compHand == 2){ // if player picks Rock and computer picks paper
System.out.println("the computer picks " + compHand + "! " + "Paper beats rock, You lose");
loss++; // add 1 to loss score
}
else if (playerHand == 1 && compHand == 3){ // if player picks rock and computer scissors
System.out.println("the computer picks " + compHand + "! " + "Rock beats Scissors, You win!");
win++; // add 1 to win score
}
else if (playerHand == 2 && compHand == 1){ //if player picks paper and computer picks rock
System.out.println("the computer picks " + compHand + "! " + "Paper beats rock, you win!");
win++; // add 1 to win score
}
else if (playerHand == 2 && compHand == 3){ // if player picks paper and computer scissors
System.out.println("the computer picks " + compHand + "! " + "Scissors beats Paper, you lose!");
loss++; // add 1 to loss score
}
else if (playerHand == 3 && compHand == 1){ // if player picks scissors and computer rock
System.out.println("the computer picks " + compHand + "! " + "Rock beats Scissors, you lose!");
loss++; // add 1 to loss score
}
else if (playerHand == 3 && compHand == 2){ // if player picks scissors and computer paper
System.out.println("the computer picks " + compHand + "! " + "Scissors beats Paper, you win!");
win++; // add 1 to win score
}
else if (playerHand < 1 || playerHand > 3) {
System.out.println(playerHand + " is not a valid number. Try again...");// if not valid number ask again.
gameLoop = gameLoop - 1; // subtract 1 from gameLoop
}
else {
System.out.println("Great job, you broke it...");
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("Welcome to Rock Paper Scissors");
System.out.println("Lets play ten games and see if you can outsmart the computer!");
for (int gameLoop = 0; gameLoop < 10; gameLoop++) { // a for loop to keep the game running 10 times
Random randomNumber = new Random(); // create a new random number everytime
compHand = (int) randomNumber.nextInt(3); // generate a random number for the computer (compHand)
compHand++;
// while (playerHand < 1 || playerHand > 3) {
// System.out.println(playerHand + " is not a valid move. Try again...");
System.out.println("Rock(1), Paper(2), or Scissors(3) Please enter the number");
RockPaperScissors draw = new RockPaperScissors();
RockPaperScissors.playerHand = Integer.parseInt(br.readLine());
draw.playerMoves(); // go to public void playerMoves and use that.
System.out.println("the score is: " + win + " Games won. " + loss + " Games lost. " + tie + " Games tie."); // print out the game score at the end of every game
System.out.println("");
}
}
}
It is a scope issue. You are declaring a new variable gameLoop in your for loop, which hides the variable gameLoop that has been declared at the beginning of your class.
public class RockPaperScissors {
...
int gameLoop; // 1. variable with name gameLoop declared
...
// 2. variable with name gameLoop declared; hides 1. declaration
for (int gameLoop = 0; gameLoop < 10; gameLoop++) {
^ this is not the same variable as above
A quick and easy solution would be to just omit the 'int' in the for-loop:
for (gameLoop = 0; gameLoop < 10; gameLoop++) {
Now, when you decrement it in the else-branch of your playerMoves() method, it should be noticed by the for-loop.
You could look towards keeping that while loop in main which checks if the playerHand is < 1 or > 3, and inside it, validate until the user inputs a valid number. The
below is a sample idea of what you can look towards doing. It is not perfect.
//Taking in the first input
System.out.println("Rock(1), Paper(2), or Scissors(3) Please enter the number");
RockPaperScissors draw = new RockPaperScissors();
RockPaperScissors.playerHand = Integer.parseInt(br.readLine());
//Validating the input repeatedly until it is valid
while (playerHand < 1 || playerHand > 3) {
System.out.println(playerHand + " is not a valid move. Try again...");
System.out.println("Rock(1), Paper(2), or Scissors(3) Please enter the number");
RockPaperScissors.playerHand = Integer.parseInt(br.readLine());
}
//Continue with your program
draw.playerMoves(); // go to public void playerMoves and use that.
I personally find validating here to be more convenient than validating in the playerMoves method, which is a bit long already as it is.
Alternatively, if you want to subtract the invalid guess from the for loop, you can do a gameLoop-- in the for loop for invalid guesses (and not execute the method by doing something like a continue after decrementing gameLoop).

Calculating Overall Best Game in Guessing Game

So I wrote a java code for a numbers guessing game. The entire thing is pretty much done. It works by choosing a random number then asking the user for console inputs and then saying whether that is higher or lower than the random number. Once you guess it, it then asks if you want to play again. When you finally say no to this (be it one game or several) it prints out your Overall results including total games, total guesses, avg guesses/game and your best game. I have everything worked out except I cant figure out how to make it print your overall best game.
import java.util.*; //so I can use scanner
public class GuessingGame {
public static void main(String[] args) {
Random rand = new Random ();
int max = 100;
Scanner input = new Scanner(System.in);
int guess;
boolean play = true;
int totalGames = 0;
int totalGuesses = 0;
System.out.println("Can you guess the word?");
System.out.println("I am sure you cannot guess!");
System.out.println("Go ahead and try!");
System.out.println();
while (play) {
System.out.println("I'm thinking of a number between 1 and " + max + "...");
int numberToGuess = rand.nextInt(max) + 1;
int numberOfTries = 0;
boolean win = false;
while (!win) {
System.out.print("Your guess? ");
guess = input.nextInt();
numberOfTries++;
if (guess == numberToGuess) {
win = true;
} else if (guess > numberToGuess) {
System.out.println("It's lower.");
} else if (guess < numberToGuess) {
System.out.println("It's higher.");
}
input.nextLine();
}
if (numberOfTries == 1) {
System.out.println("You got it right in " + numberOfTries + " guess!");
} else {
System.out.println("You got it right in " + numberOfTries + " guesses!");
}
totalGames++;
totalGuesses+= numberOfTries;
System.out.print("Do you want to play again? ");
String answer = input.nextLine();
char firstLetter = answer.charAt(0);
if (firstLetter == 'y' || firstLetter == 'Y') {
play = true;
} else {
play = false;
}
System.out.println();
}
System.out.println("Overall results:");
System.out.println("Total games = " + totalGames);
System.out.println("Total guesses = " + totalGuesses);
System.out.println("Guesses/game = " + totalGuesses/totalGames);
System.out.println("Best game = ");
}
}
In order to get the best game you need a keep track of the best best after each game, such as a variable that checks it there is a new best game after each game.
Keep track of the best score, which is the lowest number of guesses.
int bestGame = Integer.MAX_VALUE; // at the top
bestGame = Math.min(bestGame, numberOfTries); // at the end of your inner while loop
The worst possible score is the highest number of guesses, which is limited by Integer.MAX_VALUE, so you start there.
By the best game u mean minimum number of tries needed to answer is the best game.
/* int mintries,bestgame,gamenumber=0;
bestgamenumber=0;mintreies=Integer.MAX_VALUE:*/
Add the above lines above your while(play)
gamenumber++;
/*if(mintries>numberOfTries)
{
mintries=numberOfTries;//update mintries
betgame=gamenumber;
}*/
Add the if condition just before closing while(play).
So it will be like
int mintries;
mintreies=Integer.MAX_VALUE:
int gamenumber=0;
int bestgamenumber=0//if you want to print the which game is the best game(!st,2nd,3rd..) ;
while(play)
{
// do all your stuff
gamenumber++;
if(mintries>numberOfTries)
{
mintries=numberOfTries;//update mintries
bestgamenumber=gamenumber;
}
}
}
System.out.println("Game number +bestgamenumber+"was the best game with"+ mintries+"tries);
I am considering that you want to print which game (1st,2nd,3rd)is best and minimum tries made to guess the best game.Correct me if i am wrong.
To fit into the code you have already written, You could
Create a new 'global' variable, for example int bestGame = Integer.MAX_VALUE;.
Whenever the user is done with a game do a check if the current numberOfGuesses is smaller than the current bestGame, and if it is, then overwrite bestGame with the current numberOfGuesses.
At the end, you simply need to output bestGame.

Two console inputs required to System.exit(0) during else if

So I'm working on a copy of a simple Dice game that was an example from the Maxwell Sanchez YouTube JAVA on Eclipse tutorials. What I started playing around with is simple ways to implement a text based menu of sorts.
What I'm trying to accomplish is a Y or N input method of either restarting the program, or killing it. I'm a total noob, coming here after a tiny bit of Arduino. I'm liking JAVA but there are many things I don't understand.
My problem right now is, everything appears to work so far, except that if you get to the end and type N to quit, It requires 2 inputs of N to actually execute the else if statement. Is that something that is a bug? Or am I just mis-programing what I'm trying to accomplish.
import java.util.*;
public class diceGame
{
static int money;
static Scanner in = new Scanner(System.in);
static Random random = new Random();
static String userName;
static String tryAgain;
public static void main(String[] args)
{
money = 1000;
System.out.println("Welcome to this simple dice game! " +
"Please enter your name.");
String userName = in.nextLine();
System.out.println("Hey " + userName + ".");
rollDice();
}
public static void rollDice()
{
System.out.println("You have " + money + " coins!");
System.out.println("Please select a number (1-6) to bet on!");
int betRoll = in.nextInt();
System.out.println("Please place your bet!");
int betMoney = in.nextInt();
while (betMoney > money)
{
System.out.println("You don't have enough coins... you only " +
"have " + money + "coins.");
System.out.println("Please place a realistic bet!");
betMoney = in.nextInt();
}
int dice;
dice = random.nextInt(6)+1;
if (betRoll == dice)
{
System.out.println("You Win!");
money+=betMoney*6;
System.out.println("You have " + money + " coins.");
}
else
{
System.out.println("Snap! You lost your coins!");
money-=betMoney;
System.out.println("You have " + money + " coins.");
}
if (money <= 0)
{
System.out.println("You've lost all yer coins!");
System.out.println("Play again?" + " Type y or n");
if (in.next().equalsIgnoreCase("y"))
{
System.out.println("Maybe you'll win this time!");
money = 1000;
rollDice();
}
else if (in.next().equalsIgnoreCase("n"))
{
System.out.println("Maybe next time...");
System.exit(0);
}
else
{
System.out.println("Invalid character");
}
}
else
{
rollDice();
}
}
}
Store the input in a variable, and compare it... or you'll have to input twice.
String choice = in.next();
if (choice.equalsIgnoreCase("y"))
{
System.out.println("Maybe you'll win this time!");
money = 1000;
rollDice();
}
else if (choice.equalsIgnoreCase("n")) // <-- not in.next()
Every time you call in.next() you read user input.
if (in.next().equalsIgnoreCase("y"))
else if (in.next().equalsIgnoreCase("n"))
In this code, you are calling in.next() twice, once for each condition, so it will read two inputs.
You need to separate the reading from the comparison.
String input = in.next();
if (input.equalsIgnoreCase("y"))
else if (input.equalsIgnoreCase("n"))

Categories