0

我是一名高中生,目前正在学习计算机科学入门课程。在课堂上,我们被分配创建一个程序,该程序将接受用户输入的卡片符号并返回卡片的完整描述。例如,输入“AS”的用户会在终端窗口中看到“Ace of Spades”。但是,当我的代码执行时,我得到一个“null of null”而不是“Ace of Spades”或其他纸牌符号。

公共课卡

{

private String rank; 

private String suit;

private String fullRank;

private String fullSuit;

public Card(String rankAndSuit)
{
    rank = rankAndSuit.substring(0,1);


    if (rank == "A")
    {    
       fullRank = "Ace";
    } 
    else
    if  (rank == "2")
    {
        fullRank = "2"; 
    }
    else
    if (rank == "3")
    {    
        fullRank = "3";
    } 
    else
    if  (rank == "4")
    { 
        fullRank = "4"; 
    }
    else
    if (rank == "5")
    {    
        fullRank = "5";
    } 
    else
    if  (rank == "6")
    { 
        fullRank = "6"; 
    }
    else
    if (rank == "7")
    {    
        fullRank = "7";
    } 
    else
    if  (rank == "8")
    {
        fullRank = "8"; 
    }
    else
    if (rank == "9")
    {    
        fullRank = "9";
    } 
    else
    if  (rank == "10")
    {
        fullRank = "10"; 
    }
    else
    if (rank == "J")
    {    
        fullRank = "Jack";
    } 
    else
    if  (rank == "Q")
    { 
        fullRank = "Queen"; 
    }
    else
    if (rank == "K")
    {    
        fullRank = "King";
    } 


    suit = rankAndSuit.substring(1,2);


    if (suit == "D")
    {    
       fullSuit = "Diamonds";
    } 
    else
    if  (suit == "H")
    {
        fullSuit = "Hearts"; 
    }
    else
    if (suit == "S")
    {    
        fullSuit = "Spades";
    } 
    else
    if  (suit == "C")
    {      fullSuit = "Clubs"; 
    }
}

public String getCardDescription()
{
    return fullRank + " of " + fullSuit;
}

}

我的测试员课程是:

公共类 CardTester

{

public static void main(String[] args)
{
    Card testCard = new Card("AS");
    String cardDescription = testCard.getCardDescription();

    System.out.print(cardDescription);
}

}

是什么导致我为空?

4

2 回答 2

0

您正在使用以下方式比较字符串==

rank == "5"

不。利用:

if("5".equals(rank)){

反而。顺序(相反,if(rank.equals("5"))如果您要比较的字符串曾经为空,则确保没有空指针异常。

于 2013-10-23T00:51:17.283 回答
0

你在 Java 中犯了字符串比较的大罪。

请参阅这个问题:如何比较 Java 中的字符串?

于 2013-10-23T00:52:32.513 回答