当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Why is my call to the shuffle method not working?

问题描述:

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.

网友答案:

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();
网友答案:

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();
.....
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: