BlackJack in Java with same Deck(s) for Dealer-Player - java

I am writing a program in Java that is a classic BlackJack Game.
The rules are the same,and we make choices as players and the dealer(CPU) plays under some rules.
My code, that is beneath, makes 2 seperate stacks of Deck(s),one for Player and one for Dealer and each one draws from a different Deck but i want to make them both(Player and Dealer) draw from the same Deck(s).
Any suggestions/corrections on my Code ?
import java.util.Random;
import java.util.Scanner;
public class River
{
private int CardNumber;
private int BeginCards;
private int Decks;
private int[] PartialSumArray = {4,8,12,16,20,24,28,32,36,52};
private int[] BeginPartialSumArray = {4,8,12,16,20,24,28,32,36,52};
private int PickedCard;
private Random randomGenerator = new Random();
//Constructor without definition
public River()
{
CardNumber = 52;
BeginCards = 52;
}
//Constructor with definition
public River(int Decks)
{
CardNumber = Decks * 52;
BeginCards = CardNumber;
this.Decks = Decks;
//Initialize partial sum array for many decks of cards
for (int i=0; i<10; i++)
{
PartialSumArray[i] = PartialSumArray[i] * Decks;
BeginPartialSumArray[i] = PartialSumArray[i] * Decks;
}
System.out.println();
}
//Create random numbers
private int computeRandomSteps(int CardNumber)
{
//System.out.print("stin random , cardnumber is" + CardNumber);
int randomSteps = randomGenerator.nextInt(CardNumber-1);
return randomSteps;
}
public int nextCard()
{
int steps = computeRandomSteps(CardNumber);
int position=0;
for (int i=0; i<CardNumber; i++)
{
if (steps<= PartialSumArray[i])
{
position = i+1;
break;
}
}
CardNumber--;
return position;
}
public int start()
{
int ShuffleLimit;
PickedCard = nextCard();
System.out.println("Picked card is :" + PickedCard);
int HelpVariable = PickedCard-1;
for (int i=0; i<10; i++)
{
if (i >= HelpVariable)
{
PartialSumArray[HelpVariable] = PartialSumArray[i]-1;
HelpVariable++;
}
}
ShuffleLimit = BeginCards/4;
if (CardNumber<ShuffleLimit)
{
for (int i=0; i<9; i++)
{
BeginPartialSumArray[i] = BeginPartialSumArray[i] * Decks;
}
}
return PickedCard;
}
public int ReturnCardNumber()
{
System.out.println("return cardnumber is " + CardNumber);
return CardNumber;
}
}
class Hand
{
private int points;
private int SumPoints=0;
private boolean Ace = true;
Scanner input = new Scanner(System.in);
//Scanner input3 = new Scanner(System.in);
//int Decks = input3.nextInt();
River myRiver = new River();
//River myRiver = new River(Decks);
public int getPoints()
{
points = myRiver.start();
if (points == 1 && Ace)
{
System.out.println("It is an Ace. Do you want to count 1 or 11?");
points = input.nextInt();
Ace = false;
}
SumPoints += points;
System.out.println("Points are : " + SumPoints);
return SumPoints;
}
public int getPointsDealer()
{
points = myRiver.start();
if (points == 1 && Ace)
{
if (SumPoints + 11 > 21)
{
points = 1;
}
else
{
points = 11;
}
Ace = false;
}
SumPoints += points;
System.out.println("Points are : " + SumPoints);
return SumPoints;
}
}
class Player
{
private int points;
private double account=0;
private double bet;
private boolean WinOrLose;
Scanner input1 = new Scanner(System.in);
Scanner input2 = new Scanner(System.in);
public double placeBet()
{
System.out.println("How much do you want to bet?");
bet = input1.nextDouble();
return bet;
}
public double profit(boolean WinOrLose)
{
if (WinOrLose)
{
account += bet;
return account;
}
else
{
account -= bet;
return account;
}
}
public int play(River other)
{
Hand myHand = new Hand();
bet = placeBet();
points = myHand.getPoints();
boolean end = true;
String Choice;
while (end)
{
System.out.println("Make a choice");
Choice = input2.nextLine();
switch(Choice)
{
case "DoubleBet":
bet = bet *2;
points = myHand.getPoints();
if (points > 21)
{
System.out.print("Burned!");
WinOrLose = false;
account = profit(WinOrLose);
end = false;
break;
}
else if (points == 21)
{
System.out.print("You won!");
WinOrLose = true;
account = profit(WinOrLose);
end = false;
break;
}
else
{
System.out.println("Your points are :" + points);
end = false;
break;
}
case "stop":
System.out.println("Your points are :" + points);
end = false;
break;
case "Hit":
points = myHand.getPoints();
if (points > 21)
{
System.out.print("Burned!");
WinOrLose = false;
account = profit(WinOrLose);
end = false;
break;
}
else if (points == 21)
{
System.out.print("You won!");
WinOrLose = true;
account = profit(WinOrLose);
end = false;
break;
}
break;
default:
System.out.println("That is not a choice.");
end = false;
break;
}
}
return points;
}
}
class BlackJack
{
public static void main(String args[])
{
int SumPointsPlayer;
int SumPointsDealer;
boolean WinOrLose = true;
double account;
int Decks;
int BeginCards;
int ThisMomentCards;
Scanner input1 = new Scanner(System.in);
Scanner input2 = new Scanner(System.in);
System.out.println("How many decks do you want to begin with?");
Decks = input1.nextInt();
River myRiver = new River(Decks);
Player myPlayer = new Player();
//Calculate the cards we have when the game starts
BeginCards = 52 * Decks;
System.out.println("Do you want to start the game? Yes or No.");
String Repeat;
Repeat = input2.nextLine();
while (Repeat.equals("Yes"))
{
ThisMomentCards = myRiver.ReturnCardNumber();
System.out.println("Cards are : " + ThisMomentCards);
//Player's points for 1 round
SumPointsPlayer = myPlayer.play(myRiver);
//If player catches 21 he wins instantly
if(SumPointsPlayer == 21)
{
account = myPlayer.profit(WinOrLose);
System.out.println("Your account has :" + account + "dollars!");
}
//If player catches >21 he loses instantly
else if(SumPointsPlayer > 21)
{
WinOrLose = false;
account = myPlayer.profit(WinOrLose);
System.out.println("Your account has :" + account + "dollars!");
}
//Compare the hand of player and dealer and the bigger wins
else
{
//Dealer's points for 1 round
SumPointsDealer = playDealer(myRiver);
//If dealer catches >21 he loses instantly
if(SumPointsDealer>21)
{
System.out.println("Player wins!");
account = myPlayer.profit(WinOrLose);
System.out.println("Your account has :" + account + "dollars!");
}
//Hand of player bigger than the hand of the dealer , player wins
else if (SumPointsPlayer>SumPointsDealer)
{
WinOrLose = true;
account = myPlayer.profit(WinOrLose);
System.out.println("Player wins. Your account has :" + account + "dollars!");
}
//Hand of player smaller than the hand of the dealer , dealer wins
else if (SumPointsPlayer<SumPointsDealer)
{
WinOrLose = false;
account = myPlayer.profit(WinOrLose);
System.out.println("Player lost. Your account has :" + account + "dollars!");
}
//Hand of player is equal with the hand of the dealer , it is tie
else
{
System.out.println("Player and Dealer are tie!!");
}
}
System.out.println("Do you want to continue the game? Yes or No.");
Repeat = input2.nextLine();
}
}
public static int playDealer(River other)
{
boolean bountry = true;
System.out.println("Dealer plays :");
Hand myHand = new Hand();
int SumPointsDealer = myHand.getPointsDealer();
while (bountry)
{
if (SumPointsDealer<17)
{
SumPointsDealer = myHand.getPointsDealer();
}
else if (SumPointsDealer>21)
{
System.out.println("Dealer burned!");
bountry = false;
}
else
{
bountry = false;
}
}
return SumPointsDealer;
}
}
Some Clarifications:
1) The way we draw randomly a card is based on a strange way but this is not the problem its ok the way the program Does draw randomly cards from the Decks
2) Another problem that i noticed is that in class Hand the code that i have in // is not working as it doesnt allow me to have a System.out.println()
Scanner input = new Scanner(System.in);
//Scanner input3 = new Scanner(System.in);
//int Decks = input3.nextInt();
River myRiver = new River();
//River myRiver = new River(Decks);
I wanted to do this so that i will say with how many Decks the user wants to play

You can do better and easier of code is oriented into objects.
i.e. Collections.shuffle(Deck) replaces that whole random conundrum
where Deck is your created Object made of such attributes as LinkedList and a counter[deck value]
hope that helps.
remove object Card from linked list of main deck and move it into the deck of a player. and yes, you can create as many decks as you want that way.
object Card has attributes Value and Suit.

Related

Homework error java.lang.IllegalAccessException

I am currently attempting to finish my first coding Homework assignment, and My teacher and TA are utterly useless. I have been stuck on this problem and many more for days now with no response other than "There is an error" whenever I ask for help. When I try to run my code in Eclipse, it works perfectly and I have no errors that I have noticed. But, when I try to execute it from the cmd prompt I get the following message:
Exception in thread "main" java.lang.IllegalAccessException: Class org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader can not access a member of class ATM with modifiers "public static"
at sun.reflect.Reflection.ensureMemberAccess(Unknown Source)
at java.lang.reflect.AccessibleObject.slowCheckMemberAccess(Unknown Source)
at java.lang.reflect.AccessibleObject.checkAccess(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58)
I have tried googling it, and as far as I have found, the Illegal Access Exception is thrown only for Private and Final methods, which I do not have any of in my code. Any help would be greatly appreciated! Also, please realize that my code may not be good as I have had to teach myself how to code completely.
import java.util.Scanner;
public class ATM {
static Scanner read = new Scanner(System.in); //created a scanner
static String inpCard;
static int listId = -1; //created an int to store the id of the place in which the ATMCard is stored under
static int withdrawlAMT = 0;
public static void main(String[] args) {
cardServices.initializeCardDB(); //enters the array's content
// asks for card number
if(cardServices.insertCard() == true) {
//checks for the pin to be correct
if(pin.processPin() == true) {
int x = account.select();
//if the account selected is checkings, it = 1.
if(x == 1) {
//asks user for how much to withdrawal.
money.moneyAmount();
// insures you dont have to little to withdrawal
// that much, loops forever if you try to withdrawal
// to much.
if(security.verifyBalCheck(withdrawlAMT) == true) {
cardServices.processCard(withdrawlAMT, "checking");
dispense.dispensing();
System.out.println("Your new balance is " +cardServices.cardList[listId].checkBal);
System.out.println("");
cardServices.returnCard();
}
}
//if the account selected is savings, it = 2.
if(x == 2) {
// asks user for how much to withdrawal
money.moneyAmount();
// insures you dont have to little to withdrawal
// that much, loops forever if you try to withdrawal
// to much.
if(security.verifyBalSaving(withdrawlAMT) == true) {
cardServices.processCard(withdrawlAMT, "savings");
dispense.dispensing();
System.out.println("Your new balance is " +cardServices.cardList[listId].savingsBal);
System.out.println("");
cardServices.returnCard();
}
}
}
}
}
}
class ATMBal
{
static int one = 50;
static int five = 40;
static int ten = 25;
static int twenty = 20;
static int total = 1000;
}
class ATMCard //Creating the blueprint for all cards
{
public String cardNum = " "; //Made both cardNum and cardPin to string, to avoid octal numbers
public String cardPin = " ";
public float checkBal = 0;
public float savingsBal = 0;
}
class cardServices
{
static ATMCard[] cardList = new ATMCard[5];
public static void initializeCardDB()
{
cardList[0] = new ATMCard();
cardList[0].cardNum = "123456789"; //added card 1's information
cardList[0].cardPin = "1111";
cardList[0].checkBal = 550;
cardList[0].savingsBal = 1275;
cardList[1] = new ATMCard();
cardList[1].cardNum = "135792468"; //added card 2's information
cardList[1].cardPin = "2097";
cardList[1].checkBal = 90;
cardList[1].savingsBal = -1;
cardList[2] = new ATMCard();
cardList[2].cardNum = "019283746"; //added card 3's information
cardList[2].cardPin = "6194";
cardList[2].checkBal = 7915;
cardList[2].savingsBal = -1;
cardList[3] = new ATMCard();
cardList[3].cardNum = "675849302"; //added card 4's information
cardList[3].cardPin = "0071";
cardList[3].checkBal = 790;
cardList[3].savingsBal = 211;
cardList[4] = new ATMCard();
cardList[4].cardNum = "347821904"; //added card 5's information
cardList[4].cardPin = "9871";
cardList[4].checkBal = 113;
cardList[4].savingsBal = 78;
}
public static boolean insertCard()
{
System.out.print("Please insert your card: "); //ask for card number
ATM.inpCard = ATM.read.nextLine(); //read card number
for(int i = 0; i < 5; i++) //start a loop
{
if(ATM.inpCard.compareTo(cardServices.cardList[i].cardNum) == 0) //checks all card numbers in the database, to see if they matched the input card
{
ATM.listId = i;
return true;
}
if(i == 4)
{
System.out.println("I'm sorry, your card was not found in our system.");
insertCard();
return false;
}
}
return false;
}
public static void processCard(int withdrawalAmount, String account) //actual process withdrawing the amount from the card
{
if(account.compareTo("checking") == 0)
cardServices.cardList[ATM.listId].checkBal = cardServices.cardList[ATM.listId].checkBal - withdrawalAmount;
if(account.compareTo("savings") == 0)
cardServices.cardList[ATM.listId].savingsBal = cardServices.cardList[ATM.listId].savingsBal - withdrawalAmount;
}
public static void returnCard() //returns the inpCard through a tempCard to insure all stored data is removed to increase security
{
System.out.println("Thank you for using Bank of America's new ACME ATMs, have a fantastic day!");
String tempCard = ATM.inpCard;
ATM.inpCard = null;
System.out.println("Here is your card: " +tempCard);
}
}
class pin
{
public static boolean processPin()
{
System.out.print("Please enter your pin number "); //asking for pin then read pin
String inpPinNum = ATM.read.nextLine();
for(int i = 0; i < 4; i++) //created loop
{
if(inpPinNum.compareTo(cardServices.cardList[ATM.listId].cardPin) == 0)
{
return true;
}
else
if(i < 3) //checks attempt amount to insure it is less than the allowed 4
{
System.out.println("Incorrect, please re-enter your pin:");
inpPinNum = ATM.read.nextLine();
}
if(i == 3) //if the pin has been incorrectly 4 times, the user is told that the card will be eaten
{
System.out.println("You have entered your pin incorrectly to many times,"
+ " your card is being destroyed. Please go to any Bank of America to recieve a new card");
eatCard(); //the eatCard() command is called to eat the card
}
}
return false;
}
public static void eatCard() //deletes the card in the system, without returning the card
{
ATM.inpCard = null;
}
}
class security
{
public static boolean verifyBalCheck(int withdrawlAmt) //checks checking balance
{
if(!(withdrawlAmt <=cardServices.cardList[ATM.listId].checkBal))
{
System.out.println("I'm sorry, you're current balance is: " +cardServices.cardList[ATM.listId].checkBal +", and as such you do not have enough to withdrawal that amount.");
money.moneyAmount();
return false;
}
return true;
}
public static boolean verifyBalSaving(int withdrawlAmt) //checks savings balance
{
if(!(withdrawlAmt <=cardServices.cardList[ATM.listId].savingsBal))
{
System.out.println("I'm sorry, you're current balance is: " +cardServices.cardList[ATM.listId].savingsBal +", and as such you do not have enough to withdrawal that amount.");
money.moneyAmount();
return false;
}
return true;
}
public boolean verifyMachineBalance(int withdrawlAmt) //checks ATM Machine Balance
{
if(withdrawlAmt <= ATMBal.total)
{
return true;
}
return false;
}
}
class account
{
public static int select()
{
System.out.print("Would you like to withdrawal from Checkings or Savings? ");
String type = ATM.read.nextLine();
if(type.compareToIgnoreCase("checkings") == 0) //checks to see if the string is checkings, returns 1 if so
{
return 1;
}
if(type.compareToIgnoreCase("savings") == 0) //checks to see if the string is savings, returns 2 if so
{
return 2;
}
return 0;
}
}
class money
{
public static void moneyAmount()
{
System.out.print("How much would you like to withdrawl? ");
ATM.withdrawlAMT = Integer.parseInt(ATM.read.nextLine());
}
}
class dispense
{
public static void dispensing()
{
ATMBal.total = ATMBal.total - ATM.withdrawlAMT; //removes the withdrawalAmt from total
System.out.println("");
System.out.println("Your total withdrawal amount is: " +ATM.withdrawlAMT);
while(ATM.withdrawlAMT >= 20 && ATMBal.twenty > 0) //checks to figure out the biggest bills the machine is able to dispense
{
ATM.withdrawlAMT = ATM.withdrawlAMT - 20;
ATMBal.twenty = ATMBal.twenty - 1;
}
while(ATM.withdrawlAMT >= 10 && ATMBal.ten > 0)
{
ATM.withdrawlAMT = ATM.withdrawlAMT - 10;
ATMBal.ten = ATMBal.ten - 1;
}
while(ATM.withdrawlAMT >= 5 && ATMBal.five > 0)
{
ATM.withdrawlAMT = ATM.withdrawlAMT - 5;
ATMBal.five = ATMBal.five - 1;
}
while(ATM.withdrawlAMT >= 1 && ATMBal.one > 0)
{
ATM.withdrawlAMT = ATM.withdrawlAMT - 1;
ATMBal.one = ATMBal.one - 1;
}
int twenties = 20 - ATMBal.twenty; //Stoes how many of each will be dispensed
int tens = 25 - ATMBal.ten;
int fives = 40 - ATMBal.five;
int ones = 50 - ATMBal.one;
System.out.println("This is comprised of: " +twenties +" twenties, " //prints how much of each bill is being dispensed
+tens +" tens, "
+fives +" fives, and "
+ones +" ones");
}
}

Creating an array of objects but it doesn't find the symbols

I am creating an array of Players in a minigame in Java. There is a class called Players and one called Game.
In the Main we scan two names and send them to the Game
game.createPlayer(name1, name2);
and later on try to get some information back
playerArray[(game.getPlayerTurn() % 2)].getPlayerName();
The Player gets constructed in the Game as an array:
public class Game
{
private Player[] playerArray;
[...]
public void createPlayer(String name1, String name2)
{
Player[] playerArray = new Player[2];
playerArray[0] = new Player(name2);
playerArray[1] = new Player(name1);
}
with the Player as a standard class:
public class Player
{
private String playerName;
public Player( String playerName )
{
this.playerName = playerName;
}
public String getPlayerName()
{
return playerName;
}
}
This however returns multiple errors saying it cannot find the symbol wherever i try to find out the name of the player. Did I not properly instanciate them?
Additional code (as per request):
package oop.nimspiel;
import java.util.Scanner;
import java.util.Arrays;
public class Game
{
private int take;
private int turn;
private int playerTake;
private int playerTurn;
protected Player[] playerArray;
public Game(int turn, int playerTurn)
{
this.turn = turn;
this.playerTurn = playerTurn;
}
protected void setPlayerTake(int take)
{
this.playerTake = take;
}
public int getPlayerTake()
{
return playerTake;
}
public void incrementTurns()
{
turn = turn + 1;
playerTurn = playerTurn + 1;
}
public int getTurn()
{
return turn;
}
public int getPlayerTurn()
{
return playerTurn;
}
public void createPlayer(String name1, String name2)
{
this.playerArray = new Player[2];
playerArray[0] = new Player(name2);
playerArray[1] = new Player(name1);
}
public String getPlayer()
{
String playerName = playerArray[(getPlayerTurn() % 2)].getPlayerName();
return playerName;
}
public void checkTake(int take)
{
Scanner input = new Scanner(System.in);
this.take = take;
boolean rightInput = false;
do {
if (take < 1 || take > 3)
{
System.out.println("Your input was wrong, please use a number between 1 and 3.");
System.out.println("How many stones would you like to take?");
take = input.nextInt();
rightInput = false;
}
else if (stoneheap.getStones() < take) {
System.out.println("There are only " + stoneheap.getStones() + " stones left.");
System.out.println("Please take less.");
System.out.println("How many stones would you like to take?");
take = input.nextInt();
rightInput = false;
}
else
{
rightInput = true;
}
} while (rightInput == false);
}
}
and the Main:
package oop.nimspiel;
import java.util.Random;
import java.util.Scanner;
import java.util.Arrays;
public class Main
{
private int take;
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String nextRound;
do
{
int maxPlayers = 2;
int startTurn = 1;
Game game = new Game ( startTurn, (1 + (int)(Math.random() * ((maxPlayers - 1) + 1)) ) );
int minStones = 20;
int maxStones = 30;
Stoneheap stoneheap = new Stoneheap((minStones + (int)(Math.random() * ((maxStones - minStones) + 1)) ) );
System.out.println("Rules: Two players take stones from a heap of 20 to 30 until there are no more left. The one to take the last stone loses. Each round you can only take between 1 - 3 stones. Have fun!"); // Rules
System.out.println("");
System.out.println("Hello Player 1, what is your name?");
String name1 = input.next();
System.out.println("");
System.out.println("Hello Player 2, what is your name?");
String name2 = input.next();
game.createPlayer(name1, name2);
System.out.println("");
System.out.println("Number of stones: " + stoneheap.getStones());
System.out.println("The first to draw is Player " + game.getPlayerTurn());
System.out.println("The game starts now!");
while (stoneheap.getStones() > 0)
{
if ((game.getPlayerTurn() % 2) > 0) // Turn Player 1
{
System.out.println("It is your turn " + playerArray[(game.getPlayerTurn() % 2)].getPlayerName() + ".");
System.out.println("How many stones would you like to take?");
int take = input.nextInt();
game.checkTake(take);
game.setPlayerTake(take);
stoneheap.currentStones();
System.out.println("There are " + stoneheap.getStones() + " stones left.");
}
else // Turn Player 2
{
System.out.println("It is your turn " + playerArray[(game.getPlayerTurn() % 2)].getPlayerName() + ".");
System.out.println("How many stones would you like to take?");
int take = input.nextInt();
game.checkTake(take);
game.setPlayerTake(take);
stoneheap.currentStones();
System.out.println("There are " + stoneheap.getStones() + " stones left.");
}
game.incrementTurns();
}
System.out.println("The game has ended and the winner is ...");
System.out.println(playerArray[(game.getPlayerTurn() % 2)].getPlayerName());
System.out.println("It took " + (game.getTurn() - 1) + " turns." );
System.out.println("");
System.out.println("Do you want to play another round? Y for yes, anything else for no");
String userInput = input.next();
nextRound = userInput.toUpperCase();
} while (nextRound.equals("Y"));
}
}
In your createPlayer method, you should access playerArray by this keyword (this.playerArray = new Player[2]).
Currently you are creating an array on the fly, and the class variable is untouched, that's why you are getting an exception.
public class Game
{
private Player[] playerArray;
[...]
public void createPlayer(String name1, String name2)
{
this.playerArray = new Player[2];
playerArray[0] = new Player(name2);
playerArray[1] = new Player(name1);
}

Java - BlackJack project - Problems with I/O and cycles

I'm trying to make a simple BlackJack game driven by character input and I'm having a lot of problems in the later part it.
I commented the part that's giving me troubles, the rest doesn't seem to have errors and I did unit test it.
So, what did I do? I created a class that holds the cards drawn and manages them, table, player and dealer are both instances of table.
A table has max 5 cards(for simplicity), every card object comes from the Card class that has a method to add data to the card object.
The main class drives the program and the decisions are made with a character input from the keyboard, I get problems at that point.
import java.io.IOException;
class Table{
Card[] hand = new Card[5];
int counter = 1;
Table() {
for ( int i=0; i<hand.length; i++) {
hand[i]=new Card();
}
hand[0].GetCard();
}
void ReadCards(){
for(int i= 0;i<counter;i++ ) {
System.out.println("The card "+(i+1)+" is " + hand[i].name + " "+ hand[i].seed + "." );
}
}
void DrawCards() {
hand[counter].GetCard();
counter++;
}
boolean isOut() {
int sum = 0;
for(int i= 0;i<counter;i++ ) {
sum += hand[i].value;
if(sum >21) {
return true;
}
}
return false;
}
int TheSum() {
int sum = 0;
for(int i= 0;i<counter;i++ ) {
sum += hand[i].value;
}
return sum;
}
boolean isWIN(Table p2) {
int sum = 0;
int sump2 = 0;
for(int i= 0;i<counter;i++ ) {
sum += hand[i].value;
}
for(int i= 0;i<p2.counter;i++ ) {
sump2 += p2.hand[i].value;
}
if (sum>sump2) {
return true;
}
else return false;
}
class Card {
public int value = 0;
public String name = "";
public String seed = "";
void GetCard(){
int positive = 0;
do {
positive = (int) (Math.random()*100) % 10;
}while(positive == 0 );
value = positive;
if(value<10) {
name = String.valueOf(value);
}
else {
positive = 0;
do {
positive = (int) (Math.random()*100) % 3;
}while(positive == 0 );
switch(positive) {
case 1:
name = "J";
break;
case 2:
name = "Q";
break;
case 3:
name ="K";
break;
}
}
positive = 0;
do {
positive = (int) (Math.random()*100) % 4;
}while(positive == 0 );
switch(positive) {
case 1:
seed = "CLUB";
break;
case 2:
seed = "DIAMOND";
break;
case 3:
seed ="SPADE";
break;
case 4:
seed ="HEART";
break;
}
}
}
}
public class BlackJack {
public static void main(String args[])throws IOException {
System.out.println("Welcome to the BlackJack's table! Press y to start! ");
char flag;
do {
flag = (char)System.in.read();
}while(flag != 'y' );
Table dealer = new Table();
Table player = new Table();
System.out.println("DEALER");
dealer.ReadCards();
System.out.println("PLAYER");
player.ReadCards();
flag = ' ';
System.out.println("Do you want to draw a card? I'll draw until you'll press n");
/*
flag = (char)System.in.read();
while(flag != 'n' ) {
player.DrawCards();
player.ReadCards();
if (player.isOut()) {
System.out.println("YOU LOSE");
System.exit(0);
}
flag = (char)System.in.read();
}
System.out.println("The dealer will draw");
while(dealer.TheSum()<18) {
dealer.DrawCards();
dealer.ReadCards();
if (dealer.isOut()) {
System.out.println("YOU WIN");
System.exit(0);
}
}
*/
System.out.println("WHO WON?");
if (player.isWIN(dealer)){
System.out.println("YOU WIN");
}
else System.out.println("YOU LOSE");
}
}
And yes, I'm not used to java.
Console screenshot of the output here!
Here is an example of fixing your looping issues, however there may be some issue with the game logic, which is out of the scope of this question.
public static void main(String args[]) throws IOException {
Scanner s = new Scanner(System.in);
System.out.println("Welcome to the BlackJack's table! Press y to start! ");
char flag;
do {
flag = (char) s.nextLine().charAt(0);
} while (flag != 'y');
Table dealer = new Table();
Table player = new Table();
System.out.println("DEALER");
dealer.ReadCards();
System.out.println("PLAYER");
player.ReadCards();
flag = ' ';
System.out.println("Do you want to draw a card? I'll draw until you'll press n");
while (true) {
flag = s.nextLine().charAt(0);
if (flag == 'n') {
break;
}
player.DrawCards();
player.ReadCards();
if (player.isOut()) {
System.out.println("YOU LOSE");
System.exit(0);
}
System.out.println("The dealer will draw");
while (dealer.TheSum() < 18) {
dealer.DrawCards();
dealer.ReadCards();
if (dealer.isOut()) {
System.out.println("YOU WIN");
System.exit(0);
}
}
System.out.println(String.format("The dealer has finished drawing. Dealers score %d. Your score %d", dealer.TheSum(), player.TheSum()));
}
System.out.println("WHO WON?");
if (player.isWIN(dealer)) {
System.out.println("YOU WIN");
} else {
System.out.println("YOU LOSE");
}
}
Output:
Welcome to the BlackJack's table! Press y to start!
y
DEALER
The card 1 is 8 CLUB.
PLAYER
The card 1 is 2 SPADE.
Do you want to draw a card? I'll draw until you'll press n
n
WHO WON?
YOU LOSE

update a variable in a different class

How do I make amount() in class Casino.java store the total value and allow it to be returned to the class Roulette.java.
When I use:
int amount = Casino.amount();
It gives me several hundred lines of errors.
What I want done is to run the game number() and store the value into Casino.amount()
Please note in class Roulette.java there is a function called amountUpdate() which should update Casino.amount().
This is class Casino.java
package Casino;
import java.util.*;
public class Casino {
static String player = "";
static int playAmount = 0;
public static void main(String[] args) {
System.out.println("Welcome to Michael & Erics Casino!");
player();
ask();
start();
}
public static String player() {
if (player.equals("")) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter your name : ");
player = sc.nextLine();
}
return player;
}
public static void ask() {
Scanner sc = new Scanner(System.in);
System.out.println("How much would you like to play with? ");
playAmount = sc.nextInt();
if (playAmount < 1) {
System.out.println("Please enter a value that is more than $1");
playAmount = 0;
}
System.out.println("You are playing with: $" + playAmount + "\n");
}
public static int amount() {
int amount = playAmount;
if (Roulette.amountUpdate() >= 1) {
amount += Roulette.amountUpdate();
}
return amount;
/*if (Blackjack.amountUpdate() >= 1)
amount += Blackjack.amountUpdate();
return amount;*/
}
public static void start() {
System.out.println("Which table would you like to play at?");
System.out.println("1: Blackjack");
System.out.println("2: Roulette");
System.out.println("3: Check Balance");
System.out.println("4: Exit");
Scanner sc = new Scanner(System.in);
int table = sc.nextInt();
switch (table) {
case 1:
//blackjack.main(new String[]{});
break;
case 2:
Roulette.main(new String[]{});
break;
case 3:
System.out.println("You have : $" + playAmount);
start();
break;
case 4:
System.exit(0);
break;
}
}
}
This is class Roulette.java
package Casino;
import java.util.*;
import java.lang.*;
public class Roulette {
public static void main(String[] args) {
System.out.println("Welcome to the roulette table " + Casino.player());
placeBet();
amountUpdate();
//number();
}
public static int amountUpdate() {
int amount = 0;
if (number() > 0) {
amount += number();
}
if (br() > 0) {
amount += br();
}
if (oe() > 0) {
amount += oe();
}
if (third() > 0) {
amount += third();
}
return amount;
}
public static void placeBet() {
Scanner sc_Choice = new Scanner(System.in);
System.out.println("What would you like to bet on?");
System.out.println("1: Numbers");
System.out.println("2: Black or Red");
System.out.println("3: Odd or Even");
System.out.println("4: One Third");
System.out.println("5: Count Chips");
System.out.println("6: Restart");
int choice = sc_Choice.nextInt();
if (choice > 0 && choice < 7) {
switch (choice) {
case 1:
number();
break;
case 2:
br();
break;
case 3:
oe();
break;
case 4:
third();
break;
case 5:
System.out.println(Casino.amount());
break;
case 6:
Casino.main(new String[]{});
break;
}
} else {
System.out.println("You must choose between 1 and 6");
}
}
public static int number() {
Boolean betting = true;
//int amount = Casino.amount();
int amount = 5000;
int number;
int winnings;
String reply;
int betX;
int betAgain = 1;
Scanner sc_Number = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<Integer>();
ArrayList<Integer> bet = new ArrayList<Integer>();
while (betAgain == 1) {
System.out.println("What number would you like to place a bet on?");
int listCheck = sc_Number.nextInt();
if (listCheck >= 0 && listCheck <= 36) {
list.add(listCheck);
} else {
System.out.println("You must choose a number between 0 and 36");
}
System.out.println("How much do you want to bet?");
betX = sc_Number.nextInt();
if (betX > amount) {
System.out.println("You have insufficient funds to make that bet");
number();
} else if (betX < 1) {
System.out.println("You must bet more than 1$");
} else {
bet.add(betX);
amount = amount - betX;
}
System.out.println("Do you want to bet on more numbers?");
reply = sc_Number.next();
if (reply.matches("no|No|false|nope")) {
betAgain = betAgain - 1;
//No - Don't bet again
} else {
betAgain = 1;
//Yes - Bet again
}
int result = wheel();
System.out.println("Spinning! .... The number is: " + result);
for (int i = 0; i < bet.size(); i++) {
if (list.get(i) == result) {
winnings = bet.get(i) * 35;
System.out.println("Congratulations!! You won: $" + winnings);
amount = amount + winnings;
System.out.println("Current Balance: " + amount);
betAgain = betAgain - 1;
} else {
System.out.println("Sorry, better luck next time!");
System.out.println("Current Balance: " + amount);
betAgain = betAgain - 1;
}
}
betAgain = betAgain - 1;
}
return amount;
}
public static int wheel() {
Random rnd = new Random();
int number = rnd.nextInt(37);
return number;
}
//NOT WORKING - AFTER MAKING A BET IT RUNS Number()
public static int br() {
Scanner sc_br = new Scanner(System.in);
int amount = Casino.amount();
int winnings;
System.out.println("Would you like to bet on Black or Red?");
String replyBR = sc_br.nextLine();
boolean black;
//****************
if (replyBR.matches("black|Black")) {
black = true;
} else {
black = false;
}
System.out.println("How much would you like to bet?");
int betBR = sc_br.nextInt();
if (betBR > amount) {
System.out.println("You have insufficient funds to make that bet");
br();
} else if (betBR < 1) {
System.out.println("You must bet more than 1$");
br();
} else {
amount = amount - betBR;
}
//*****************
boolean resultColour = colour();
if (resultColour == black) {
winnings = betBR * 2;
//PRINT OUT WHAT COLOUR!!!
System.out.println("Congratulations!! You won: $" + winnings);
amount = amount + winnings;
System.out.println("Current Balance: " + amount);
} else {
System.out.println("Sorry, better luck next time!");
}
System.out.println("Current Balance: " + amount);
return amount;
}
public static boolean colour() {
Random rnd = new Random();
boolean colour = rnd.nextBoolean();
return colour;
}
//NOT WORKING - AFTER MAKING A BET IT RUNS Number()
public static int oe() {
Scanner sc_oe = new Scanner(System.in);
int amount = Casino.amount();
int winnings;
System.out.println("Would you like to bet on Odd or Even?");
String replyOE = sc_oe.next();
System.out.println("How much would you like to bet?");
int betOE = sc_oe.nextInt();
if (betOE > amount) {
System.out.println("You have insufficient funds to make that bet");
oe();
}
amount = amount - betOE;
boolean resultOE = oddOrEven();
//PRINT OUT IF IT WAS ODD OR EVEN
if (resultOE == true) {
winnings = betOE * 2;
System.out.println("Congratulations!! You won: $" + winnings);
amount = amount + winnings;
System.out.println("Current Balance: " + amount);
} else {
System.out.println("Sorry, better luck next time!");
System.out.println("Current Balance: " + amount);
}
return amount;
}
public static boolean oddOrEven() {
Random rnd = new Random();
boolean num = rnd.nextBoolean();
return num;
}
//NOT WORKING - AFTER MAKING A BET IT RUNS Number()
public static int third() {
Scanner sc_Third = new Scanner(System.in);
int amount = Casino.amount();
int winnings;
System.out.println("Would you like to bet on 1st, 2nd or 3rd third?");
String replyT = sc_Third.next();
System.out.println("How much would you like to bet?");
int betT = sc_Third.nextInt();
if (betT > amount) {
System.out.println("You have insufficient funds to make that bet");
third();
}
amount = amount - betT;
boolean resultT = thirdResult();
//PRINT OUT WHAT NUMBER IT WAS AND IF IT WAS IN WHICH THIRD
if (resultT == true) {
winnings = betT * 3;
System.out.println("Congratulations!! You won: $" + winnings);
amount = amount + winnings;
System.out.println("Current Balance: " + amount);
} else {
System.out.println("Sorry, better luck next time!");
System.out.println("Current Balance: " + amount);
}
return amount;
}
public static boolean thirdResult() {
Random rnd = new Random();
int num = rnd.nextInt(2);
if (num == 0) {
return true;
} else {
return false;
}
}
}
Looks like you're probably running into a StackOverflowException. When you call Casino.amount() inside of Roulette.number(), it then calls Roulette.amountUpdate(), which then calls Roulette.number(). Your methods are stuck in an infinite loop like this. You'll need to redesign your code such that these 3 functions are not all dependent on each other.
Your code is terse, so it's hard to help you fully solve the problem, but I believe you would benefit from splitting up your "amount" variable into separate entities. Keep things like bet amount, winnings, and such separate until you need to combine them.
Another issue you may run into is thatRoulette.amountUpdate() is called twice in Casino.amount(), but Roulette.amountUpdate() will not necessarily return the same thing both times. Consider storing the return value from the first call instead of calling it twice.

Blackjack program score total

So in my blackjack program when each game ends the program asks you if you would to play again. My main problem right now is that when the new game is started the score counter just keeps adding the new score to the old score instead of resetting to 0. Im not really sure how to fix it. Here are the two classes where the problem is.
Player class:
public class Player{
private String name;
private Card[] hand; // from 2 - 5 cards allowed
private int cardCount,
chips;
public Player()
{
hand = new Card[5];
chips = 5;
cardCount = 0;
}
public Player(String n){
hand = new Card[5];
name = n;
chips = 5;
cardCount = 0;
}
public void acceptACard(Card c){
hand[cardCount] = new Card();
hand[cardCount] = c;
cardCount++;
}
public void showHand(int startCard)
{
for (int i = startCard; i < cardCount; i++){
System.out.print(hand[i] + "\t"); // displays one card from hand
}
}
public int calcScore(){
int cardScore =0;
int total = 0;
boolean hasAce = false;
for(int i=0; i < cardCount; i++){
cardScore = hand[i].getValue();
if (cardScore >=11 && cardScore <=13)
cardScore = 10;
else if (cardScore == 14){
cardScore = 11;
hasAce = true;
}
total += cardScore;}
if (total > 21 && hasAce == true)
total -= 10;
return total;
}
public void incrementChips(){
chips ++;
}
public void decrementChips(){
chips --;
}
public int getChips(){
return chips;
}
}
BlackJack class:
public class BlackJack {
private Player human,
computer;
private Deck deck = new Deck();
Scanner scan = new Scanner(System.in);
public BlackJack(){
human = new Player("");
computer = new Player ("");
}
public void playGame()
{
int cardTotal = 0;
String answer, answer2;
deck.shuffle();
do{
for ( int i = 0; i < 2; i++)
{
human.acceptACard(deck.dealACard());
computer.acceptACard(deck.dealACard());
}
System.out.print(" Human hand: ");
human.showHand(0);
System.out.print("\n Computer hand: ");
computer.showHand(1);
System.out.println("\nThe computers total points: " +
computer.calcScore());
System.out.println("Players total points: " + human.calcScore());
if(human.calcScore() == 21 && computer.calcScore() < 21)
System.out.println("You win");
else if (computer.calcScore() == 21 && human.calcScore() < 21)
System.out.println("Computer wins!");
else if (computer.calcScore() == 21 && human.calcScore() == 21)
System.out.println("Tie!");
else if (human.calcScore() < 21)
do{
System.out.println("\nWould you like to hit or stay? Type hit or" +
" stay.");
answer = scan.nextLine();
if(answer.equals("hit"))
{
dealHand();
human.calcScore();
computer.calcScore();
cardTotal ++;
}
}while(cardTotal < 4 && answer.equals("hit"));
determineWinner();
System.out.println("Would you like to play again? Enter yes or no: ");
answer = scan.nextLine();
}while(answer.equals("yes"));
reportGameStatus();
}
public void dealHand(){
int i = 2; int j =2;
human.acceptACard(deck.dealACard());
System.out.println("New card: ");
human.showHand(i++);
while(computer.calcScore() < 17){
computer.acceptACard(deck.dealACard());
System.out.println();
System.out.println("Computer's new card: ");
computer.showHand(j++);
}
}
public void determineWinner(){
System.out.println("\nThe computers total points: " +
computer.calcScore());
System.out.println("Players total points: " + human.calcScore());
if (computer.calcScore() > human.calcScore() && computer.calcScore()<22){
System.out.println("Computer wins!");
computer.incrementChips();
human.decrementChips();
}
else if (human.calcScore() > computer.calcScore() && human.calcScore()
<22){
System.out.println("You win!!");
human.incrementChips();
computer.decrementChips();
}
else if (human.calcScore() == computer.calcScore() )
System.out.println("Tie!");
else if (human.calcScore() > 21){
System.out.println("You bust! The Computer wins!");
computer.incrementChips();
human.decrementChips();
}
else if (computer.calcScore() > 21){
System.out.println("The Computer busts! You win!");
computer.decrementChips();
human.incrementChips();
}
}
public void reportGameStatus(){
if(computer.getChips() > human.getChips())
System.out.println("Overall winner is the computer!");
else if(human.getChips() > computer.getChips())
System.out.println("You are the overall winner!");
}
}
Any help would be much appreciated.
I think here is your problem:
if(answer.equals("hit"))
{
dealHand();
human.calcScore();
computer.calcScore();
cardTotal ++;
}
Instead of making new Objects you use the old ones and keep their inner state. That means your construktor is not used a second time and therefore your score, hand, chips are not resetted.
How about trying this:
if(answer.equals("hit"))
{
dealHand();
Player human = new Player();
human.calcScore();
Computer computer = new Coputer();
computer.calcScore();
cardTotal ++;
}
Also you have to make a new Deck everytime you start a new game:
Deck deck = new Deck();
Edit:
If you want to keep your chipCount place it in an Object wich will be initialiset in the constructor of your Blackjack class. After that call a function chipcount.setChipcount(chips); if you want to change the chipCount. Obvisoulsly your chipcount-object should have a getter getChipcounts() as well to get the actual chipCount.
It could look like this:
public BlackJack(){
human = new Player("");
computer = new Player ("");
ChipCount chipCount = new Chipcount(0);
}
here is how your object would be:
class ChipCount{
int chipCount;
public ChipCount(int startChips){
this.chipCount = startchips;
}
public void setChips(int chipsToAdd){
this.chipCount = this.chipcount + chipsToAdd;
}
public int getChips(){
return chipCount;
}
}
Before youre asking. Of course you could make two objects (ChipCountPlayer & ChipCountComputer). Also there is the possibility of giving setChips & getChips another argument like:
class ChipCount{
int chipCountPlayer;
int chipCountComp;
public ChipCount(int startChips){
this.chipCountPlayer = startchips;
this.chipCountComp = startchips;
}
public void setChips(int chipsToAdd, String player){
if(player.equals("player")){
this.chipCountPlayer = this.chipcountPlayer + chipsToAdd;
} else if (player.equals("computer")){
this.chipCountComp = this.chipcountComp + chipsToAdd;
}
}
public int getChips(String player){
if(player.equals("player")){
return chipCountPlayer;
} else if (player.equals("computer")){
return chipCountcomp;
}
}
}
that would be the other solution :P
PS: I am not fond of blackjack, does the computer even have chips? Anyway you could replace the comp with another player if you want to further extent your programm :D

Categories