public class BlackJack {
public static void main(String args[]) {
String input;
char reDo;
Scanner keyboard = new Scanner (System.in);
Random random = new Random();
int card1 = random.nextInt(10) + 1;
int card2 = random.nextInt(10) + 1;
int card = random.nextInt(10) + 1;
int total1 = card1 + card2;
int total2 = total1 + card;
System.out.print("First cards: " + card1 + ", " + card2 + "\n");
System.out.print("Total: " + total1 + "\n");
boolean loop = true;
while (loop) {
System.out.print("Do you want another card? (y/n): ");
input = keyboard.nextLine();
reDo = input.charAt(0);
if (reDo == 'y' || reDo == 'Y') {
System.out.print("Card: " + card + "\n");
System.out.print("Total: " + total2 + "\n");
} else if (reDo == 'n' || reDo == 'N') {
loop = false;
}
}
}
}
The output is as follows:
First cards: 8, 3
Total: 11
Do you want another card? (y/n): y
Card: 7
Total: 18
Do you want another card? (y/n): y
Card: 7
Total: 18
Do you want another card? (y/n): n
I want to be able to generate a new random card within the loop, display the recurring total, and stop the program. The issue I can't understand is how to use the random.nextInt tool and be able to reuse it more accessibly. Currently its stuck as card1, card2, card, total1, and total2. If I could make them so that I could access them more easily the program would be easier I think to write. The issue is that I can't understand how to repeat the random.nextInt within the while loop.
First put all the cards in a deck.
Then generate a random number between 0 and the number of cards in the deck.
If deck is an ArrayList (for example), you could do
import java.util.*;
public class Main
{
public static void main(String[] args)
{
List<Card> deck = new ArrayList<Card>();
deck.add(new Card(1));
deck.add(new Card(3));
deck.add(new Card(7));
deck.add(new Card(10));
Random randomGenerator = new Random();
System.out.println("Deck 1 tests");
// draw 3 cards:
for (int i = 0; i < 3; i++)
{
int randomCard = randomGenerator.nextInt(deck.size());
Card card = deck.remove(randomCard);
System.out.println("Removed a(n) "+card);
}
// you could also do
List<Card> deck2 = new ArrayList<Card>();
deck2.add(new Card(1));
deck2.add(new Card(7));
deck2.add(new Card(3));
deck2.add(new Card(10));
Collections.shuffle(deck2);
System.out.println("Deck 2 tests");
// draw 3 cards:
for (int i = 0; i < 3; i++)
{
Card card = deck2.remove(0);
System.out.println("Removed a(n) "+card);
}
}
}
class Card {
public Card(int i)
{
blackJackValue = i;
}
public int blackJackValue;
public String toString() {
return String.valueOf(blackJackValue);
}
}