这是我分手的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');
}
}
答案 0 :(得分:4)
从循环中提取 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);
这样每个循环只会将新卡值添加到总和中。