我的纸牌游戏代码有什么问题吗?

时间:2015-04-10 09:48:27

标签: static switch-statement

//Usage:  public Static void play()
//Desc:   Play the game of OneCard. The game has 2 players. the user and the
//        computer.
//        The user is dealt 1 card, and so is the computer. The user has the
//        option to change the card once. The winner is the player with the
//        higher rank card (Ace>King>Queen>...>3>2). The suit is irrelevant.
//Input:  The user enters a character (Y/N) signaling whether the user wants 
//        to change the card.
//Output: The user's card, followed by a message asking if the user wants
//        to change the card, followed optionally the user's new card,
//        followed by the computer's card, followed by the result of the game,
//        followed by a message asking the user if the user wants to play
//        again.
import java.util.Scanner;
class OneCard 
{
public static void play()
{
    Scanner f = new Scanner(System.in);
    DeckOfCards d = new DeckOfCards();
    String meatbag = d.deal();
    String CPU = d.deal();
    System.out.printf("Your card: %s " , meatbag);
    System.out.print("Change card: (y/n)");
    char ch = f.nextLine().charAt(0);
    if (ch == 'y' || ch == 'y') meatbag = d.deal();
    else ;
    findRank(meatbag);
    findRank(CPU);
    whoWon(meatbag, CPU);
}
public static int findRank(String s)
{
    int rank_num= 0;
    switch(s)
    {
        case "Two": rank_num = 2;
            break;
        case "Three": rank_num = 3;
            break;
        case "Four": rank_num = 4;
            break;
        case "Five": rank_num = 5;
            break;
        case "Six": rank_num = 6;
            break;
        case "Seven": rank_num = 7;
            break;
        case "Eight": rank_num = 8;
            break;
        case "Nine": rank_num = 9;
            break;
        case "Ten": rank_num = 10;
            break;
        case "Jack": rank_num = 11;
            break;
        case "Queen": rank_num = 12;
            break;
        case "King": rank_num = 13;
            break;
        case "Ace": rank_num = 14;
            break;
    }
    return rank_num;
}
public static void whoWon(String s1, String s2)
{
    System.out.printf("Your card: %s " , s1);
    System.out.printf("Dealer's card: %s ", s2);
    if(findRank(s1)> findRank(s2)) System.out.println("You won.");
    else if (findRank(s1) < findRank(s2)) System.out.println("Dealer won.");
    else System.out.println("Draw.");
}  
}

我不确定在编写findRank和whoWon方法时是否确实犯了一个逻辑错误。您可以假设已在此代码之前创建了类DeckOfCards和方法DeckOfCards.deal。

1 个答案:

答案 0 :(得分:0)

似乎没有逻辑错误, 只是你可以删除的一些东西:

else ;
findRank(meatbag);
findRank(CPU);

您也可以更改

if (ch == 'y' || ch == 'y') meatbag = d.deal();

if (ch == 'y' || ch == 'Y') meatbag = d.deal();