Scanner will not wait for new input - java

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.

Related

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 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?

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

Creating a deck of cards by adding a card each time a user inputs a value [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am trying to make a deck of cards by a user input. E.g. if the user entered 0,4 the card shown would be stored as the 4 of hearts. The code I have so far is not working at all for the suits. I plan to do the same else if for the card values as well.
public void addCard() {
String suit[] = {"Hearts", "Diamonds", "Spades", "Clubs"};
String value[] = {"ZZZZ", "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};
System.out.println("Please enter a suit");
Scanner input = new Scanner(System.in);
int card[] = card.nextLine();
int i;
if(int card[] = 0) {
String newSuit [] = String suit[0];
} else if(int card[] = 1){
String newSuit [] = String suit[1];
} else if (int card[] = 2){
String newSuit [] = String suit [2];
} else if (int card[] = 3){
String newSuit [] = String suit [3];
}
}
You probably get a compiler error in this (and the next ones) line:
if(int card[] = 0)
int card[] is an array, which is eventually an Object, and you are trying to assign to it a primitive value... which won't work.
Besides, it looks like you are trying to compare something, which rather uses ==, and not =.

Type Mismatch can't convert from Boolean to Int (Arrays in custom method)

In my program 13 arrays are supposed to be created, to hold a sum of the range 2-12, in this case two die rolls are rolled 1000 times, and are supposed to print out the amount of times the die's add to roll "2". However,originally the program worked, but later realizing that I need to use arrays in the program, instead of just using a single math.random method. I have tried, simply printing the array values, in the main method, except that proceeded with more errors. Also, i researched the usage of histogram to call arrays to the main, except as my previous attempt, it created severe amounts of more errors
My question is ;
1: How would I fix the main error, allow it to convert from Boolean to int
2: How does a return statement work, does it have to be different for arrays compared to regular integers
Any guidance or information would be well appreciated.
import java.io.*;
public class dont {
public static void main(String[] args) throws Exception {
// System.out.println(input());
int[] counts = new int[13];
System.out.print("The number of times it rolls 4 on two 6 sided dice :" + counts);
}
public static int input () throws IOException {
BufferedReader myInput = new BufferedReader (new InputStreamReader (System.in));
System.out.println("Hello and welcome to the program");
System.out.println("In this program two six sided dices will be rolled and one eleven sided dice will be rolled (1000 times each");
int sum;
int[] counts = new int[13];
System.out.println("The dices will be rolled to determine the odds of how many times the roll 2 comes up on both dies(Press any key to con't) ");
myInput.readLine();
//int count2=0;
int Sixside;
for (int i = 0; i < 1000; i++)
{
// two dice that add to 4, after being rolled one thousand times
Sixside = (int)(Math.random ()*6+1)+(int)(Math.random ()*6+1) == 4;
//print the number of times they add to 4
counts[sum]++;
}
counts[i] = Sixside;
{
//return array to main
return counts [13];
}
}
}
To convert from boolean to int:
In general, assuming you have some boolean b, I would use this:
int x = b? 1:0; // If b is true, x is now 1; if b is false, x is now 0.
This uses the ternary operator.
In your case, however, this construction is unnecessary. If I understand correctly, you want index i of counts to hold the number of times that the dice summed to that index. To do that:
int sumOfDice = (int)(Math.random ()*6+1)+(int)(Math.random ()*6+1);
counts[sumOfDice]++;
To return an array:
Returning an array is much like returning an int. Just change the method declaration for 'input()' to
public static int[] input () throws IOException {
and the return statement to
return counts;
To print an array:
Import java.util.Arrays and call Arrays.toString(yourArrayHere).
The complete program now looks like:
import java.io.*;
import java.util.Arrays;
public class dont {
public static void main(String[] args) throws Exception {
int[] counts = input();
System.out.println("The number of times it rolls 4 on two 6 sided dice :" + counts[4]);
System.out.println("The number of times each number was the sum:" + Arrays.toString(counts);
}
public static int[] input () throws IOException {
BufferedReader myInput = new BufferedReader (new InputStreamReader (System.in));
System.out.println("Hello and welcome to the program");
System.out.println("In this program two six sided dices will be rolled and one eleven sided dice will be rolled (1000 times each"); // We don't actually roll any eleven-sided dice, so I'm not sure why this is here?
int[] counts = new int[13];
System.out.println("The dices will be rolled to determine the odds of how many times the roll 2 comes up on both dies(Press any key to con't) ");
myInput.readLine();
for (int i = 0; i < 1000; i++)
{
int sumOfDice = (int)(Math.random ()*6+1) + (int)(Math.random ()*6+1);
counts[sumOfDice]++;
}
// return array to main
return counts;
}
}
Sixside = (int)(Math.random ()*6+1)+(int)(Math.random ()*6+1) ;
if(Sixside == 4)
System.out.println("Print something");
I assume that you want to check condition and print .
counts[i] = Sixside;
You are using above code after for loop terminates. Scope of i is inside for loop only as it is declared in for loop . So you getting error cannot find symbol variable i

Categories