How to create for-loop for Blackjack? - java

Trying to create a blackjack game, and I'm having some trouble figuring out how to print out and array of cards.
So after the player has seen their first two cards, they can choose to either hit or stand.
When they choose to hit, I want it to print a random card from the array I've created and add the integer value of the card (using .rank to get int) to a variable to count their score.
Here I made a loop that filled two arrays with cards.
Card[] dealerDeck = new Card[21];
Card[] playerDeck = new Card[21];
for (int i = 0; i < 21; i++)
{
dealerDeck[i] = deck.cards[i+11];
playerDeck[i] = deck.cards[i+30];
}
How do I get it to print some random card from the array using a for-loop?
String temp;
int userChoice = 0;
while (score < 21 || userChoice != 1)
{
System.out.println("Do you want to HIT or STAND?");
temp = scanner.nextLine();
if (temp.contains("H") || temp.contains ("h"))
{
System.out.println(" "); //This is for aesthetics
System.out.println("The dealer gave you a ");
//you can use .printCard(); to print the card out
// as King of Hearts, Four of Spades, etc.
}
else if (temp.contains("S") || temp.contains ("s"))
{
System.out.println(" ");
System.out.println("Your final score is "+score+".");
userChoice++;
}
}
Sorry if this a bit confusing, English is my first language.
I think I have it all in my head, I just need to get what's in my head into code.
Thanks in advance!

First, you'll need to change your arrays to an ArrayList as shown:
ArrayList<Card> dealerDeck = new ArrayList<Card>();
ArrayList<Card> playerDeck = new ArrayList<Card>();
This will enable you to remove cards from the Card arrays and modify them more easily. To pick a random card, use this:
Random rand = new Random();
void addRandomCard() {
int randIndex = rand.nextInt(dealerDeck.size());
dealerDeck.remove(randIndex);
playerDeck.add(randIndex);
}
Is this what you were looking for?

Related

Implementing a second ship into one dimensional battleship game Java

I have designed the battleship game to only have one ship hidden and now I have to implement another ship into the game. I am new to Java and was wondering if anybody could offer me a simple way to go about this. Do I need to create another method or just adjust the display river method?
public static void displayRiver(int[] river, boolean showShip) {
System.out.println();
System.out.print("|");
for (int val : river) {
switch (val) {
case -1: // No Ship
System.out.print("x");
break;
case 0: // Unknown
System.out.print(" ");
break;
case 1: // Ship Found
System.out.print(showShip ? "Y" : " ");
break;
}//switch
System.out.print("|");
}//for
System.out.println();
System.out.println();
}//displayRiver
// main method
public static void main(String[] arg) {
int riverLength = promptForInt("Please, enter the river lenght");
int [] shipArray = new int[riverLength];
int randomBattleshipLocation = new Random().nextInt(riverLength);
shipArray[randomBattleshipLocation] = 1;
boolean showShip = false ;
int userGuess;
do
{
displayRiver (shipArray, false);
userGuess = promptForInt(String.format("Guess, enter a location from 1 to " + riverLength));
userGuess = userGuess -1;
if(shipArray[userGuess] == 1)
{
System.out.println("Boom! ");
showShip = true;
displayRiver(shipArray, true);
}
else if(shipArray[userGuess] == -1)
{
System.out.println("Location was already hit, try again! ");
}
else if(shipArray[userGuess] == 0)
{
System.out.println("Splash...");
shipArray[userGuess] = -1 ;
}
} while(!showShip);
System.exit(0);
}
}
Your logic seems to be that an 1 in the array indicates a ship, and your ships apparently are never more than one in width.
You currently use the following to create one ship
int randomBattleshipLocation = new Random().nextInt(riverLength);
shipArray[randomBattleshipLocation] = 1;
So you could turn that into a method that creates a battleship, then call that as many times as you want for multiple ships. Just make sure that you don't assign a ship on top of another ship, or make another logical error (like trying to put 5 ships into a river of size 4, and it will loop forever trying to find space for ships).
Pseudo-code and not-so-pseudo-code:
for(int i = 0;i < shipsToAdd; i++) {
addShip(shipArray);
}
// Use a shared class-level Random object, don't do new Random().nextInt();
private static Random rnd = new Random();
private static addShip(int[] array) {
// Here you should loop to check if the array is already full of ships
// otherwise it's a design flaw that will result in an infinite loop with bad input
// loop until we find a shipless array index
int index = rnd.nextInt(array);
while(array[index] == 1)
index = rnd.nextInt(array);
array[index] = 1;
}

Flag variable with user input to quit

I have a program that is supposed to simulate a game of poker in java. I have a method class called Poker and a check class called CheckPoker which calls the methods in the method class. I haven't even been able to check if the algorithmic part works because while asking if the user would like to switch out any cards. The loop should quit after 5 cards have been entered or if the user enters "1" but in running the program, the for loop doesn't quit until 5 card values have been entered and then throws a "java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 56" error. I have tried a for loop, a while loop, a do-while loop, but none have seemed to work thus far.
import java.util.*;
public class Poker {
private String[] deck = {
"D1","D2","D3","D4","D5","D6","D7","D8","D9","D10","DJ","DQ","DK","DA",
"C1","C2","C3","C4","C5","C6","C7","C8","C9","C10","CJ", "CQ","CK","CA",
"H1","H2","H3","H4","H5","H6","H7","H8","H9","H10","HJ", "HQ","HK","HA",
"S1","S2","S3","S4","S5","S6","S7","S8","S9","S10","SJ", "SQ","SK","SA"};
private List<String> hand = new ArrayList<>();
public Poker(){
Collections.shuffle(Arrays.asList(deck));
}
public void playGame(){
System.out.print("The first five cards are: ");
for(int i = 0; i<5; i++){
System.out.print(deck[i] +", ");
}
System.out.println(" ");
int k = 0;
String j;
List<String> discard = new ArrayList<>();
Scanner in = new Scanner(System.in);
System.out.println("Enter up to 5 cards you want to get rid of (1 to quit): ");
while (k<5) { //this is the loop I'm having trouble with
j = in.next();
if(!j.equals("1")){
j = in.next();
discard.add(j);
k++;
}else{
break;
}
}
List deckList = Arrays.asList(deck);
String[] discard1 = discard.toArray(new String[0]);
for(int l = 0; l<k; l++){
int m = deckList.indexOf(discard1[l]);
String n = deck[m];
deck[m] = deck[l+5];
deck[l+5] = n;
}
System.out.print("Your new hand is: ");
for(int i = 0; i<5; i++){
System.out.print(deck[i] +", ");
hand.add(deck[i]);
}
System.out.println(" ");
}
Try the code below. It seems you were grabbing two cards per iteration and not capturing them all in the ArrayList.
Scanner in = new Scanner(System.in);
System.out.println("Enter up to 5 cards you want to get rid of (1 to quit): ");
while (k<5) { //this is the loop I'm having trouble with
j = in.nextLine();
if(j.equals("1") {
break;
}
discard.add(j);
k++;
}

How to program a dice race

I'm taking a programming II class in which we've been working on programming classes. Now we've been assigned homework to write a driver class to incorporate these classes. The homework states
Using the die, dice, and player classes completed in class, write a
driver class to have three players taking turns rolling the dice.
First player to accumulate a total score of 35 or more is the winner."
For example, if player 1 rolls a 3, their score is 3. Then player 2
rolls. Then player 3. As each player rolls, their roll is added to
their previous score.
I've started writing it, but have been given the error that several items in my program cannot be resolved to a type. I also have absolutely no idea how to even begin creating a loop to do what is being asked. This is what I have so far:
import java.util.Scanner;
public class DiceRace {
public static void main(String[] args){
Player player1;
Player player2;
Player player3;
Dice dice;
Scanner keyboard;
keyboard=new Scanner(System.in);
dice=new Dice();
System.out.print("First player's name: ");
player1=keyboard.next();
System.out.print("Second player's name: ");
player2=keyboard.next();
System.out.print("Third player's name: ");
player3=keyboard.next();
}//Ending bracket of method main
}//Ending bracket of class DiceRace
You can create 3 methods, for each player, and a method that plays the game. In each player's method, it first calls the play method with a parameter containing the player name, and the play method prints it out so that the player knows who's turn it is. once the play method is done, it will call the next player method, then the player after that, and finally back to player 1.
It looks like you're a beginner. You should do some tutorials or stuff like that to know the basics :) Also, if you start getting familiar with an IDE (like Eclipse) then programming will be far more easy for you as IDEs can give you detailed descriptions of errors, even while writing the code.
In your above example you need to create two classes by yourself Dice and Player, as they are not in Java by default.
The method keyboard.next() reads an input from the console and returns it as object of the type String, not Player. Thus, you can not assign the variable player1 the result, a String.
What you probably want is a Player object having a member variable String name. Here's an example:
public final class Player {
private String mName;
public Player(final String name) {
mName = name;
}
public String getName() {
return mName;
}
}
Then you can do something like this in your main-method:
player1 = new Player(keyboard.next());
System.out.println("Name of player1 is: " + player1.getName());
Next you probably want a Dice to have a roll method:
public final class Dice() {
private Random mRandom;
public Dice() {
mRandom = new Random();
}
public int roll() {
// Returns a random number between 1 and 6 (inclusive)
return mRandom.nextInt(6) + 1;
}
}
Then, in your main you can do:
Dice dice = new Dice();
System.out.println("Let's roll the dice: " dice.roll());
Now to the games logic, let's keep it very simple, beginner friendly:
int player1Score = 0;
int player2Score = 0;
int player3Score = 0;
boolean finished = false;
boolean player1One = false;
boolean player2One = false;
boolean player3One = false;
// 0 is first player, 1 second and 2 third
int currentPlayer = 0;
while(!finished) {
int rollValue = dice.roll();
if (currentPlayer == 0) {
player1Score += rollValue;
} else if (currentPlayer == 1) {
player2Score += rollValue;
} else {
player3Score += rollValue;
}
player1One = player1Score >= 35;
player2One = player2Score >= 35;
player3One = player3Score >= 35;
finished = player1One || player2One || player3One;
// Increment and modulo 3 (numbers between 0 and 2)
currentPlayer = ((currentPlayer + 1) % 3);
}
Good luck :)

Deck Dealing Java

I'm trying to write a code for class that does the following:
Asks how many decks to use
Program produces a single unused card, from the deck(s) each time enter is pressed
Program notifies the user when there are no more cards to deal
Program Allows the user to play again
Methods are used extensively
So far, my code looks like this:
import java.util.*;
public class IA3 {
#SuppressWarnings({ })
public static void play () {
}
#SuppressWarnings("resource")
public static void main(String[] args) {
boolean draw = true;
boolean pa = true;
Scanner console = new Scanner(System.in);
// TODO Auto-generated method stub
System.out.println("Hello! Please input the number of decks you would like to use:");
int decks = console.nextInt();
int t = decks * 52;
System.out.println("Your total amount of cards to use are " +t);
int a = 0;
do {
int[] deck = new int[t];
//declaration of suits and ranks
String[] suits = {"Spades", "Hearts", "Diamonds", "Clubs"};
String[] ranks = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};
//Initializing of the cards
for (int i = 0; i < t; i++) {
deck[i] = i;
}
System.out.println("Press enter to draw a random card : "); //allows player to prompt the system for the next card
String input = console.nextLine();
a++;
if (input.equals("")) {
// Shuffles the cards
for (int i = 0; i < 1; i++) {
int index = (int)(Math.random() * t);
int temp = deck[i];
deck[i] = deck[index];
deck[index] = temp;
}
for (int i = 0; i < 1; i++) {
String suit = suits[deck[i] / 13];
String rank = ranks[deck[i] % 13];
System.out.println(rank + " of " + suit);
}
if (a>t) {
System.out.println ("No more cards available");
break;
}
System.out.println("Draw another card? (Yes or No) : ");
String again = console.nextLine();
if (again.equals("Yes")) {
continue;
}
if (again.equals("No")) {
draw = false;
System.out.println("Game over!");
}
System.out.println("Play again? (Yes or No) : ");
String plag = console.nextLine();
if (plag.equals("Yes")) {
continue;
}
if (plag.equals("No")) {
pa = false;
System.out.println("Thank you for playing!");
break;
} while (pa == true);
}
} while (draw == true);
}
}
Issues arise when I try to run more than 1 deck, sometimes failing immediately, while sometimes running maybe 4 deals then failing. I also cannot seem to get it to run again; it just terminates whenever I input "Yes" instead of playing again. As you can see, I have no methods in there (I am SO LOST on methods). Any help would be appreciated, thank you!
You should post full error message. Without it it's hard to guess what is happening. I see at least one place where array index can be out of boundaries:
String suit = suits[deck[i] / 13];
Result of this devision will be greater than 3 if you have more than 1 deck. You can fix it using:
String suit = suits[(deck[i] / 13) % 4];
This way you ensure than only elements with indexes [0,1,2,3] will be used.
Can't post a comment yet, so here are a few ideas to make this code easier to follow, especially that your question is asking for "any help."
Remove for loops that look like this:
for (int i = 0; i < 1; i++) {
// code
}
The above for loop sets i to 0, then executes the internal code, then increments i (so i is now equal to 1), then checks to see if i is less than 1 (which it is not because it equals 1 now), so it does not execute the internal code again. So in other words, this type of for loop is not necessary because it can only ever execute its internal code once. The surrounding for loop should be removed and the internal code left intact.
It may be simpler to store your deck as a ArrayList, instead of an array. The advantage of this is that you can take advantage of operations like .remove(int) and .size(), and you wouldn't have to worry about shuffling your deck (you could just randomly remove an entry and print it out).
Hope that gives you a few pointers in the right direction. Keep it up!
And here is an helpful tutorial for creating methods, which I found by doing a google search for "java methods". http://www.tutorialspoint.com/java/java_methods.htm

Java passing array error

I've looked around and I can't see why I'm having this problem. Basically, I'm passing an array of player objects but after passing them I can't access the details correctly.
Code:
for(int i = 0; i <= 2;i++){
players[i] = new Player(names[i], chipCount);
System.out.println(players[i].getName());
}
This for loop is in my main method. I have another for loop that sets up three players (Player is an object that requires a name and a number of chips, and has two methods - getName() and getChips()). The players are "Bob" "Billy" and "Barney" and in the above loop they get printed out fine, however when I pass the array of players over to my 'Game' class, attempting to print the player's names in the same way as above just prints "Barney Barney Barney" instead.
Code for Game class:
public class Game {
Player[] players;
int pot = 0;
public Game(Player[] player){
this.players = player;
}
public void startGame(int rounds){
int roundNumber = 1;
while(roundNumber != rounds){
System.out.println("Starting round " + roundNumber);
System.out.print("Players: ");
for(int i = 0; i <= 2; i++){
System.out.print(players[i].getName() + " ");
}
System.out.println("");
roundNumber = rounds;
}
}
}
And how I'm calling Game:
Game game = new Game(players);
Anyone know why it's not printing out the names correctly? Am I passing the array incorrectly?
Thanks
My bet is that the fields (name and chips) in Player are static. They shouldn't.
Read the Java tutorial about instance and static members.

Categories