我是一名高中生,目前正在修读计算机科学课程。在课堂上,我们被分配了创建一个程序,该程序将用户输入卡片表示法并返回卡片的完整描述。例如,输入“AS”的用户将在终端窗口中看到“黑桃王牌”。但是,当我的代码执行时,我得到一个“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);
}
}
是什么导致我得到空?
答案 0 :(得分:0)
您正在使用==
比较字符串:
rank == "5"
别。使用:
if("5".equals(rank)){
代替。顺序(与if(rank.equals("5"))
相对)确保如果您比较的字符串始终为null,则不存在空指针异常。
答案 1 :(得分:0)
你在Java中犯了字符串比较的主要罪。