Everything else works fine except I run into an issue of printing out the card the player (if they 'hit' ) as I don't know what card the player draws and which player draws what card, it starts at 8 as the first 7 cards are drawn but I don't know what player gets what and how many. So I tried to have a method to print out the hand of each player but I'm having a LOT of trouble with that could use some help. I want to print the cards the players get in my output. I'll post my Card, Player, and BlackJackGame class as my Dealer class is very similar to player.
Card.java
import java.util.Random;
public class Card
{
private String suit, rank;
private int value;
public Card(String suit, String rank)
{
this.suit = suit;
this.rank = rank;
}
public String getRank()
{
return rank;
}
public int Value()
{
if(rank.equals("2"))
{
value=2;
}
else if(rank.equals("3"))
{
value=3;
}
else if(rank.equals("4"))
{
value=4;
}
else if(rank.equals("5"))
{
value=5;
}
else if(rank.equals("6"))
{
value=6;
}
else if(rank.equals("7"))
{
value=7;
}
else if(rank.equals("8"))
{
value=8;
}
else if(rank.equals("9"))
{
value=9;
}
else if(rank.equals("10"))
{
value=10;
}
else if(rank.equals("A"))
{
Random rand = new Random();
int count = rand.nextInt(1) +1;
if(count == 1)
{
value=11;
}
else
value= 1;
}
else if(rank.equals("Q"))
{
value=10;
}
else if(rank.equals("J"))
{
value=10;
}
else if(rank.equals("K"))
{
value=10;
}
return value;
}
public String toString()
{
return(rank + " of " + suit);
}
}
Player.java
public class Player
{
private int cValue;
private int cCount; //Card count used to count how many 'cards' added
Card[] deck= new Card[52];
private int sum;
public Player()
{
cCount=0;
}
public Card addCard(Card a)
{
deck[cCount] = a;
cCount++;
return a;
}
public int getcCount()
{
return cCount;
}
public int getValue()
{
int total=0;
for(int i=0; i < cCount; i++)
{
total += deck[i].Value();
}
return total;
}
BlackJackGame.java
public class BlackJackGame
{
public static void main(String [] args)
{
Card[] deck = new Card[52];
Player[] player = new Player[3];
int loopcount=0;
String p1result = " ", p2result = " ", p3result = " ", p4result = " ", dresult = " ";
String[] suit = {"Hearts", "Clubs", "Spades", "Diamonds"};
String[] rank = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};
for(int i=0; i<13; i++)
{
for(int x=0; x<4;x++)
{
deck[loopcount] = new Card(suit[x], rank[i]);
loopcount++;
}
}
System.out.println("Shuffling...");
for(int i=0; i< deck.length; i++) //Shuffle
{
Card tmp = deck[i];
int count= (int)(Math.random()* deck.length);
deck[i] = deck[count];
deck[count] = tmp;
}
Player player1 = new Player();
Player player2 = new Player();
Player player3 = new Player();
System.out.println("Welcome to our BlackJackGame!");
System.out.println("Welcome Dealer!");
Dealer dealer = new Dealer();
System.out.println("Let's deal the cards!");
player1.addCard(deck[0]);
player2.addCard(deck[1]);
player3.addCard(deck[2]);
System.out.println("And now the Dealer gets his card...");
dealer.addCard(deck[3]);
System.out.println("Now we get our second cards!");
System.out.println("Okay Dealer, deal out the cards!");
player1.addCard(deck[4]);
player2.addCard(deck[5]);
player3.addCard(deck[6]);
dealer.addCard(deck[7]);
int count =8;
int i=0;
do
{
p1result = "";
p2result = "";
p3result = "";
dresult = "";
int dvalue = dealer.getValue();
int p1value = player1.getValue();
int p2value = player2.getValue();
int p3value = player3.getValue();
while(p1value < 17) //hit
{
player1.addCard(deck[count]);
count++;
p1value = player1.getValue();
}
if(p1value > 21)
{
p1result = "Bust!";
}
if(p1value <21 && p1value >17)//stand
{
}
while(p2value < 17)//hit
{
player2.addCard(deck[count]);
count++;
p2value = player2.getValue();
}
if(p2value > 21) //bust
{
p2result = "Bust!";
}
if(p2value <21 && p2value >17) //stand
{
}
while(p3value < 17) //hit
{
player3.addCard(deck[count]);
count++;
p3value = player3.getValue();
}
if( p3value > 21)
{
p3result = "Bust!";
}
if(p3value <21 && p3value >21) //stand
{
}
while(dvalue < 17)
{
dealer.addCard(deck[count]);
count++;
dvalue = dealer.getValue();
}
if(dvalue > 21) //Bust
{
p1value = player1.getValue();
p2value = player2.getValue();
p3value = player3.getValue();
if(p1value == 21 || p1value <21)
{
p1result = "Win!";
}
if(p2value == 21 || p2value <21)
{
p2result = "Win!";
}
if(p3value == 21 || p3value <21 )
{
p3result = "Win!";
}
}
if(dvalue < 21 && dvalue >= 17) //For Dealer values in between
{
p1value = player1.getValue();
p2value = player2.getValue();
p3value = player3.getValue();
dvalue = dealer.getValue();
if(p1value == dvalue)
{
p1result = "Push!";
}
if(p1value > dvalue)
{
p1result = "Win!";
}
if(p1value < dvalue)
{
p1result = "Lose!";
}
if(p2value == dvalue)
{
p2result = "Push!";
}
if(p2value > dvalue)
{
p2result = "Win!";
}
if(p2value < dvalue)
{
p2result = "Lose!";
}
if(p3value == dvalue)
{
p3result = "Push!";
}
if(p3value > dvalue)
{
p3result = "Win!";
}
if(p3value < dvalue)
{
p3result = "Lose!";
}
}
if(dvalue == 21 )
{
p1value = player1.getValue();
p2value = player2.getValue();
p3value = player3.getValue();
dvalue = dealer.getValue();
if(p1value == dvalue)
{
p1result = "Push!";
}
if(p1value < dvalue || p1value > dvalue)
{
p1result = "Lose!";
}
if(p2value == dvalue)
{
p2result = "Push!";
}
if(p2value < dvalue || p2value > dvalue)
{
p2result = "Lose!";
}
if(p3value == dvalue)
{
p3result = "Push!";
}
if(p3value < dvalue || p3value > dvalue)
{
p3result = "Lose!";
}
}
System.out.println("The BlackJack Game is Complete: ");
System.out.println("Results: ");
System.out.println("Dealer: " +deck[3] + " " + deck[7] + " " +("total of " +dealer.getValue() ));
System.out.println("Player1: " +deck[0] + " " + deck[4] + " "+("total of " +player1.getValue() )+ ": " +p1result);
System.out.println("Player2: " +deck[1] + " " + deck[5] + " "+("total of " +player2.getValue() )+ ": " +p2result);
System.out.println("Player3: " +deck[2] + " " + deck[6] + " "+("total of " +player3.getValue() )+ ": " +p3result);
i++;
}
while(i <1);
}
}
Example Output:
BlackJack Game is Complete!
Results!
Dealer : 6 of Clubs 8 of Spades total 17
Player1: 2 of Clubs 2 of Spades total 16 Lose!
Player2: Q of Hearts Q of Spades total 20 Win!
Player3: A of Spades 6 of Hearts total 17 Push!
// The Problem is when the cards are printed , I print out the first two cards each player has and the dealer which are known. The problem I run into is if the player or dealer 'hits' as you can see with Player 1 I don't know which cards are hit/ and which player has them and was wondering how to have a method in the Player class that would print the hand of each player including the dealer and the cards they have for my output. That is what I need help with. Everything else works fine.
First, I would suggest using a switch statement instead of all those else ifs for rank, it'll be a lot neater :)
Second, in Blackjack an Ace doesn't have a "random" value of either 1 or 11; it is an 11 unless it being an 11 makes the player bust.
Third, I would consider using a list for the deck. Then all you need to do is "shuffle" the list and when you deal a card, remove the top card from the list and add it to the player's hand. (see Collections.Shuffle)
Now to address the initial question, you should have a List hand in the player class. Then add an extension method to the player class to print the hand; it should look something like this:
public void printHand() {
ListIterator<Card> it = hand.listIterator();
if(it.hasNext())
System.out.print(it.next());
while(it.hasNext())
System.out.print(", " + it.next());
System.out.println();
}
Related
i have a exercice to do in Java. I need to create a World Cup tournament and the restriction is that the program will restart until my favourite team win. However, if my team didn't win after 20 times, the program stop
The problem is when I try to put the second restriction (20 times max) with a for after the while (true), I always get an infinite loop.
//Q1
String[] teams16 = {"Uruguay", "Portugal", "France", "Argentina", "Brazil", "Mexico",
"Belgium", "Japan", "Spain", "Russia", "Croatia", "Denmark", "Sweden", "Switzerland",
"Colombia", "England"};
//data
Scanner keyboard = new Scanner(System.in);
Random result = new Random();
System.out.print("Enter your favourite team: ");
String team = keyboard.nextLine();
boolean teamwc = false;
// choice of the favourite team
for (int i = 0 ; i < 16 ; i++ ) {
if (teams16[i].equalsIgnoreCase(team)) {
teamwc = true;
}
}
if(teamwc == false) {
System.out.println("Your team is not in the Round of 16 ");
}
// the tournament begins (ROUND OF 16)
while (true) {
if (teamwc == true) {
int z = 0;
String[] winnerof16 = new String[8];
int a = 0;
System.out.print("ROUND OF 16:");
for (int i = 0; i < 16 ; i+=2) {
int score1 = result.nextInt(5);
int score2 = result.nextInt(5);
if (score1 > score2) {
winnerof16 [a] = teams16[i];
}
else if (score1 < score2) {
winnerof16[a] = teams16[i+1];
} else if (score1 == score2) {
Random overtime = new Random();
int ot = overtime.nextInt(2);
if (ot == 0) {
score1++;
winnerof16[a] = teams16[i];
} else if (ot == 1) {
score2++;
winnerof16[a]=teams16[i+1];
}
}
System.out.print("["+teams16[i] +"]"+ " " + score1+":"+score2 + " " + "["+teams16[i+1]+"]" + " ");
a++;
}
System.out.println();
String[] winnerof8 = new String[4];
int b = 0;
System.out.print("QUARTER-FINALS:");
for (int k = 0 ; k < 8 ; k+=2) {
int score3 = result.nextInt(5);
int score4 = result.nextInt(5);
if (score3 > score4) {
winnerof8[b]=winnerof16[k];
}
else if (score3 < score4) {
winnerof8[b] = winnerof16[k+1];
} else if (score3 == score4) {
Random overtime2 = new Random();
int ot2 = overtime2.nextInt(2);
if (ot2 == 0) {
score3++;
winnerof8[b]=winnerof16[k];
} else if (ot2 == 1) {
score4++;
winnerof8[b]=winnerof16[k+1];
}
}
System.out.print("["+winnerof16[k] +"]"+ " " + score3+":"+score4 + " " + "["+winnerof16[k+1]+"]" + " ");
b++;
}
System.out.println();
String[] winnerof4 = new String[2];
int c = 0;
System.out.print("SEMI-FINALS:");
for (int l = 0 ; l < 4 ; l+=2) {
int score5 = result.nextInt(5);
int score6 = result.nextInt(5);
if (score5 > score6) {
winnerof4[c]=winnerof8[l];
}
else if (score5 < score6) {
winnerof4[c] = winnerof8[l+1];
} else if (score5 == score6) {
Random overtime3 = new Random();
int ot3 = overtime3.nextInt(2);
if (ot3 == 0) {
score5++;
winnerof4[c]=winnerof8[l];
} else if (ot3 == 1) {
score6++;
winnerof4[c]=winnerof8[l+1];
}
}
System.out.print("["+winnerof8[l] +"]"+ " " + score5+":"+score6 + " " + "["+winnerof8[l+1]+"]" + " ");
c++;
}
System.out.println();
String[] winnerof2 = new String[1];
int d = 0;
System.out.print("FINALS:");
for (int m = 0 ; m < 2 ; m+=2) {
int score7 = result.nextInt(5);
int score8 = result.nextInt(5);
if (score7 > score8) {
winnerof2[d]=winnerof4[m];
}
else if (score7 < score8) {
winnerof2[d] = winnerof4[m+1];
} else if (score7 == score8) {
Random overtime4 = new Random();
int ot4 = overtime4.nextInt(2);
if (ot4 == 0) {
score7++;
winnerof2[d]=winnerof4[m];
} else if (ot4 == 1) {
score8++;
winnerof2[d]=winnerof4[m+1];
}
}
System.out.print("["+winnerof4[m] +"]"+ " " + score7+":"+score8 + " " + "["+winnerof4[m+1]+"]" + " ");
System.out.println();
}
System.out.println("Tournament: " + z + " The WINNER is: " + winnerof2[d]);
z++;
if (winnerof2[d].equalsIgnoreCase(team)) {
break;
}
}
}
}
}
This is my code before I put the second restriction.
Is there a problem with my code ? How can I put the second restriction ? Thank you
The infinite loop is due to this 2:
while (true) { // it will quit while loop only when an exception raised
if (teamwc == true) { // after this you nowhere assign teamwc == false therefore it is always true
instead of direct assigning True to while loop, use a boolean variable or a condition to quit somewhere:
t = true
while(t):
OR
while n>0:
I have a Java game in which you play Blackjack, and I use a Scanner to take input for things like "hit" and "stay." When I run it, the Windows wait cursor shows up and doesn't go away until I close the program. I tried to use Scanner's close() method, but that throws an exception.
here's the code:
import java.util.Scanner;
import java.util.ArrayList;
public class CardGame {
public static ArrayList<Card> dealIn(ArrayList<Card> hand) {
Card a = new Card();
Card b = new Card();
hand.add(a);
while (hand.size() < 2) {
if (!b.equals(a)) {
hand.add(b);
} else
dealIn(hand);
}
return hand;
}
public static int calcScore(ArrayList<Card> hand) {
int sum = 0;
int aces = 0;
for (Card c : hand) {
if (c.getCardValue().getFace().equals("A")) {
aces++;
} else {
sum += c.getCardValue().getNumeric();
}
}
while (aces > 0) {
aces--;
if (sum <= 10) {
sum += 11;
} else {
sum += 1;
}
}
return sum;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Welcome to Blackjack!\n");
ArrayList<Card> playerhand = new ArrayList<Card>();
ArrayList<Card> dealerhand = new ArrayList<Card>();
dealIn(playerhand);
for (int i = 0; i < 2; i++) {
Card a = new Card();
if ((!playerhand.contains(a)) && (!dealerhand.contains(a))) {
dealerhand.add(a);
}
}
// System.out.println("DEALER HAND: [hidden]" + " and " +
// dealerhand.get(1));
System.out.println("TEST DEALER HAND: " + dealerhand);
System.out.println("Your hand: " + playerhand);
while (!isBusted(playerhand)) {
System.out.println("Your score is " + calcScore(playerhand) + ". Hit or stay?");
String hOrS = in.nextLine();
if (hOrS.equalsIgnoreCase("hit")) {
hit(playerhand);
System.out.println(playerhand);
if (isBusted(playerhand)) {
System.out.println("Your score is " + calcScore(playerhand) + "! YOU LOSE");
break;
}
// System.out.println(playerhand);
}
if (hOrS.equalsIgnoreCase("stay")) {
while (calcScore(dealerhand) <= 17) {
Card n = new Card();
if (!dealerhand.contains(n)) {
dealerhand.add(n);
// System.out.println(dealerhand);
}
}
}
if (isBusted(dealerhand) || (!isBusted(playerhand) && (calcScore(playerhand) > calcScore(dealerhand)))) {
System.out.println("DEALER HAND: " + dealerhand);
System.out.println("YOUR HAND: " + playerhand);
System.out.println("YOU WIN");
// break;
} else {
System.out.println(dealerhand);
System.out.println("YOU LOSE");
break;
}
}
}
}
Is it possible to fix this?
I have an assignment in my Java 1 class. It is to create a Black-Jack Game with a Command Line Interface.
However my book only has one page devoted to Command-Line Arguments. This project is an extra credit thing so I guess we are supposed to look elsewhere to find this info. I've finished my program. It runs and works. I'm sure my Code will look clunky to anyone that has been doing this for a while.
Can anyone enlighten me on this topic, the topic being Command Line Interface?
Here is my code:
package blackjack;
import java.util.Scanner;
public class BlackJack {
public static void main(String[] args) {
boolean play = true;
while (play == true) {
Game game1 = new Game();
Scanner keyboard = new Scanner(System.in);
Deck deck1 = new Deck();
deck1.createDeck();
deck1.shuffleDeck(deck1.getDeck1());
game1.setDeck(deck1.getDeck2());
System.out.println("Welcome to BLACKJACK!");
System.out.println("------------------------");
System.out.println("Enter 1 to Start: ");
int start = keyboard.nextInt();
if (start == 1) {
deck1.createDeck();
System.out.println("Shuffling Deck");
deck1.shuffleDeck(deck1.getDeck1());
System.out.println("Shuffling Deck");
System.out.println("Shuffling Deck");
System.out.println("Shuffling Deck");
System.out.println("Shuffling Deck");
System.out.println("Shuffling Deck");
System.out.println("Lets Play!");
game1.dealOneCardPlayer(game1.getCardCounter());
game1.setCardCounter(game1.getCardCounter() + 1);
game1.dealOneCardPlayer(game1.getCardCounter());
game1.setCardCounter(game1.getCardCounter() + 1);
game1.dealoneCardDealer(game1.getCardCounter());
game1.setCardCounter(game1.getCardCounter() + 1);
game1.dealoneCardDealer(game1.getCardCounter());
game1.setCardCounter(game1.getCardCounter() + 1);
game1.check();
}
while (game1.isEndGame() == false) {
game1.displayPlayer();
game1.turnLoop();
}
if (game1.isEndGame() == true) {
System.out.println("FINAL HANDS");
System.out.println("");
game1.displayPlayer();
System.out.println("");
System.out.println("Do you want to Play again? 1 = yes or 2 = no");
int answer = keyboard.nextInt();
if (answer == 1) {
play = true;
} else if (answer == 2) {
System.out.println("Fine, Go do something else.");
play = false;
}
} else {
System.out.println("Why won't you play with me billy?");
}
}
}
}
public class Card {
private int value;
private String suit;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Card(int value, String suit) {
this.value = value;
this.suit = suit;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public String getSuit() {
return suit;
}
public void setSuit(String suit) {
this.suit = suit;
}
public class Deck {
private Card[] Deck1 = new Card[52];
private Card[] Deck2 = new Card[52];
public Card[] getDeck2() {
return Deck2;
}
// this is important... I think.
public void setDeck2(Card[] Deck2) {
this.Deck2 = Deck2;
}
public Card[] getDeck1() {
return Deck1;
}
public void setDeck1(Card[] Deck1) {
this.Deck1 = Deck1;
}
public Card getOneCard2(int i) {
System.out.println("your drew the " + Deck2[i].getName() + " of " + Deck2[i].getSuit());
return Deck1[2];
}
public Card getOneCard(int i) {
System.out.println("your drew the " + Deck1[i].getName() + " of " + Deck1[i].getSuit());
return Deck1[i];
}
public void setDeck(Card Card, int position) {
Deck1[position] = Card;
}
public void shuffleDeck(Card[] Deck){
for(int i = 0; i < 52 ; i++){
Random rand = new Random();
int position = rand.nextInt((51 - 0) + 1);
Deck2[i] = Deck1[position];
}
}
public void printDeck1(){
for(int i = 0; i < 52 ; i++){
System.out.println(Deck1[i].getName() + " of " + Deck1[i].getSuit() + " In Game Value: " + Deck1[i].getValue() );
}
}
public void createDeck(){
int B;
int value;
String suit;
int deckPosition = 0;
for( B = 1 ; B <= 4 ; B++){
if( B == 1){
suit = "Spades";
}
else if (B == 2){
suit = "Hearts";
}
else if (B == 3){
suit = "Clubs";
}
else {
suit = "Diamonds";
}
for (int i = 1; i <= 13; i++){
value = i;
Card card = new Card(value, suit);
Deck1[deckPosition] = card;
if(Deck1[deckPosition].getValue() == 11){
Deck1[deckPosition].setName("Jack");
Deck1[deckPosition].setValue(10);
}
else if(Deck1[deckPosition].getValue() == 12){
Deck1[deckPosition].setName("Queen");
Deck1[deckPosition].setValue(10);
}
else if(Deck1[deckPosition].getValue() == 13){
Deck1[deckPosition].setName("King");
Deck1[deckPosition].setValue(10);
}
else if(Deck1[deckPosition].getValue() == 1){
Deck1[deckPosition].setName("Ace");
Deck1[deckPosition].setValue(11);
}
else{
Deck1[deckPosition].setName(Integer.toString(Deck1[deckPosition].getValue()));
}
deckPosition++;
}
}
}
}
public class Game {
private Card[] Deck = new Card[52];
private ArrayList<Card> playerHand = new ArrayList<>();
private ArrayList<Card> dealerHand = new ArrayList<>();
private int pValue = 0;
private int dValue = 0;
private int cardCounter = 0;
private boolean endGame = false;
public boolean isEndGame() {
return endGame;
}
public int getCardCounter() {
return cardCounter;
}
public void setCardCounter(int cardCounter) {
this.cardCounter = cardCounter;
}
public int getpValue() {
return pValue;
}
public int getdValue() {
return dValue;
}
public ArrayList<Card> getPlayerHand() {
return playerHand;
}
public ArrayList<Card> getDealerHand() {
return dealerHand;
}
public void dealOneCardPlayer(int i) {
playerHand.add(Deck[i]);
}
public void dealoneCardDealer(int i) {
dealerHand.add(Deck[i]);
}
public void setDealerHand(ArrayList<Card> dealerHand) {
this.dealerHand = dealerHand;
}
public void setDeck(Card[] Deck) {
this.Deck = Deck;
}
public void displayPlayer(){
pValue = 0;
dValue = 0;
System.out.println("---------------------------------------------");
System.out.println("DEALER HAND");
for( int i = 0 ; i < dealerHand.size() ; i++){
System.out.println(dealerHand.get(i).getName() + " of " + dealerHand.get(i).getSuit());
dValue = dValue + dealerHand.get(i).getValue();
}
System.out.println("Dealer Hand Value = " + dValue);
System.out.println("---------------------------------------------");
System.out.println("PLAYER HAND");
for( int i = 0 ; i < playerHand.size() ; i++){
System.out.println(playerHand.get(i).getName() + " of " + playerHand.get(i).getSuit());
pValue = pValue + playerHand.get(i).getValue();
}
System.out.println("Player Hand Value = " + pValue);
System.out.println("");
System.out.println("");
}
public void turnLoop() {
Scanner keyboard = new Scanner(System.in);
System.out.println("Do you want to (H)it, (S)tay, or (C)all?");
String hitstaycall = keyboard.nextLine();
if("h".equals(hitstaycall.toLowerCase())){
playerHand.add(Deck[cardCounter]);
pValue = pValue + Deck[cardCounter].getValue();
cardCounter++;
if ( dValue < 16 ){
dealerHand.add(Deck[cardCounter]);
dValue = dValue + Deck[cardCounter].getValue();
cardCounter++;
}
dValue = 0;
pValue = 0;
for( int i = 0 ; i < dealerHand.size() ; i++){
dValue = dValue + dealerHand.get(i).getValue();
}
for( int i = 0 ; i < playerHand.size() ; i++){
pValue = pValue + playerHand.get(i).getValue();
}
if ( dValue > 21 && pValue > 21){
System.out.println("You Lose. Dealer doesn't lose because you bust first. Its the House rules...");
endGame = true;
}
if (pValue == 21 || dValue == 21 ){
System.out.println("BLACKJACK!");
endGame = true;
}
if ( dValue > 21 && pValue < 22){
System.out.println("Dealer BUST. You Win");
endGame = true;
}
if ( pValue > 21 && dValue <22){
System.out.println("You BUST. Dealer Win");
endGame = true;
}
}
else if("s".equals(hitstaycall.toLowerCase())){
if ( dValue < 16 ){
dealerHand.add(Deck[cardCounter]);
dValue = dValue + Deck[cardCounter].getValue();
cardCounter++;
}
dValue = 0;
pValue = 0;
for( int i = 0 ; i < dealerHand.size() ; i++){
dValue = dValue + dealerHand.get(i).getValue();
}
for( int i = 0 ; i < playerHand.size() ; i++){
pValue = pValue + playerHand.get(i).getValue();
}
if ( dValue > 21 && pValue > 21){
System.out.println("You Lose. Dealer doesn't lose because you bust first. Its the House rules...");
endGame = true;
}
if (pValue == 21 || dValue == 21 ){
System.out.println("BLACKJACK!");
endGame = true;
}
if ( dValue > 21 && pValue < 22){
System.out.println("Dealer BUST. You Win");
endGame = true;
}
if ( pValue > 21 && dValue <22){
System.out.println("You BUST. Dealer Win");
endGame = true;
}
}
else if("c".equals(hitstaycall.toLowerCase())){
dValue = 0;
pValue = 0;
for( int i = 0 ; i < dealerHand.size() ; i++){
dValue = dValue + dealerHand.get(i).getValue();
}
for( int i = 0 ; i < playerHand.size() ; i++){
pValue = pValue + playerHand.get(i).getValue();
}
if ( dValue < pValue && pValue < 21){
dealerHand.add(Deck[cardCounter]);
dValue = dValue + Deck[cardCounter].getValue();
cardCounter++;
}
if ( pValue > dValue && pValue < 22){
System.out.print("YOU WIN!!!!");
endGame = true;
}
if ( dValue > pValue && dValue < 22){
System.out.println("Dealer Wins!");
endGame = true;
}
if ( dValue > 21 && pValue > 21){
System.out.println("You Lose. Dealer doesn't lose because you bust first. Its the House rules...");
endGame = true;
}
if (pValue == 21 || dValue == 21 ){
System.out.println("BLACKJACK!");
endGame = true;
}
if ( dValue > 21 && pValue < 22){
System.out.println("Dealer BUST. You Win");
endGame = true;
}
if ( pValue > 21 && dValue <22){
System.out.println("You BUST. Dealer Win");
endGame = true;
}
}
else { System.out.println("Hey you.");
}
}
public void check(){
dValue = 0;
pValue = 0;
for( int i = 0 ; i < dealerHand.size() ; i++){
dValue = dValue + dealerHand.get(i).getValue();
}
for( int i = 0 ; i < playerHand.size() ; i++){
pValue = pValue + playerHand.get(i).getValue();
}
if ( dValue > 21 && pValue > 21){
System.out.println("You Lose. Dealer doesn't lose because you bust first. Its the House rules...");
endGame = true;
}
if (pValue == 21 || dValue == 21 ){
System.out.println("BLACKJACK!");
endGame = true;
}
if ( dValue > 21 && pValue < 22){
System.out.println("Dealer BUST. You Win");
endGame = true;
}
if ( pValue > 21 && dValue <22){
System.out.println("You BUST. Dealer Win");
endGame = true;
}
}
}
I think the meaning of "command line interface" here is a mixture of command line arguments and reading from System.in and writing to System.out. ie the user can interface with the program through a command line terminal or window.
Furthermore it probably implies that the user issues commands through that window that are interpreted by the program after reading from System.in.
I guess the term "command" here can be interpreted however you like but you probably have some idea what your instructor would expect.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Why does the array "prevScore" not print the value "points"?
I want it to print out points for prevScore [0], and then null 0
This is the array, after the // is something I thought I could use.
int [] prevScore = new int[10]; //{ 0 };
String [] prevScoreName = new String[10]; //{"John Doe"};
public static int[] scoreChange (int prevScore[], int points)
{
for(int i = 9; i > 0; i--){
prevScore[i] = prevScore[i-1];
}
prevScore[0]= points;
return prevScore;
}
I dont know if the print of prevScore is needed.
//a method that prints high scores
public static void printScores (int prevScore[], String prevScoreName[])
{
for (int i = 10; i > 0; i--){
System.out.println(prevScore[i] + " " + prevScoreName[i]);
}
}
Here is the rest of my program I am working on... currently only i get one, 0 John Doe.
public class Main
{
static BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); // user input
public static void main (String args[]) throws IOException
{
int press = 0;
do {
int menuchoice = 0;
int [] prevScore = new int[] { 0 };
String [] prevScoreName = new String[] {"John Doe"};
System.out.println("Menu choice: 1 to start game, 2 print instructions,"
+ "3 prev score");
Scanner input = new Scanner(System.in);
int userinput = Integer.parseInt(input.next());
int points;
menuchoice = userinput;
if (menuchoice == 1){
points = startGame();
String newName = endGame(points);
prevScore = scoreChange(prevScore,points);
prevScoreName = nameChange(prevScoreName, newName);
}
if (menuchoice == 2){
printInstructions();
}
if(menuchoice == 3) {
printScores(prevScore, prevScoreName); }
if (menuchoice != 1 && menuchoice != 2 && menuchoice !=3 ) {
System.out.println("ERROR"); }
} while (press !=4 );
}
//a method that initializes a new game
public static int startGame () throws IOException //a method that initializes a new game
{
int lives = 3;
int points = 0;
System.out.println("Good Luck!");
do {
System.out.println("Points: " + points);
System.out.println("Lives: " + lives);
int correct = displayNewQuestion();
Scanner userinput = new Scanner(System.in);
int userAnswer = Integer.parseInt(userinput.nextLine());
if (userAnswer == correct){
points ++;
System.out.println("Correct");
}
if (userAnswer != correct ){
lives --;
System.out.println("Incorrect");
}
} while (lives > 0);
return points;
}
public static String endGame (int points) throws IOException // a method that tells the user the game is over
{
System.out.println("GAME OVER");
Scanner nameinput = new Scanner(System.in);
System.out.println("Please enter your name for the score charts!");
String newName = nameinput.next();
return newName;
}
public static int[] scoreChange (int prevScore[], int points)
{
// for(int i = 0; i < 10; i--){
// prevScore[i] = prevScore[i-1];
// }
// prevScore[1]= prevScore[0];
prevScore[0]= points;
return prevScore;
}
public static String[] nameChange (String prevScoreName[], String newName)
{
/*for(int i = 0; i < 10; i++){
prevScoreName[i] = prevScoreName[i-1];
}
//prevScoreName[1] = prevScoreName[0];*/
prevScoreName[0] = newName;
return prevScoreName;
}
public static void printInstructions () //a method that will print the instructions to the user
{
System.out.println("Instructions");
}
public static void printScores (int prevScore[], String prevScoreName[]) //a method that prints high scores
{
/* for (int i = 0; i < 10; i--){
System.out.println(prevScore[i] + " " + prevScoreName[i]);
}*/
for (int i = prevScore.length; i > 0; i--){
System.out.println(prevScore[i-1] + " " + prevScoreName[i-1]);
}
}
public static int displayNewQuestion () // a method that displays a random arithmetic question
{
int correctAnswer = 0;
int num1 = randInt (12,-12);
int num2 = randInt(12, -12);
Random rand = new Random();
int operator = rand.nextInt((4 - 1) + 1) + 1;
if (operator == 1)
{
System.out.println(num1 + " + " + num2);
correctAnswer = num1 + num2;
}
if (operator == 2)
{
System.out.println(num1 + " - " + num2);
correctAnswer= num1 - num2;
}
if (operator == 3)
{
System.out.println(num1 + " x " + num2);
correctAnswer= num1*num2;
}
if (operator == 4)
{
if (num2 == 0) {
System.out.println(num1*num2 + " / " + num1);
correctAnswer= ((num1*num2)/num1);
}
if (num2 != 0) {
System.out.println(num1*num2 + " / " + num2);
correctAnswer= ((num1*num2)/num2);
}
}
return correctAnswer;
}
public static int randInt(int max , int min) {
Random rand = new Random();
min = -12;
max = 12;
int randnum = rand.nextInt((max - min) + 1) + min;
return randnum;
}
}
Use this loop:
for (int i = prevScore.length; i > 0; i--){
System.out.println(prevScore[i-1] + " " + prevScoreName[i-1]);
}
I think it should solve your problem.
Update
based on your updated program. Move the following code above the start of the 'do' loop.
int [] prevScore = new int[] { 0 };
String [] prevScoreName = new String[] {"John Doe"};
That is you are moving these lines out of the loop. It should work now.
That is the start of your 'main' method should look something like this:
public static void main(String args[]) throws IOException {
int press = 0;
int[] prevScore = new int[] { 0 };
String[] prevScoreName = new String[] { "John Doe" };
do {
int menuchoice = 0;
System.out.println("Menu choice: 1 to start game, 2 print instructions," + "3 prev score");
Your printScore() method is trying to access element [10] of an array whose index range is 0 - 9, and is never accessing element [0]. You may want to print the most recent score first:
for (int i = 0; i < 10; i++) {
Or conversely, to print the most recent score last:
for (int i = 9; i >= 0; i--) {
Thank you so much! It Works! The only problem still is that the scorelist prints backwards.
public class Main
{
static BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); // user input
public static void main (String args[]) throws IOException
{
int press = 0;
int[] prevScore = new int[10];
String[] prevScoreName = new String[10];
do {
int menuchoice = 0;
System.out.println("Menu choice: 1 to start game, 2 print instructions,"
+ "3 prev score");
Scanner input = new Scanner(System.in);
int userinput = Integer.parseInt(input.next());
int points;
menuchoice = userinput;
if (menuchoice == 1) {
points = startGame();
String newName = endGame(points);
prevScore = scoreChange(prevScore,points);
prevScoreName = nameChange(prevScoreName, newName);
}
if (menuchoice == 2) {
printInstructions();
}
if(menuchoice == 3) {
printScores(prevScore, prevScoreName);
}
if (menuchoice != 1 && menuchoice != 2 && menuchoice !=3 ) {
System.out.println("ERROR");
}
} while (press !=4 );
}
//a method that initializes a new game
public static int startGame () throws IOException //a method that initializes a new game
{
int lives = 3;
int points = 0;
System.out.println("Good Luck!");
do {
System.out.println("Points: " + points);
System.out.println("Lives: " + lives);
int correct = displayNewQuestion();
Scanner userinput = new Scanner(System.in);
int userAnswer = Integer.parseInt(userinput.nextLine());
if (userAnswer == correct) {
points ++;
System.out.println("Correct");
}
if (userAnswer != correct ) {
lives --;
System.out.println("Incorrect");
}
} while (lives > 0);
return points;
}
public static String endGame (int points) throws IOException // a method that tells the user the game is over
{
System.out.println("GAME OVER");
Scanner nameinput = new Scanner(System.in);
System.out.println("Please enter your name for the score charts!");
String newName = nameinput.next();
return newName;
}
public static int[] scoreChange (int prevScore[], int points)
{
// for(int i = 0; i < 10; i--){
// prevScore[i] = prevScore[i-1];
// }
// prevScore[1]= prevScore[0];
prevScore[0]= points;
return prevScore;
}
public static String[] nameChange (String prevScoreName[], String newName)
{
/*for(int i = 0; i < 10; i++){
prevScoreName[i] = prevScoreName[i-1];
}
//prevScoreName[1] = prevScoreName[0];*/
prevScoreName[0] = newName;
return prevScoreName;
}
public static void printInstructions () //a method that will print the instructions to the user
{
System.out.println("Instructions");
}
public static void printScores (int prevScore[], String prevScoreName[]) //a method that prints high scores
{
/* for (int i = 0; i < 10; i--){
System.out.println(prevScore[i] + " " + prevScoreName[i]);
}*/
System.out.println("Scores: ");
for (int i = prevScore.length; i > 0; i--){
System.out.println(prevScore[i-1] + " " + prevScoreName[i-1]);
}
}
public static int displayNewQuestion () // a method that displays a random arithmetic question
{
int correctAnswer = 0;
int num1 = randInt (12,-12);
int num2 = randInt(12, -12);
Random rand = new Random();
int operator = rand.nextInt((4 - 1) + 1) + 1;
if (operator == 1)
{
System.out.println(num1 + " + " + num2);
correctAnswer = num1 + num2;
}
if (operator == 2)
{
System.out.println(num1 + " - " + num2);
correctAnswer= num1 - num2;
}
if (operator == 3)
{
System.out.println(num1 + " x " + num2);
correctAnswer= num1*num2;
}
if (operator == 4)
{
if (num2 == 0) {
System.out.println(num1*num2 + " / " + num1);
correctAnswer= ((num1*num2)/num1);
}
if (num2 != 0) {
System.out.println(num1*num2 + " / " + num2);
correctAnswer= ((num1*num2)/num2);
}
}
return correctAnswer;
}
public static int randInt(int max , int min) {
Random rand = new Random();
min = -12;
max = 12;
int randnum = rand.nextInt((max - min) + 1) + min;
return randnum;
}
}
I created this program in my quest to learn Java but every time I run it I get the same cards over and over again. I can't really find the problem, so why aren't my cards random? I don't really get what I'm missing, is my shuffle method incorrect?
package blackjack;
import java.util.Scanner;
public class BlackJack {
public static void main(String[] args) {
System.out.println("Are you ready to play BlackJack?");
System.out.println();
playBlackjack();
System.out.println("Thanks for playing!");
}
static boolean playBlackjack() {
Deck deck;
Hand dealerHand;
Hand playerHand;
deck = new Deck();
dealerHand = new Hand();
playerHand = new Hand();
dealerHand.addCard( deck.dealCard() );
playerHand.addCard( deck.dealCard() );
dealerHand.addCard( deck.dealCard() );
playerHand.addCard( deck.dealCard() );
System.out.println();
if (dealerHand.getBlackjackValue() == 21) {
System.out.println("The dealer have the " + dealerHand.getCard(0)
+ " and the " + dealerHand.getCard(1) + ".");
System.out.println("You have the " + playerHand.getCard(0)
+ " and the " + playerHand.getCard(1) + ".");
System.out.println();
System.out.println("The dealer has Blackjack! The dealer wins!");
return false;
}
if (playerHand.getBlackjackValue() == 21) {
System.out.println("Dealer has the " + dealerHand.getCard(0)
+ " and the " + dealerHand.getCard(1) + ".");
System.out.println("User has the " + playerHand.getCard(0)
+ " and the " + playerHand.getCard(1) + ".");
System.out.println();
System.out.println("You have Blackjack. You win.");
return true;
}
while (true) {
// User decides whether to hit or stand
System.out.println();
System.out.println();
System.out.println("Your cards are:");
for ( int i = 0; i < playerHand.getCardCount(); i++ )
System.out.println(" " + playerHand.getCard(i));
System.out.println("The total of your hand is " + playerHand.getBlackjackValue());
System.out.println();
System.out.println("The dealer is showing the " + dealerHand.getCard(0));
System.out.println();
System.out.println("Do you hit(type 0) or stand(type 1)? ");
Scanner input = new Scanner(System.in);
int choice = input.nextInt();
if (choice != 0 && choice != 1){
System.out.println("0 or 1 must be inputted to continue ");}
while (choice != 0 && choice != 1);
if ( choice == 1 ) {
break;
}
else {
Card newCard = deck.dealCard();
playerHand.addCard(newCard);
System.out.println();
System.out.println("You hits and your card is the " + newCard);
System.out.println("The total of the hand is now " + playerHand.getBlackjackValue());
if (playerHand.getBlackjackValue() > 21) {
System.out.println();
System.out.println("Fool of a Took! You went over 21 and busted!");
return false;
}
}
}
//User has stood at this point. Poor fool
System.out.println();
System.out.println("You stand. Wouldn't it be nice to sit sometime?");
System.out.println("The dealer's cards are "+ dealerHand.getCard(0) + " and the " + dealerHand.getCard(1));
while (dealerHand.getBlackjackValue() <= 16) {
Card newCard = deck.dealCard();
System.out.println("The dealer hits and gets the " + newCard);
dealerHand.addCard(newCard);
if (dealerHand.getBlackjackValue() > 21) {
System.out.println();
System.out.println("The dealer busted! You win!");
return true;
}
}
System.out.println("The dealer's total is " + dealerHand.getBlackjackValue());
System.out.println();
if (playerHand.getBlackjackValue() == dealerHand.getBlackjackValue()) {
System.out.println("The house always wins on a tie. You lose :(");
return false;
}
else if (dealerHand.getBlackjackValue() >= playerHand.getBlackjackValue()) {
System.out.println("The dealer wins as he has " + dealerHand.getBlackjackValue()
+ " points to your " + playerHand.getBlackjackValue() + "!");
return false;
}
else {
System.out.println("You win because you had " + playerHand.getBlackjackValue()
+ " points while the dealer only had " + dealerHand.getBlackjackValue() + "!");
return true;
}
}
}
package blackjack;
public class Card {
private int suit;
private int rank;
public final static int SPADES = 0, // Codes for the 4 suits.
HEARTS = 1,
DIAMONDS = 2,
CLUBS = 3;
public final static int ACE = 1,
JACK = 11,
QUEEN = 12,
KING = 13;
public Card(int cRank, int cSuit) {
rank = cRank;
suit = cSuit;
}
public int getSuit() {
return suit;
}
public int getRank() {
return rank;
}
public String getSuitString() {
// Return a String representing the card's suit.
// (If the card's suit is invalid, "??" is returned.)
switch ( suit ) {
case SPADES: return "Spades";
case HEARTS: return "Hearts";
case DIAMONDS: return "Diamonds";
case CLUBS: return "Clubs";
default: return "I don't even know";
}
}
public String getRankString() {
switch ( rank ) {
case 1: return "Ace";
case 2: return "2";
case 3: return "3";
case 4: return "4";
case 5: return "5";
case 6: return "6";
case 7: return "7";
case 8: return "8";
case 9: return "9";
case 10: return "10";
case 11: return "Jack";
case 12: return "Queen";
case 13: return "King";
default: return "This is impossible!";
}
}
#Override
public String toString() {
return getRankString() + " of " + getSuitString();
}
}
package blackjack;
public class Deck {
private Card[] deck;
private int cardsUsed;
public Deck() {
deck = new Card[52];
int l = 0;
for ( int suit = 0; suit <= 3; suit++ ) {
for ( int value = 1; value <= 13; value++ ) {
deck[l] = new Card(value,suit);
l++;
}
}
cardsUsed = 0;
}
public void shuffle() {
for ( int i = 51; i > 0; i-- ) {
int rand = (int)(Math.random()*(i+1));
Card temp = deck[i];
deck[i] = deck[rand];
deck[rand] = temp;
}
cardsUsed = 0;
}
public int cardsLeft() {
return 52 - cardsUsed;
}
public Card dealCard() {
if (cardsUsed == 52){
shuffle();}
cardsUsed++;
return deck[cardsUsed - 1];
}
}
package blackjack;
import java.util.*;
public class Hand {
private ArrayList hand;
public Hand() {
hand = new ArrayList();
}
public void clear() {
hand.clear();
}
public void addCard(Card c) {
if (c != null){
hand.add(c);
}
}
public void removeCard(Card c) {
hand.remove(c);
}
public void removeCard(int location) {
if (location >= 0 && location < hand.size()){
hand.remove(location);
}
}
public int getCardCount() {
return hand.size();
}
public Card getCard(int location) {
if (location >= 0 && location < hand.size()){
return (Card)hand.get(location);}
else{
return null;
}
}
public void sortBySuit() {
ArrayList newHand = new ArrayList();
while (hand.size() > 0) {
int pos = 0;
Card c = (Card)hand.get(0);
for (int i = 1; i < hand.size(); i++) {
Card c1 = (Card)hand.get(i);
if ( c1.getSuit() < c.getSuit() ||
(c1.getSuit() == c.getSuit() && c1.getRank() < c.getRank()) ) {
pos = i;
c = c1;
}
}
Object remove = hand.remove(pos);
newHand.add(c);
}
hand = newHand;
}
public int getBlackjackValue() {
int val;
boolean ace;
int cards;
val = 0;
ace = false;
cards = getCardCount();
for ( int i = 0; i < cards; i++ ) {
Card card;
int cardVal;
card = getCard(i);
cardVal = card.getRank();
if (cardVal > 10) {
cardVal = 10;
}
if (cardVal == 1) {
ace = true;
}
val = val + cardVal;
}
if ( ace == true && val + 10 <= 21 ){
val = val + 10;
}
return val;
}
}
It's impossible to tell because you have not shown us the relevant code. However, if your results are not random, it's probably because Deck.dealCard() is not random.
Update
After reading the new code you posted. You are not shuffling your deck after you create it.
It's not random, because Deck::dealCard() is not random.
dealCard is quite strange: when a new Deck is created, cardsUsed is 0, yet you shuffle only if cardsUsed is 52.
public Card dealCard() {
if (cardsUsed == 52){
shuffle();}
cardsUsed++;
return deck[cardsUsed - 1];
}
I think you should move the call to shuffle to the constructor, right after constructing the deck.