Why is my call to the shuffle method not working?

240 views Asked by At

I am making a blackjack game that requires the deck to be shuffled at the beginning of each iteration. The two classes of importance here are Deck and Game. In Deck, I created an ArrayList called deck to hold the 52 cards. I also created a method called shuffle.

public void shuffle(){
    Collections.shuffle(deck);
}

Then, in my Game class:

cards = new Deck();
String response;
System.out.println("Do you want to play the game? (0-Yes, 1-No)");
if (Integer.parseInt(response)==1){
    cards.shuffle();
    .....
}

From this point, I then write simple code to distribute the cards and check to see how close the player is to 21. I put all my code in a while loop that iterates 5 times. The problem is that for some reason the player's hand does not change each round(i.e. cards.shuffle() is not shuffling the deck). Why is this occurring. I apologize if this is vague as I am new to Java programming.

2

There are 2 answers

2
maskacovnik On

Threre is no user input:

cards = new Deck();
String response;
System.out.println("Do you want to play the game? (0-Yes, 1-No)");
if (Integer.parseInt(response)==1){
    cards.shuffle();
    .....
}

response will bee null
So i would expect something like this:

cards = new Deck();
Scanner sc = new Scanner(System.in);
String response;
System.out.println("Do you want to play the game? (0-Yes, 1-No)");
response=sc.nextLine();
if (Integer.parseInt(response)==1){
    cards.shuffle();
    .....
}
sc.close();
0
Sagar Pilkhwal On

Integer.parseInt(response) but where are your getting this response, you forgot to get it from user

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Do you want to play the game? (0-Yes, 1-No)");
int response = Integer.parseInt(br.readLine());
if(response==1){
cards.shuffle();
.....
}