切换案例卡类

时间:2014-10-27 00:00:12

标签: java switch-statement

主类:

public class Card
{
private String cardShort;
private String cardClas;
private String cardType;
public Card(String cardClas, String cardType)
{
    this.cardType = cardType;
    this.cardClas = cardClas;
}
public void cardSelector()
{
    switch(cardClas.toUpperCase())
    {
            case "J" : cardClas = "Jack";
                  break;
            case "K" : cardClas = "King";
                  break;
            case "Q" : cardClas = "Queen";
                  break;
            case "A" : cardClas = "Ace";
                  break; 
            case "2" : cardClas = "Two";
                  break;
            case "3" : cardClas = "Three";
                  break;
            case "4" : cardClas = "Four";
                  break;
            case "5" : cardClas = "Five";
                  break;
            case "6" : cardClas = "Six";
                  break; 
            case "7" : cardClas = "Seven";
                  break; 
            case "8" : cardClas = "Eight";
                  break;
            case "9" : cardClas = "Nine";
                  break; 
            case "10" : cardClas = "Ten";
                  break;                       
    }
    switch(cardType.toUpperCase())
    {
        case "S" : cardClas = "Spades";
                  break; 
        case "C" : cardClas = "Clubs";
                  break;
        case "H" : cardClas = "Hearts";
                  break; 
        case "D" : cardClas = "Diamonds";
                  break;                
    }
}
public String getClasses()
{
    return cardType;
}
public String getType()
{
    return cardClas;
}
public String toString()
{
    String theory = getClasses() + " of " + getType();
    return theory;
}

}

测试仪:

import java.util.Scanner;
public class CardTester
{
public static void main(String[] args)
{
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter card: ");
    String shortHand = sc.next();

    if(shortHand.length() == 2)
    {
        Card c = new Card(shortHand.substring(0,1),shortHand.substring(1,2) );
        c.cardSelector();
        System.out.println(c.toString());
    } else if(shortHand.length() == 3)
    {
        Card c = new Card(shortHand.substring(0,2), shortHand.substring(2,3));
        c.cardSelector();
        System.out.println(c.toString());
    }
}

}

控制台: “输入卡片: 如 黑桃S “ 假设输出“黑桃王牌”。尝试了一系列不同的修复程序,不确定是什么原因引起了这个问题。

第一次使用开关盒,可以使用一些帮助......谢谢!

2 个答案:

答案 0 :(得分:2)

您的两个switch语句都设置为cardClas。您需要其中一个来设置cardType

另外,你的两个吸气剂非常令人困惑。你似乎已经以某种方式交换了名字;因此,getClasses返回cardTypegetType返回cardClas。你可能想解决这个问题。

答案 1 :(得分:0)

首先,我希望您使用的是Java 7.如果不是(或者您只想简化它),您可以在switch语句中使用char而不是String。同时在两个switch语句中设置cardClas。你的方法getClasses返回cardType,你的getCardType返回cardClas