import java.lang.*;
public class Card
{
String face, suit;
int value;
public Card (String a, String b)
{
face = a;
suit = b;
faceValue(face);
}
public void faceValue(String abc)
{
if (abc.equals("Jack") || abc.equals("Queen") || abc.equals("King"))
{
value = 10;
}
else if (abc.equals("Ace"))
{
value = 11;
}
else
{
value = Integer.parseInt(abc);
}
}
public String toString()
{
return face + " of " + suit + "\nValue of: " + value;
}
public int getValue()
{
return value;
}
public static void main(String [] args)
{
Deck deck = new Deck();
deck.fillDeck();
System.out.println(deck.toString());
}
}
class Deck
{
Card [] cards;
String [] faces = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"};
int counter = 0;
String deckList;
public Deck()
{
cards = new Card[52];
}
public void fillDeck()
{
for (int i = 0; i <= 12; i++)
{
cards[i] = new Card(faces[counter], "Hearts");
counter++;
}
counter = 0;
for (int i = 0; i >= 13 && i <= 25; i++)
{
cards[i] = new Card(faces[counter], "Diamonds");
counter++;
}
counter = 0;
for (int i = 0; i >= 26 && i <= 38; i++)
{
cards[i] = new Card(faces[counter], "Clubs");
counter++;
}
counter = 0;
for (int i = 0; i >= 39 && i <= 51; i++)
{
cards[i] = new Card(faces[counter], "Spades");
counter++;
}
}
public String toString()
{
for (int i = 0; i <= 51; i++)
{
deckList = cards[i].getValue() + " ";
}
return deckList;
}
}
这是我得到的错误,我不确定它是什么。之前的parseInt()也存在一些问题,也许它与之有关?这个课程旨在用于黑色杰克游戏,但我似乎无法通过此错误,任何帮助表示赞赏。
Exception in thread "main" java.lang.NullPointerException
at Deck.toString(Card.java:100)
at Card.main(Card.java:47)
答案 0 :(得分:0)
问题是Deck没有初始化,因为For loop
不正确。
您的循环就像在filDeck方法中一样:
for (int i = 0; i >= 39 && i <= 51; i++)
{
cards[i] = new Card(faces[counter], "Spades");
counter++;
}
但是当你初始化i = 0时,这永远不会运行。所以i的第一个值不符合条件i >= 39 && i <= 51
,循环就会中断。
我宁愿把它作为循环:
for (int i = 51; i >= 39; i--)
{
cards[i] = new Card(faces[counter], "Spades");
counter++;
}
答案 1 :(得分:0)
每个for循环都以i = 0开头。你需要将它改为条件的下限,否则for循环不会运行。
ex:让我们逐步完成最后一次
for(int i=0; i >=39 && i <=51; i++)
i = 0,&gt; = 39&amp;&amp;我&lt; = 51?不,不要输入循环
将其更改为:
(int i = 39; i >= 39 && i <= 51; i++)