This is part of my code for a Black Jack program that I broke apart. This is just the section that deals two cards to the player and then prompts for another card and totals up the sum. My sum messes up every time when the player chooses another card, because my formula will add the new number to the original two cards and now the first two cards and the first new card.
这是我分手的Black Jack程序代码的一部分。这只是向玩家发放两张牌然后提示另一张牌并总计总和的部分。每当玩家选择另一张牌时,我的总和就会混乱,因为我的公式会将新号码添加到原来的两张牌,现在是前两张牌和第一张新牌。
import java.util.Scanner;
import java.util.Random;
public class DealToPlayer
{
public static void main(String[] args)
{
String input;
char choice;
int sum;
int card1;
int card2;
int newCard;
@SuppressWarnings("resource")
Scanner keyboard = new Scanner(System.in);
Random randomNumbers = new Random();
card1 = randomNumbers.nextInt(13)+1;
card2 = randomNumbers.nextInt(13)+1;
System.out.println("First Card: " +card1 + " Second Card: " +card2);
System.out.println("Would you like another card?");
input = keyboard.nextLine();
choice = input.charAt(0);
do
{
newCard = randomNumbers.nextInt(13)+1;
System.out.println("New card: " +newCard);
sum = card1 + card2 + newCard;
System.out.println("Sum: " +sum);
System.out.println("Would you like another card?");
input = keyboard.nextLine();
choice = input.charAt(0);
}while (choice == 'Y' || choice == 'y');
}
}
1 个解决方案
#1
4
just extract the card1 + card2 from the loop :
只需从循环中提取card1 + card2:
sum = card1 + card2;
do
{
newCard = randomNumbers.nextInt(13)+1;
System.out.println("New card: " +newCard);
sum = sum + newCard;
System.out.println("Sum: " +sum);
this way each loop will add only the new card value to the sum.
这样每个循环只会将新卡值添加到总和中。
#1
4
just extract the card1 + card2 from the loop :
只需从循环中提取card1 + card2:
sum = card1 + card2;
do
{
newCard = randomNumbers.nextInt(13)+1;
System.out.println("New card: " +newCard);
sum = sum + newCard;
System.out.println("Sum: " +sum);
this way each loop will add only the new card value to the sum.
这样每个循环只会将新卡值添加到总和中。