Java BlackJack not entering while loop - java

First of all, I apologize because this code seems inefficient to me, but my professor wants it this way (the comments are hers). I have many problems here, but a central one seems to be that when I run the program it does not enter the for loop. Therefore I'm assuming it is not entering the while loop that the for loop is in, and I'm not sure why. Here is the "modified" blackjack program, any help is appreciated:
import java.util.Scanner;
import java.util.Random;
public class BlackJack {
enum Decisions
{
HIT, STAND, SURRENDER, QUIT, PLAY, NOTVALID;
// NOTVALID is used to re-ask to play again
}
enum Card {
ACE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, QUEEN, JACK, KING;
}
// Tells you if the Decision enum is valid or not
public static boolean containsDecision(String decision) {
for (Decisions d : Decisions.values()) {
if (d.name().equals(decision)) {
return true;
}
}
return false;
}
// Tells you what is the integer value of said Card enum
public static int getCardValue(int pick) {
if (pick == 0) {
return 1;
} else if (pick >= 10 && pick <= 12) {
return 10;
}
return pick + 1;
}
// 1 pts
public static int housePlay(int houseCardSum) {
int cardPick;
cardPick = -1;
while (houseCardSum <= 17)
{
getCardValue(cardPick);
houseCardSum = (cardPick + houseCardSum);
System.out.println("Hit from house! CARD: " + cardPick + " VALUE: " + houseCardSum);
}
return houseCardSum;
}
// 1.5 pts
public static void findWinner(int playerCardSum, int houseCardSum, Decisions decision) {
houseCardSum = housePlay(houseCardSum);
if ( (playerCardSum > 21) || (houseCardSum > 21))
{
if (houseCardSum > 21)
{
System.out.println("Sorry you lose!");
}
else
{
System.out.println("You win!");
}
}
else if (decision == Decisions.SURRENDER)
{
System.out.println("You lose because you surrendered!");
}
else if (playerCardSum == houseCardSum)
{
System.out.println("Its a push (tie)!");
}
else if ((playerCardSum > houseCardSum) && (playerCardSum < 21))
{
System.out.println("You win!");
}
else if ( (playerCardSum == 21) && (houseCardSum != 21) )
{
System.out.println("Blackjack win!");
}
else
{
System.out.println("Sorry you lose!");
}
// if, else if, else, check playerCardSum, houseCardSum as well as if
// Decision equaled to SURRENDER
// print the House and You Hand at the end
// call housePlay function and assign the output to houseCard function
// iff not playerCardSum is not 21 and Decisions is not Surrender
// these below will be used moved them around freely in this function
// where you need too.
// put in correct branch sub
// statement
System.out.println("House Hand: " + houseCardSum + " Your Hand: " + playerCardSum); // this
// is
// printed
// out
// after
// all
// branch
// statements
// assessed
}
// 7.5pts
public static void main(String[] args) {
System.out.println("========== BlackJack ==========");
System.out.print("What is your name: ");
Scanner keyboard = new Scanner(System.in);
String playerName;
playerName = keyboard.nextLine();
System.out.println("Okay, " + playerName + ", let's play!");
Decisions decision = Decisions.PLAY ;
int cardPick;
cardPick = -1;
while ( decision != Decisions.QUIT);
{
int playerSum;
int houseSum;
playerSum = 0;
houseSum = 0;
Card holeCard = null;
for ( int i = 0; i < 3; i++)
{
Random newCard = new Random();
cardPick = newCard.nextInt(14);
playerSum = playerSum + getCardValue(cardPick);
System.out.println("Card: " + (Card.values()[cardPick]) );
System.out.println("Sum of your hand: " + playerSum );
}
}

Remove the semicolon after the while statement.
while ( decision != Decisions.QUIT);
while ( decision != Decisions.QUIT)

Related

How can I start the program over again

I'm trying to start the game over if the user enters "Yes". I tried using a while loop, but it's gone wrong somewhere that I can't find.
import java.util.Scanner;
import java.util.Random;
public class RockPaperScissors {
public static void main(String[] args) {
int playerScore = 0;
int computerScore = 0;
int round = 0;
String decision;
// Get user input
while (round<3) {
System.out.println("Please enter your move: Rock, Paper or Scissors");
System.out.println(">>");
Scanner input = new Scanner(System.in);
String playerMove = input.next();
// Check if user input is valid
if (!playerMove.equalsIgnoreCase("Rock") && !playerMove.equalsIgnoreCase("Paper") && !playerMove.equalsIgnoreCase("Scissors")) {
System.out.println("Move is invalid, Opponent gets a point");
computerScore++;
round++;
System.out.println("Your point is "+ playerScore + "; Opponent score is "+ computerScore);
} else {
// Randomly generate computerMove
int computerInt = (int)(Math.random()*3);
String computerMove = " ";
if (computerInt == 0) {
computerMove = "Rock";
} else if (computerInt == 1) {
computerMove = "Paper";
} else if (computerInt == 2) {
computerMove = "Scissors";}
System.out.println("Opponent move is "+ computerMove);
// Establish winning or losing scenarios
if (playerMove.equalsIgnoreCase(computerMove)) {
System.out.println("Tied");
round++;
System.out.println("Your point is "+ playerScore + "; Opponent score is "+ computerScore);
} else if (playerMove.equalsIgnoreCase("Rock") && computerMove.equalsIgnoreCase("Scissors") ||
playerMove.equalsIgnoreCase("Scissors") && computerMove.equalsIgnoreCase("Paper") ||
playerMove.equalsIgnoreCase("Rock") && computerMove.equalsIgnoreCase("Paper")) {
System.out.println("You won");
playerScore++;
round++;
System.out.println("Your point is "+ playerScore + "; Opponent score is "+ computerScore);
}
else {
System.out.println("You lost");
computerScore++;
round++;
System.out.println("Your point is "+ playerScore + "; Opponent score is "+ computerScore);
}
}
// Determine the last winner
if (playerScore < computerScore) {
System.out.println("You lose, so sad ;(");
} else if (playerScore > computerScore) {
System.out.println("You win, here's a cookie ;) ");
} else {
System.out.println("Tied, maybe try harder ^_^"); }
}
System.out.println("Do you wanna play again?");
}
}
}
Sounds like this might be a HW or Test question, so just writing steps to help you out:
first have a user-decision variable and initialize it to "Y"
then put the game in a while(user-decision="Y") loop
at the end of this loop ask the user for their decision and update the user-decision variable to either Y or N
if they say Y loop continues, else it ends
if you need to repeat your code, put it in a new class (Game) and instantiate in main () and call until your Game class returns TRUE (press Y)
package appMain;
import java.util.Scanner;
public class Game {
public Boolean PlayGame() {
System.out.println("START GAME");
//
// >> PUT THERE YOUT GAME CODE <<
//
Scanner input = new Scanner(System.in);
String answer = input.next();
if(answer.equals("Y")) {
return true;
}
return false;
}
}
package appMain;
public class GameMain {
public static void main(String args[]) {
Game game = new Game();
while (game.PlayGame()) {
}
System.out.println("GAME finish");
}
}

Best way to code my unintelligent Nim game?

This is my nim game (goal is dont be the last person to pick up marbles), can someone please guide me. In playing the game, I have just one question
How can I keep track of whose turn it is, I guess if I can keep track of that I can monitor my remainingMarbles. This is the crux of my code. Please help
public class Nim{
public static void main(String[] args)
{
System.out.println("************** Welcome to the game of Nim *******************");
System.out.println("The object of this game is to make me take the last marble off the table");
System.out.println("You must take at least 1 and you can take up to 3 marbles on your turn");
System.out.println("You can go first");
Scanner scan = new Scanner(System.in);
final int MARBLES = 13;
int remainingMarbles;
String input;
do {
//boolean whoseTurn = true;
remainingMarbles = MARBLES;
System.out.println("There are " + MARBLES + " marbles on the table");
while (remainingMarbles > 0){
remainingMarbles -= getUserSelection();
System.out.println("There are " + (remainingMarbles -= getComputerSelection()) + " marble(s) on the table.");
}
if (1 <= remainingMarbles && remainingMarbles <= 2 && remainingMarbles < 0) {
System.out.println("Congratulations! you won!");
System.out.println("Want to play again? y/n");
input = scan.nextLine();
input = input.toLowerCase();
} else
System.out.println("Hard luck you lose!");
System.out.println("Want to play again? y/n");
input = scan.nextLine();
input = input.toLowerCase();
}while (input.charAt(0) == 'y');
}
private static int getUserSelection()
{
Scanner scan = new Scanner(System.in);
do {
System.out.println("Enter 1, 2 or 3");
int userSelection = scan.nextInt();
if (isValidMove(userSelection)){
return userSelection;
}
else {
System.out.println("Not a valid entry");
}
}while (true);
}
private static boolean isValidMove(int input)
{
return 1 <= input && input <= 3;
}
private static int getComputerSelection ()
{
Random generator = new Random();
int computerSelection = 1 + generator.nextInt(3);
System.out.println("The computer chooses " + computerSelection);
return computerSelection;
}
}
First, make a boolean before the loop.
boolean whoseTurn = true;
When the variable is true it's the first player's turn, otherwise the second player's turn.
Now inside the while loop we change the variable at the end of every repetition:
whoseTurn = !whoseTurn;
(Which is a faster way of this)
if(whoseTurn) whoseTurn = false;
else whoseTurn = true;
To conclude, you should do something like that:
...
boolean whoseTurn = true;
while(remainingMarbles > 0){
remainingMarbles -= getUserSelection();
System.out.println("There are " + (remainingMarbles -= getComputerSelection()) + " marble(s) on the table.");
whoseTurn = !whoseTurn;
}
...

Validate user string input

Coding a simple HiLo card game where the user is given a card value from a deck of cards and then inputs 'higher', 'lower' or 'equal' trying to guess the balue of the next card.
Just really can't get my head around user input validation with iteration ie. not moving on until a string with the required parameters has been entered.
My code so far:
import java.util.Scanner;
import java.util.Random;
public class HiLoGame {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
Random randomCard = new Random();
int numberOfSuccesses = 0;
boolean finished = false;
int card = (randomCard.nextInt(13) + 2);
while (finished != true) {
int nextCard = (randomCard.nextInt(13) + 2);
String pictureCard = "";
if (((numberOfSuccesses < 0) ? nextCard : card) == 11) {
pictureCard = "Jack";
} else if (((numberOfSuccesses < 0) ? nextCard : card) == 12) {
pictureCard = "Queen";
} else if (((numberOfSuccesses < 0) ? nextCard : card) == 13) {
pictureCard = "King";
} else if (((numberOfSuccesses < 0) ? nextCard : card) == 14) {
pictureCard = "Ace";
}
System.out.println("The card is a " + ((card > 10) ? pictureCard : card));
if (numberOfSuccesses == 4) {
System.out.println("Congratulations. You got them all correct");
finished = true;
break;
}
while (!reader.nextLine().toLowerCase().equals("higher")
|| !reader.nextLine().toLowerCase().equals("lower")
|| !reader.nextLine().toLowerCase().equals("equal")) {
System.out.println("Try again!");
reader.next();
}
String userGuess = reader.nextLine().toLowerCase();
//TODO validate input
if (userGuess.equals("higher")) {
if (nextCard > card) {
numberOfSuccesses++;
} else {
finished = true;
break;
}
} else if (userGuess.equals("lower")) {
if (nextCard < card) {
numberOfSuccesses++;
} else {
finished = true;
break;
}
} else if (userGuess.equals("equal")) {
if (nextCard == card) {
numberOfSuccesses++;
} else {
finished = true;
break;
}
}
System.out.println(numberOfSuccesses);
card = nextCard;
}
if (numberOfSuccesses < 4) {
System.out.println("Sorry, incorrect!");
}
}
}
and the relevant code extract:
while (!reader.nextLine().toLowerCase().equals("higher")
|| !reader.nextLine().toLowerCase().equals("lower")
|| !reader.nextLine().toLowerCase().equals("equal")) {
System.out.println("Try again!");
reader.next();
}
It kinda just gets stuck at the above part giving "Try again" over and. I've completed programs having to use .hasNextInt() but I'm struggling with this string validation.
Thanks for any and all help/comments!
You are calling reader.nextLine() up to 3 times and so you are comparing 3 different strings.
If I enter "xxx" your code says "xxx != higher so read another line" - it never compares "xxx" to "lower" or "equal".
Also pay attention to && vs ||.
Solution is to read one line into a variable and use that variable for each condition. I'm not going to write it out as this is clearly homework or a self learning exercise, so best for you to do it yourself.
I think your condition logic needs to change. You are checking if input not equal to "higher" or not equal to "lower" or not equal to "equal" so it will always be false overall even if you enter expected value - if you enter "higher" it's not equal to lower. You need to change ors to ands.

How to fix my if statement / program

my problem is that in my code, the if statement I have is supposed to take from a certain pot and then return the value but instead it takes values from both pots instead of one, can't figure out how to fix it. Also my other issue is that every time it takes candy from one pot its supposed to switch to that other pot, how can i do that? The if statement I'm talking about is in the class PassOutCandy.
import java.util.Random;
public class TreatHouse {
int candyPot1; // amount of candy in pot 1
int candyPot2; // amount of candy in pot 2
int currentPot; // 1 or 2
int totalCandy;
int currentTreaters; // variables
int treatsPerTreater;
public TreatHouse(int candyPot, int totalCandy) {
// Add code here, be sure to split the candy between the pots.
currentPot = candyPot;
this.totalCandy = totalCandy;
if (totalCandy <=0) {
System.out.println("We can't give out candy if we don't have amy. I think we have some from last year. " +
"Yep, we have 100 pieces of candy to give out.");
totalCandy = 100;
candyPot1 = totalCandy/2; // splits candy between both pots and sets totalCandy to 100 if user puts in false input
candyPot2 = totalCandy/2;
}
if (totalCandy > 0) {
this.totalCandy = totalCandy;
candyPot1 = totalCandy/2; // with correct user input splits the candy properly between both pots
candyPot2 = totalCandy - candyPot1;
}
}
public int getCandyCount() {
return candyPot1 + candyPot2; // total candy left
}
public void passOutCandy() {
//If there are enough treats per treater for the given amount per treater, pass out candy
//from the current pot and switch to the other one.
//Else display a message that the treaters have been tricked... (no candy for them.)
// but do not change the current pot
if ((totalCandy > 0) && (treatsPerTreater < totalCandy)) {
if (currentPot == 1 || currentPot == 2) {
if (currentPot == 1) {
candyPot1 = candyPot1 - (this.currentTreaters*this.treatsPerTreater);
}
if (currentPot == 2) {
candyPot2 = candyPot2 - (this.currentTreaters*this.treatsPerTreater);
}
}
else
System.out.println("Pot " + currentPot + " doesn't exist. Try again next time");
}
else
System.out.println("You have been tricked! No candy for you >:D!!!!");
}
//Sets the number of trick or treaters.
public void knockKnock() {
Random gen = new Random(System.currentTimeMillis());
this.currentTreaters = gen.nextInt(13) + 1; //1 to 13 treaters.
}
//Displays how much candy in each pot, total candy left
public void getCandyStatus() {
//add in code here
System.out.println("Candy in Pot1: " + candyPot1 + " Candy in Pot2: " + candyPot2); // will display candy in pot 1 / pot 2
System.out.println("Total candy left: " + (candyPot1 + candyPot2)); // total candy left
}
//returns the pot number for which candy was last given.
public int getLastPot() {
if (currentPot == 1 || currentPot == 2) {
if (currentPot == 2) { // returns the last pot that candy was taken from
currentPot = 1;
return currentPot;
}
if (currentPot == 1) {
currentPot = 2;
return currentPot;
}
}
else
return currentPot;
}
public void setTreatsPerTreater(int treatsPerTreater) {
//add code here
this.treatsPerTreater = treatsPerTreater; // sets the proper amount of treats per treater from user input
}
}

boolean will not return false

import java.util.Random;
import java.util.Scanner;
public class HiLo {
/**
* Nick Jones
* 2/10/2015
* High or Low
*/
public static boolean high() {
int x;
boolean answer;
Random randomGenerator = new Random();
x = randomGenerator.nextInt(9 - 1) + 1;
System.out.println("number is " + x);
if (x > 6 && x < 14) {
System.out.println("You win!");
answer = true;
return answer;
} else {
System.out.println("You lose!");
answer = false;
return answer;
}
}
public static boolean low() {
int x;
boolean answer;
Random randomGenerator = new Random();
x = randomGenerator.nextInt(9 - 1) + 1;
System.out.println("number is " + x);
if (x > 0 && x < 7) {
System.out.println("You win!");
answer = true;
return answer;
} else {
System.out.println("You lose!");
answer = false;
return answer;
}
}
public static void main(String[] args) {
int points = 1000;
int risk;
int guess;
boolean answer;
int again;
do {
System.out.println("you have " + points + " points.");
Scanner input = new Scanner (System.in);
System.out.println ("Input number of points to risk: ");
risk = input.nextInt();
System.out.println ("predict <1-high, 0-low>: ");
guess = input.nextInt();
if (guess == 1) {
answer = high();
} if (guess == 0) {
answer = low();
}
if (answer = true) {
points = points + (risk*2);
**} if (answer = false) {
points = points - risk;**
}
System.out.println("You have " + points + " points.");
System.out.println("play again?<yes-1, no-0> ");
again = input.nextInt();
} while (again == 1);
}
}
This program is meant to start with the player having a score of 1000 points a number is then randomly generated and they chose a amount of their score to 'risk' then chose high or low (low - 1-6. high - 8-13) if their guess is correct their risk is doubled and added back into their score. If incorrect then risk is subtracted from score. my boolean statment seems to be stopping the program from
if (answer = false) {
points = points - risk;
this part, so my boolean never returns false is what I believe my problem is. because when run it only ever allows the player to win, never to lose, it will output that 'you lose' but still add the points as if they had won.
You are using the assignment operator =, so answer is always true. The comparison operator for equality is ==, as you have already used elsewhere in your code. But answer is already a boolean. There is no need to use == to compare it; just use it. Change
if (answer = true) {
points = points + (risk*2);
} if (answer = false) {
points = points - risk;
}
to
if (answer) {
points = points + (risk*2);
} else {
points = points - risk;
}

Categories

Resources