Deck Dealing Java - 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

Related

Java chatbot mirroring and canned responses

So I got this java chatbot program that I'm working on.
Depending on what the user says, the chatbot either gives a canned response canned_phrases or a mirrored response if the user's response has one of the keywords I love pizza --> you love pizza.
The problem is that the chatbot does not give back the mirrored version. I think the problem is that the words are being overwritten by each other but I'm not sure how to fix that.
Thank for your help!
import java.util.Random;
import java.util.Scanner;
public class Conversation {
public static void main(String[] args) {
String[] canned_phrases = {"Yes",
"Hmmm. Please tell me more news",
"Of course",
"Okay",
"Interesting...",
"Indeed"};
int canned_times = canned_phrases.length;
Scanner conversation_start = new Scanner(System.in);
System.out.println("\nWelcome!\n");
System.out.println("How many rounds of conversation would you like to have?\n");
int rounds = conversation_start.nextInt();
conversation_start.nextLine();
String[] transcript = new String[2 * rounds + 1];
transcript[0] = "Sounds great! How are you doing today?";
System.out.println(transcript[0]);
for (int i = 0; i < rounds; i++) {
String user_words = conversation_start.nextLine();
String mirrored;
String new_version = user_words.replace("I", "you");
new_version = new_version.replace("me", "you");
new_version = new_version.replace("am", "are");
new_version = new_version.replace("you", "I");
new_version = new_version.replace("my", "your");
new_version = new_version.replace("your", "my");
new_version = new_version.replace("my", "you");
if (!new_version.equals(user_words)) {
mirrored = new_version;
}
else {
mirrored = canned_phrases[(int) Math.floor(canned_times * Math.random())];
}
System.out.println(mirrored);
transcript[2 * i + 1] = user_words;
transcript[2 * i + 1] = mirrored;
}
System.out.println("Thank you for chatting with me! Come back soon!");
System.out.println(" ");
System.out.println("TRANSCRIPT ");
for (int i = 0; i <= transcript.length; i++) {
System.out.println(transcript[i]);
}
System.exit(0);
}
}
I think the best way to achieve what you want is to split the user-entered sentence into words and change the individual words according to your rules, for example if the word is my then change it to your. In the below code, I iterate through all the words in order, changing each word as needed and appending them to a StringBuilder so that after iterating through all the words, the StringBuilder contains the mirrored sentence.
(More notes after the code.)
import java.util.Random;
import java.util.Scanner;
public class Conversation {
public static void main(String[] args) {
String[] cannedPhrases = {"Yes",
"Hmmm. Please tell me more news",
"Of course",
"Okay",
"Interesting...",
"Indeed"};
int cannedTimes = cannedPhrases.length;
Random rand = new Random();
Scanner conversationStart = new Scanner(System.in);
System.out.println("\nWelcome!\n");
System.out.println("How many rounds of conversation would you like to have?\n");
int rounds = conversationStart.nextInt();
conversationStart.nextLine();
String[] transcript = new String[2 * rounds];
transcript[0] = "Sounds great! How are you doing today?";
System.out.println(transcript[0]);
int index = -1;
for (int i = 0; i < rounds; i++) {
String userWords = conversationStart.nextLine();
String mirrored;
StringBuilder result = new StringBuilder();
String[] words = userWords.split(" ");
boolean first = true;
for (String word : words) {
if (first) {
first = false;
}
else {
result.append(' ');
}
switch (word) {
case "I":
word = "you";
break;
case "me":
word = "you";
break;
case "am":
word = "are";
break;
case "you":
word = "I";
break;
case "my":
word = "your";
break;
case "your":
word = "my";
break;
}
result.append(word);
}
String newVersion = result.toString();
if (!newVersion.equals(userWords)) {
mirrored = newVersion;
}
else {
mirrored = cannedPhrases[rand.nextInt(cannedTimes)];
}
System.out.println(mirrored);
transcript[++index] = userWords;
transcript[++index] = mirrored;
}
System.out.println("Thank you for chatting with me! Come back soon!");
System.out.println(" ");
System.out.println("TRANSCRIPT ");
for (int i = 0; i < transcript.length; i++) {
System.out.println(transcript[i]);
}
System.exit(0);
}
}
You should try to adhere to Java naming conventions. I changed the variable names in your code accordingly.
Rather than manipulate the [first] for loop variable i to handle both the conversation round and the transcript index, I used a separate variable, named index for the transcript.
Switching on string was added in Java 7.
The for loop that prints the transcript was wrong. The terminating condition should be i < transcript.length (and not i <= transcript.length).
The above code assumes that the user-entered sentence consists of words separated by single spaces. If you want more sophisticated handling of the user-entered sentence, for example handling punctuation, like commas, periods, etc, then you will need to change the split method's regular expression.
Here is output from a sample run:
Welcome!
How many rounds of conversation would you like to have?
2
Sounds great! How are you doing today?
OK
Of course
Why do you say that
Why do I say that
Thank you for chatting with me! Come back soon!
TRANSCRIPT
OK
Of course
Why do you say that
Why do I say that
I made little modification to your code and now it work as you expected:
public static void main(String[] args) {
String[] canned_phrases = {"Yes", "Hmmm. Please tell me more news", "Of course", "Okay", "Interesting...", "Indeed"};
int canned_times = canned_phrases.length;
Scanner conversation_start = new Scanner(System.in);
System.out.println("\nWelcome!\n");
System.out.println("How many rounds of conversation would you like to have?\n");
int rounds = conversation_start.nextInt();
conversation_start.nextLine();
String[] transcript = new String[2*rounds+1];
transcript[0] = "Sounds great! How are you doing today?";
System.out.println(transcript[0]);
for (int i = 0; i < rounds; i++) {
String user_words = conversation_start.nextLine();
String mirrored;
String new_version = user_words.replace("I", "you");
new_version = new_version.replace("me","you");
new_version = new_version.replace("am","are");
//1st change as you replaced it above so not swap it again
//new_version = new_version.replace("you","I");
new_version = new_version.replace("my","your");
new_version = new_version.replace("your","my");
new_version = new_version.replace("my","you");
//by commenting the line above, will enter the IF-block
if (!new_version.equals(user_words)) {
mirrored = new_version;
} else {
mirrored = canned_phrases[(int) Math.floor(canned_times * Math.random())];
}
System.out.println(mirrored);
transcript[2*i+1] = user_words;
//2nd change to not overwrite the same index i added 2 instead of 1
transcript[2*i+2] = mirrored;
}
System.out.println("Thank you for chatting with me! Come back soon!");
System.out.println(" ");
System.out.println("TRANSCRIPT ");
//3rd change i removed the = from the loop condition to prevent exception appeared
for (int i = 0; i < transcript.length; i++) {
System.out.println(transcript[i]);
}
System.exit(0);
}

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++;
}

Scanner will not wait for new input

I have a program that works as expected except for one important aspect of it.
The program is supposed to deal out a random card from a standard deck every time the enter button is pressed.
As of now I can get the program to give me a random card when I press enter, but I can not get it to work one at a time. My console fills all 52 cards into it after pressing enter once.
How can I get it to wait each time for me to press enter before dealing the next card? (The card dealing function is the while loop near the end)
import java.util.Arrays;
import java.util.Scanner;
import java.util.Random;
import java.util.ArrayList;
public class Card {
public static void main(String[] args) {
String[] suit = {" of Diamonds", " of Spades", " of Hearts", " of Clubs"}; //Array of suits
String[] faces = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};//Array of face values
String[] deck = new String[52];//Array of actual deck
int[] random = new int[52]; //Array with all possible numbers between 1-52
boolean deckComplete = false;//Boolean for finished deck
for (int x = 0; x<random.length; x++) {
random[x] = x;
} //Fills array with all possible numbers between 1-52
Random rndNum = new Random();
Scanner scanner = new Scanner(System.in);
String readString = scanner.nextLine();
for (int i = 0; i < deck.length; i++) {
deck[i] = faces[i % 13] + suit[i/13];
} //Creates array with all possible cards in standard deck of cards
ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(deck)); //Converts above array into ArrayList
while (deckComplete == false) {
for (int i = 52; i >= 1; i--) {
int randomNumber = rndNum.nextInt(i);
if (readString.equals("")) {
System.out.println(arrayList.get(random[randomNumber]));
arrayList.remove(random[randomNumber]);
if (i == 1) {
deckComplete = true;
} //Deals out random card from deck and removes each one used
}
}
}
}
}
Your program is only doing what you tell it to do, no more and no less. Think through the code in your mind logically -- and you'll see that the scanner.nextLine() is only being called once, before the for loop, and so your program will thus wait for input only once, just as it is written. Instead, the line of code needs to be called within the for loop, if you want to wait for input before dealing each card. Again right now that line of code is only called once.

How to create for-loop for Blackjack?

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?

Categories