How can i add replayability to this blackjack game? - java

import java.util.*;
import java.util.Scanner;
public class Assignment2 {
public static void main(String args[]){
Scanner stdin = new Scanner(System.in);
Random random = new Random();
int ran2 = (random.nextInt(10));
int ran1 = (random.nextInt(10));
int total = ran1 + ran2;
char exit = 'y';
System.out.println("First cards: " + ran1 + ", " + ran2);
System.out.println("Total: " + total);
while(exit != 'n' && total < 21){
System.out.println("Do you want another card? (y/n): ");
exit = stdin.next().charAt(0);
if (exit =='n'){
System.out.println("Would you like to play again? (y/n): ");
exit = stdin.next().charAt(0);
if(total > 21 || exit == 'n'){
break;
}
}
int next = random.nextInt(10);
System.out.println("Card: "+ next);
total = total + next;//adds
System.out.println("Total: "+ total);
if(total > 21){
System.out.println("Bust.");
break;
}
if(total == 21){
System.out.println("You win!");
break;
}
}
}
}
i got the game working and all, but if i wanted to play from the beginning to where you get your first cards, how would i do it? after you win or lose how would i make it restart the game? i've been trying to figure this out and still cant find out how do it

Wrap your code in another loop :)
Scanner stdin = new Scanner(System.in);
char exit = 'n';
while( exit != 'n' ) {
// your old code here
System.out.println("Play again ? (y/n):")
exit = stdin.next().charAt(0);
}

Related

Can't get my code to repeat the questions for the game to continue

I have to write a code for my class I'm taking. It is a game based on betting on 2 colors and numbers from 1 - 36. The user has a set amount of chips already given to them which is 100. I have already written most of the code, however, I can't get my code to repeat the process. I am currently using a Do-While loop. but it just isn't working.
Here is my code:
import java.util.Scanner;
import java.lang.Math;
public class Program_8 {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
int chipsNow = 100;
int userChoice;
int chipsBetted = 0;
//welcome message
welcome();
do {
int spinNum = (int)(Math.random() * 36) + 0;
userChoice = getMenuChoice(userInput);
//get user choice
if (userChoice == 1) {
int getNum = getNumber(userInput);
int getBet = getBet(userInput, chipsNow);
String determineColor = determineColor(spinNum);
System.out.println("\nSpinning Wheel....");
System.out.println("Spin Number: " + spinNum);
System.out.println("Spin Color: " + determineColor);
if (getNum == spinNum) {
chipsNow += getBet;
chipsBetted += getBet;
System.out.println("Congrats, you won!");
System.out.println("\nYou now have: " + chipsNow + " chips");
;
}
else {
chipsNow -= getBet;
System.out.println("\nSorry, you lost!");
System.out.println("You now have: " + chipsNow + " chips");
}
}
if (userChoice == 2) {
String getColor = getColor(userInput);
int getBet = getBet(userInput, chipsNow);
String determineColor = determineColor(spinNum);
System.out.println("Spinning Wheel....");
System.out.println("Spin Number: " + spinNum);
System.out.println("Spin Color: " + determineColor);
if (getColor.equals(determineColor)) {
chipsNow += getBet;
chipsBetted += getBet;
System.out.println("\nCongrats, you won!");
System.out.println("You now have: " + chipsNow + " chips");
}
else {
chipsNow -= getBet;
System.out.println("\nSorry, you lost!");
System.out.println("You now have: " + chipsNow + " chips");
}
}
}while (userChoice != 3 && chipsNow > 0);
}
//welcome message
public static void welcome() {
int chipsNow = 100;
System.out.println("############################");
System.out.println("# Welcome To Roulette #");
System.out.println("############################");
System.out.println("# Number Bets Payout: 35:1 #");
System.out.println("# Color Bets Payout: 1:1 #");
System.out.println("############################\n");
System.out.println("Chips owned: " + chipsNow + "\n");
System.out.println("1. Pick a number to bet on");
System.out.println("2. Pick a color to bet on");
System.out.println("3. Cash Out\n");
}
//get menu choice
public static int getMenuChoice(Scanner userInput) {
int getMenuChoice;
System.out.println("\nChoose an option [1-3]: ");
getMenuChoice = userInput.nextInt();
return getMenuChoice;
}
public static int getNumber(Scanner userInput) {
int getNumber;
do {
System.out.println("Enter a number to bet on [0-36]: ");
getNumber = userInput.nextInt();
}while (getNumber < 0 || getNumber > 36);
return getNumber;
}
public static String getColor(Scanner userInput) {
String getColor = "";
do{
System.out.println("Enter a color to bet on [Red or Black]: ");
getColor = userInput.next();
}while (!(getColor.equals("Red") || getColor.equals("Black")));
return getColor;
}
public static int getBet(Scanner userInput, int chipsNow) {
int getBet;
do{
System.out.println("Enter the number of chips to bet [1 - " + chipsNow + "]: ");
getBet = userInput.nextInt();
}while (getBet < 1 || getBet > chipsNow);
return getBet;
}
public static String determineColor(int spinNum) {
if (spinNum % 2 == 0) {
if (spinNum == 0) {
return "Green";
}
//even
else {
return "Red";
}
}
return "Black";
}
public static void report(int chipsNow) {
System.out.println("\nThanks for Playing!");
System.out.println("You Won a total of: " + chipsNow + " chips today");
}
}
So just looking at the code I'd:
Declare int userChoice = 0; outside the do while. This is needed for the while condition to work.
welcome(); and userChoice = getMenuChoice(userInput); should move into the do while thus it will repeat the welcome message and ask for a user choice everything the do while executes
Simplify your while loop like this while(userChoice != 3 && chipsNow > 0). This is just to make it more readable.
Lastly remove the break;s in your if(getNum == spinNum) { } else { }. A break will force the while loop to be exited regardless of whether the while condition is met. So basically if you win or lose a game your loop will exit, which I don't think is what you want. You only want the loop to exit if the chipsNow < 0 or the userChoice == 3

Java - Loop Cannot keep track of correct count

import java.util.Scanner;
import java.util.Random;
public class BlackJack {
Scanner input = new Scanner(System.in); //Instance of the Scanner
public static void main(String[] args) {
playGame();
}
public static void playGame() {
//int newTotal;
int total;
int firstCard;
int secondCard;
String readLine;
Scanner input = new Scanner(System.in); //Instance of the Scanner
Random random = new Random(); // Instance of Random
firstCard = 1 + random.nextInt(10);
secondCard = 1 + random.nextInt(10);
System.out.println(firstCard + " , "+ secondCard + " and + 1");
total = firstCard + secondCard + 1;
System.out.println("Your total is: " + total);
System.out.println("Want another card? (y/n)");
readLine = input.nextLine();
//
int newTotal;
while (readLine.equals("y")) {
int finalCard = random.nextInt(10);
System.out.println(finalCard);
newTotal = finalCard + total;
System.out.println("You new total is: " + newTotal );
if (newTotal == 21) {
System.out.println("BlackJack!! You won!");
break;
} else if (newTotal > 21) {
System.out.println("You lose.." );
break;
} else
System.out.println("Want another card? (y/n)");
readLine = input.nextLine();
newTotal = finalCard + total;
}
}
}
Currently, I am trying to update the correct amount of newCard total; however, after the second count it goes back to old the value.
For instance,
**
Console output
**
4 , 4 and + 1
Your total is: 9
Want another card? (y/n)
y
8
You new total is: 17
Want another card? (y/n)
y
5
You new total is: 14 // this should be 22
Want another card? (y/n)
The number 3rd output should be 17 + 5; however, my program currently is adding 9 + 5. Please help..
The last line of your while loop should be
total = finalCard + total;
instead of
newTotal = finalCard + total;
newTotal = finalCard + total;
Uses the old total (given in the first round) change it to only use the total instead and it should work.
And as suggested before, remove the newTotal = finalCard + total; in the else statement
public static void playGame() {
int total;
int firstCard;
int secondCard;
String readLine;
Scanner input = new Scanner(System.in); //Instance of the Scanner
Random random = new Random(); // Instance of Random
firstCard = 1 + random.nextInt(10);
secondCard = 1 + random.nextInt(10);
System.out.println(firstCard + " , "+ secondCard + " and + 1");
total = firstCard + secondCard + 1;
System.out.println("Your total is: " + total);
System.out.println("Want another card? (y/n)");
readLine = input.nextLine();
while (readLine.equals("y")) {
int finalCard = random.nextInt(10);
System.out.println(finalCard);
total += finalCard ;
System.out.println("You new total is: " + total );
if (total == 21) {
System.out.println("BlackJack!! You won!");
break;
} else if (total > 21) {
System.out.println("You lose.." );
break;
} else {
System.out.println("Want another card? (y/n)");
readLine = input.nextLine();
}
}
}
your new gameloop ;)

A "Stick Game" program in Java not working correctly?

I've recently decided that I want to make a program that plays a game called "Nim," which is a game in which you start with a predetermined amount of "sticks" and each player takes turns removing between 1 and 3 sticks. Whoever removes the last stick loses.
Anyway, I have written my program and it compiles and runs almost flawlessly. There's only one small problem. After the game is over, it shows the "good game" screen twice, with the game's very first line appearing in the middle (I'll post screenshots at the end here). It's very strange, and I was just wondering if you guys could give it a look.
I'm cutting a chunk of the program out (only one class, named Cup()), because it's somewhat long, so if you see a class you don't recognize then just ignore it. It's pretty self explanatory what the class does in the program, and it's not where the error is occurring. Here's the code.
class SticksGame
{
public static void main(String[] args) throws InputMismatchException
{
Random r = new Random();
int score1 = 0, score2 = 0;
Cup c = new Cup();
int j = 0, d = 0, i = 0, k = 0;
boolean b = true;
String exit = "default";
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Sticks Game! Last Stick loses! Must pick 1 - 3 sticks.");
System.out.println();
do
{
i = r.nextInt(15) + 9;
System.out.println("We begin with " + i + " sticks");
System.out.println();
while (b == true)
{
System.out.println("Your move");
k = input.nextInt();
if (k > 3)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else if (k < 1)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else
{
j = i;
i = i - k;
if (i <= 0)
{
System.out.println("Computer wins!");
score2 = (score2 + 1);
b = false;
}
else
{
System.out.println("We now have " + i + " sticks.");
}
d = c.select();
System.out.println("Computer removes " + d + " sticks");
i = i - d;
System.out.println("We now have " + i + " sticks");
if (i <= 0)
{
System.out.println("You Win!");
score1 = (score1 + 1);
b = false;
}
}
}
System.out.println();
System.out.println("Good game!");
System.out.println("Your score: " + score1 + " Computer's Score: " + score2);
System.out.println("Press enter if you'd like to play again. Otherwise, type \"quit\"");
exit = input.nextLine();
b = true;
}
while(!"quit".equals(exit));
}
}
Any helps are appreciated! Thanks :)
~Andrew
CODE EDITED FOR JANOS
A little late, I know, but here is the FULL GAME for anyone who wants to play! feel free to copy and paste it into your notepad and execute using cmd(YOU MUST KEEP MY NAME AS A COMMENT ON TOP!) :)
//Andrew Mancinelli: 2015
import java.util.*;
import java.io.*;
class Cup
{
private ArrayList<Integer> c = new ArrayList<Integer>();
public Cup()
{
c.add(1);
c.add(2);
c.add(3);
}
public int count()
{
return c.size();
}
public int select()
{
int index = (int)(c.size() * Math.random());
return c.get(index);
}
public void remove(Integer move)
{
c.remove(move);
}
}
class SticksGame
{
public static void help()
{
System.out.println();
System.out.println("Okay, so here's how it works... The object of the game is to NOT have the last stick. Whoever ends up with the very last stick loses.");
System.out.println();
System.out.println("Rule 1: You will each take turns removing sticks. you may only remove 1, 2, or 3 sticks in a turn");
System.out.println();
System.out.println("Rule 2: The beginning number of sticks is always random between 9 and 24 sticks");
System.out.println();
System.out.println("Rule 3: Whoever chooses the last stick, LOSES!");
System.out.println();
System.out.println("And that's it! Simple, right?");
}
public static void main(String[] args) throws InputMismatchException
{
Random r = new Random();
int score1 = 0, score2 = 0;
Cup c = new Cup();
int j = 0, d = 0, i = 0, k = 0;
boolean b = true;
String exit = "default", inst = "default";
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Sticks Game! Last Stick loses!");
System.out.println();
System.out.println("Need some instructions? Type \"help\" now to see the instructions. Otherwise, press enter to play!");
inst = input.nextLine();
if (inst.equals("help"))
{
help();
System.out.println();
System.out.println("press \"enter\" to begin!");
inst = input.nextLine();
}
do
{
i = r.nextInt(15) + 9;
System.out.println();
System.out.println("We begin with " + i + " sticks");
System.out.println();
while (b == true)
{
System.out.println("Your move");
k = input.nextInt();
if (k > 3)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else if (k < 1)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else
{
j = i;
i = i - k;
if (i <= 0)
{
System.out.println("Computer wins!");
score2 = (score2 + 1);
b = false;
break;
}
else
{
System.out.println("We now have " + i + " sticks.");
}
d = c.select();
i = i - d;
if (i >= 0)
{
System.out.println("Computer removes " + d + " sticks");
System.out.println("We now have " + i + " sticks");
}
if (i <= 0)
{
System.out.println("You Win!");
score1 = (score1 + 1);
b = false;
break;
}
}
}
System.out.println();
System.out.println("Good game!");
System.out.println("Your score: " + score1 + " Computer's Score: " + score2);
System.out.println("Press enter if you'd like to play again. Otherwise, type \"quit\"");
input.nextLine();
exit = input.nextLine();
b = true;
}
while(!"quit".equals(exit));
}
}
The problem is that this condition is always true:
while (exit != "quit");
Because != means "not identical",
and the exit variable and "quit" are not identical.
Use the equals method for checking logical equality.
In this example, change the loop condition to this instead:
while (!"quit".equals(exit));
For your other problem of not properly starting a second game,
you need to reinitialize the state variables,
for example reset b = true.
Lastly, note that input.nextInt() doesn't read the newline character that you pressed when entering a number. So when exit = input.nextLine() runs, it reads that newline character, and doesn't actually give you a chance to type "quit". To solve this, add input.nextLine(); right before exit = input.nextLine();
The unexpected retry was because of the use of input.nextLine(); the program assumed that you already pressed [enter].
From previous work, the two options is to insert one more input.nextline();
input.nextLine();
exit = input.nextLine();
Or use input.next(); instead, although enter will not work for this method so you may need to enter any key or "quit" to exit;
exit = input.next();

How to replay basic High Low game?

I am almost finished with my second Java assignment for class, but I am stuck on how to take the user's last choice and either play again or quit. Any ideas?
import java.util.Random;
import java.util.Scanner;
public class HighLow {
public static void main(String[]args) {
Random randomNumber = new Random();
int answer = randomNumber.nextInt(100) + 1;
int numberOfTries = 0;
Scanner userInput = new Scanner(System.in);
String userGuess = null;
boolean gameWin = false;
do {
while (!gameWin) {
System.out.println("Welcome to the guessing game, guess a number between 1 - 100 or type 'quit' to exit: ");
userGuess = userInput.nextLine();
numberOfTries++;
if (userGuess.equals("quit"))
break;
if (Integer.parseInt(userGuess) == answer) {
gameWin = true;
} else if (Integer.parseInt(userGuess) < answer) {
System.out.println("Your guess is too low");
} else if (Integer.parseInt(userGuess) > answer) {
System.out.println("Your guess is too high");
}
}
if (userGuess.equals("quit")) {
System.out.println("You choose to quit! Thanks for playing");
System.out.println("The number was " + answer);
System.exit(0);
}
System.out.println("The number was " + answer);
System.out.println("It took you " + numberOfTries + " tries");
System.out.println("You win! Play again(type: yes or no)");
}
while (userGuess.equals("yes"));
userInput.nextLine();
}
}
}
The problem is because you have userInput.nextLine() prompt for the user to play again or not outside of the game loop and it isn't assigned to any value. I am referring to this section...
System.out.println("The number was " + answer);
System.out.println("It took you " + numberOfTries + " tries");
System.out.println("You win! Play again(type: yes or no)");
}
while (userGuess.equals("yes"));
userInput.nextLine(); <---
}
To fix this problem you simply need to assign the final input call to userGuess and place it back into the game loop like so.
System.out.println("The number was " + answer);
System.out.println("It took you " + numberOfTries + " tries");
System.out.println("You win! Play again(type: yes or no)");
userGuess = userInput.nextLine();
}
while (userGuess.equals("yes"));
}
Doing this will assign the play again value you prompt the user for into the variable that your testing with the do-whileloop. In your original, you had the condition testing for a value that userGuess wasn't going to be storing and instead prompting the user for that option AFTER the loop would have been exited instead of inside where it needs to be.
To reset the values for the next game, you can simply move the variables' initialization into the game loop at the top like so...
import java.util.Random;
import java.util.Scanner;
public class HighLow {
public static void main(String[]args) {
Random randomNumber = new Random();
int numberOfTries, answer;
Scanner userInput = new Scanner(System.in);
String userGuess;
boolean gameWin;
do {
answer = randomNumber.nextInt(100) + 1;
gameWin = false;
userGuess = null;
numberOfTries = 0;
while (!gameWin) {
System.out.println("Welcome to the guessing game, guess a number between 1 - 100 or type 'quit' to exit: ");
userGuess = userInput.nextLine();
numberOfTries++;
if (userGuess.equals("quit"))
break;
if (Integer.parseInt(userGuess) == answer) {
gameWin = true;
} else if (Integer.parseInt(userGuess) < answer) {
System.out.println("Your guess is too low");
} else if (Integer.parseInt(userGuess) > answer) {
System.out.println("Your guess is too high");
}
}
if (userGuess.equals("quit")) {
System.out.println("You choose to quit! Thanks for playing");
System.out.println("The number was " + answer);
System.exit(0);
}
System.out.println("The number was " + answer);
System.out.println("It took you " + numberOfTries + " tries");
System.out.println("You win! Play again(type: yes or no)");
userGuess = userInput.nextLine();
}
while (userGuess.equals("yes"));
}
}
}
this way every time the game loops through, all the values will be reset at the beginning of the new game loop.
Also you should close the Random object and Scanner object at the end of the entire program using close() on each instance.
You need to initialize most of your variables and call userInput.nextLine(); inside your outer loop. Untested suggestion:
import java.util.Random;
import java.util.Scanner;
public class HighLow {
public static void main(String[]args) {
String userGuess = null;
do {
Random randomNumber = new Random();
int answer = randomNumber.nextInt(100) + 1;
int numberOfTries = 0;
Scanner userInput = new Scanner(System.in);
boolean gameWin = false;
while (!gameWin) {
System.out.println("Welcome to the guessing game, guess a number between 1 - 100 or type 'quit' to exit: ");
userGuess = userInput.nextLine();
numberOfTries++;
if (userGuess.equals("quit"))
break;
if (Integer.parseInt(userGuess) == answer) {
gameWin = true;
} else if (Integer.parseInt(userGuess) < answer) {
System.out.println("Your guess is too low");
} else if (Integer.parseInt(userGuess) > answer) {
System.out.println("Your guess is too high");
}
}
if (userGuess.equals("quit")) {
System.out.println("You choose to quit! Thanks for playing");
System.out.println("The number was " + answer);
System.exit(0);
}
System.out.println("The number was " + answer);
System.out.println("It took you " + numberOfTries + " tries");
System.out.println("You win! Play again(type: yes or no)");
}
userInput.nextLine();
while (userGuess.equals("yes"));
}
}
}

Guessing Game, with a While loop

i'm currently trying to create a while loop for my program, a Guessing game. I've set it up so the user can create a max value i.e 1-500 and then the user can proceed to guess the number. When the number has been guessed, the User can press 1, to close, anything else to continue running the loop again.
My problem, is that the code gives me an error when trying to continue the loop, no compiling errros
This is my Code:
import java.util.Random;
import java.util.Scanner;
public class Gættespil2
{
public static void main(String[] args)
{
Random rand = new Random();
int TAL = rand.nextInt(20) + 1;
int FORSØG = 0;
Scanner input = new Scanner (System.in);
int guess;
int loft;
boolean win = false;
boolean keepPlaying = true;
while ( keepPlaying )
{
Scanner tastatur = new Scanner(System.in);
System.out.print("Indsæt loftets højeste værdi : ");
loft = tastatur.nextInt();
TAL = (int) (Math.random() * loft + 1);
while (win == false)
{
System.out.println(" Gæt et tal mellem 1 og "+ loft + "):: ");
guess = input.nextInt();
FORSØG++;
if (guess == TAL)
{
win = true;
}
else if (guess < TAL)
{
System.out.println("Koldere, gæt igen");
}
else if (guess > TAL) {
System.out.println("Varmere, Gæt igen!!");
}
}
System.out.println(" Tillykke du vandt...endeligt!!! ");
System.out.println(" tallet var" + TAL);
System.out.println(" du brugte " + FORSØG + " forsøg");
System.out.println("Slut spillet? tast 1.");
System.out.println("tryk på hvadsomhelst for at spille videre");
int userInt = input.nextInt();
if( userInt == 1)
{
keepPlaying = false;
}
}
}
}
Simple answer. You didn't initialize all the necessary values within your 'keepPlaying' loop before beginning a second round after the player successfully completed the first round. See annotations to your code, below:
import java.util.Random;
import java.util.Scanner;
public class GuessingGame
{
public static void main(String[] args)
{
Random rand = new Random();
int TAL = rand.nextInt(20) + 1;
int FORSØG = 0;
Scanner input = new Scanner (System.in);
int guess;
int loft;
boolean win = false;
boolean keepPlaying = true;
while ( keepPlaying )
{
Scanner tastatur = new Scanner(System.in);
System.out.print("Enter a maximum limit: ");
loft = tastatur.nextInt();
TAL = (int) (Math.random() * loft + 1);
// *** LOOK HERE ***
// Reset the 'win' flag here, otherwise the player receives an
// automatic win on all subsequent rounds following the first
win = false;
while (win == false)
{
System.out.println("Guess the number between one and "+ loft + "):: ");
guess = input.nextInt();
FORSØG++;
if (guess == TAL)
{
win = true;
}
else if (guess < TAL)
{
System.out.println("Colder, guess again!");
}
else if (guess > TAL) {
System.out.println("Warmer, guess again!");
}
}
System.out.println("You've found the number!");
System.out.println("The number was: " + TAL + ".");
System.out.println("You guessed " + FORSØG + " times.");
System.out.println("To quit, enter 1.");
System.out.println("Provide any other input to play again.");
int userInt = input.nextInt();
if( userInt == 1)
{
keepPlaying = false;
}
}
}
}
Sorry for the translation into English -- I had to make sure I was reading things correctly. You might also want to substitute "higher" and "lower" for "warmer" and "colder." "Warmer" and "colder" tend to suggest a proximity to the correct answer, as opposed to the direction in which that correct answer lies.

Categories