How to test my Deck class in Java - java

I would like to print my ArrayList FullDeckArray to see if my Deck has all 52 cards and values.
This is my Card and Deck Classes below
package blackjack;
/**
*
* #author mvisser
*/
public class Card
{
private int rank;
private int suit;
public String tostring(Card card1)
{
String result = "";
if (rank == 1) {
result = "Ace";
}
if (rank == 2) {
result = "Two";
}
if (rank == 3) {
result = "Three";
}
if (rank == 4) {
result = "Four";
}
if (rank == 5) {
result = "Five";
}
if (rank == 6) {
result = "Six";
}
if (rank == 7) {
result = "Seven";
}
if (rank == 8) {
result = "Eight";
}
if (rank == 9) {
result = "Nine";
}
if (rank == 10) {
result = "Ten";
}
if (rank == 11) {
result = "Jack";
}
if (rank == 12) {
result = "Queen";
}
if (rank == 13) {
result = "King";
}
if (suit == 1) {
result = result + " of Clubs ";
}
if (suit == 2) {
result = result + " of Diamonds ";
}
if (suit == 3) {
result = result + " of Hearts ";
}
if (suit == 4) {
result = result + " of Spades ";
}
return result;
}
public Card(int rank, int suit)
{
this.rank = rank;
this.suit = suit;
}
}
As you can see in my Deck Class I hava a ArrayList FullDeckArray and all I want to do is
print it out so see what value is bringing back
public class Deck
{
// private Card[][] fullDeck = new Card[0][0];
private Random shuffle = new Random();
public ArrayList<Card> FullDeckArray = new ArrayList<Card>();
// private int numberOfCards = 52;
public Deck()
{
for (int rank = 1; rank <= 13; rank++) {
for (int suit = 1; suit <= 4; suit++)
{
FullDeckArray.add(new Card(rank, suit));
}
}
}
public void shuffle() {
Collections.shuffle(FullDeckArray);
}
public Card DrawCard() {
int cardPosition = shuffle.nextInt(FullDeckArray.size()+1);
return FullDeckArray.remove(cardPosition);
}
public int TotalCards() {
return FullDeckArray.size();
}
public void test() {
System.out.println( ArrayList<Card>( FullDeckArray ) );
}
}

I would use enums, and with the enum.values() method, you can easily loop through all values of the enumeration.
public class Card {
public enum Rank {
ACE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING;
public String toString() {
switch(this) {
case ACE: return "Ace";
case TWO: return "Two";
case THREE: return "Three";
case FOUR: return "Four";
case FIVE: return "Five";
case SIX: return "Six";
case SEVEN: return "Seven";
case EIGHT: return "Eight";
case NINE: return "Nine";
case TEN: return "Ten";
case JACK: return "Jack";
case QUEEN: return "Queen";
case KING: return "King";
default: return "ERROR: no valid rank";
}
}
}
public enum Suit {
CLUBS, DIAMONDS, HEARTS, SPADES;
public String toString() {
switch(this) {
case CLUBS: return "Clubs";
case DIAMONDS: return "Diamonds";
case HEARTS: return "Hearts";
case SPADES: return "Spades";
default: return "ERROR: no valid suit";
}
}
}
private Rank rank;
private Suit suit;
public Card(Rank rank, Suit suit) {
this.rank = rank;
this.suit = suit;
}
public String toString() {
return rank.toString() + " of " + suit.toString();
}
public boolean equals(Object other) {
if (!(other instanceof Card)) return false;
Card card = (Card) other;
if (card.rank == this.rank && card.suit == this.suit) return true;
return false;
}
}
while in your deck class, you add all cards with this simple loop:
public void fill() {
for (Rank rank : Card.Rank.values()) {
for (Suit suit : Card.Suit.values()) {
Card card = new Card(rank, suit)
cards.add(card);
System.out.println(card.toString());
}
}
}
The rest of your deck class, you can maintain.
If you want to check for the cards being only added once, you can use a HashSet, as in a set, Objects can only occur once (but you need the equals() method):
HashSet<Card> set = new HashSet<Card>(cards);
cards = new ArrayList<Card>(set);
After that, you can check size with 'cards.size()'.
Update: Here's some code for evading the usage of Arrays in Card and for evading enums:
public class Deck {
private Random shuffle = new Random();
public ArrayList<Card> fullDeck = new ArrayList<Card>();
public Deck() {
for (int rank = 1; rank <= 13; rank++) {
for (int suit = 1; suit <= 4; suit++) {
fullDeck.add(new Card(rank, suit));
}
}
}
public void print() {
String deckOutput = "";
for (Card card : fullDeck) {
deckOutput += card.toString() + "\n";
}
System.out.println(deckOutput);
}
public static void main(String[] args) {
Deck deck = new Deck();
deck.print();
}
}
And for Card, use this:
public class Card {
private int rank;
private int suit;
public Card(int rank, int suit) {
this.rank = rank;
this.suit = suit;
}
public String toString() {
String Srank = "", Ssuit = "";
switch(rank) {
case 1: Srank = "Ace"; break;
case 2: Srank = "Two"; break;
case 3: Srank = "Three"; break;
case 4: Srank = "Four"; break;
case 5: Srank = "Five"; break;
case 6: Srank = "Six"; break;
case 7: Srank = "Seven"; break;
case 8: Srank = "Eight"; break;
case 9: Srank = "Nine"; break;
case 10: Srank = "Ten"; break;
case 11: Srank = "Jack"; break;
case 12: Srank = "Queen"; break;
case 13: Srank = "King"; break;
}
switch(suit) {
case 1: Ssuit = "Clubs"; break;
case 2: Ssuit = "Diamonds"; break;
case 3: Ssuit = "Hearts"; break;
case 4: Ssuit = "Spades"; break;
}
return Srank + " of " + Ssuit;
}
}
To test, you can still use the HashMap/ArrayList method stated above (only if you implement an equals method in Card as well) and check with the fulldeck.size() if there are 52 cards (which will be all different, because of the HashMap).

You should try this
public class DeckTest{
public static void main(String []args){
System.out.println(new Deck().FullDeckArray);
}
}
Your Card class should be like below code
public class Card
{
private int rank;
private int suit;
public String tostring()
{
String result = "";
if (rank == 1) {
result = "Ace";
}
if (rank == 2) {
result = "Two";
}
if (rank == 3) {
result = "Three";
}
if (rank == 4) {
result = "Four";
}
if (rank == 5) {
result = "Five";
}
if (rank == 6) {
result = "Six";
}
if (rank == 7) {
result = "Seven";
}
if (rank == 8) {
result = "Eight";
}
if (rank == 9) {
result = "Nine";
}
if (rank == 10) {
result = "Ten";
}
if (rank == 11) {
result = "Jack";
}
if (rank == 12) {
result = "Queen";
}
if (rank == 13) {
result = "King";
}
if (suit == 1) {
result = result + " of Clubs ";
}
if (suit == 2) {
result = result + " of Diamonds ";
}
if (suit == 3) {
result = result + " of Hearts ";
}
if (suit == 4) {
result = result + " of Spades ";
}
return result;
}
public Card(int rank, int suit)
{
this.rank = rank;
this.suit = suit;
}
}

you should override your tostring method like:
#override
public String toString(Card card1){
.....
}
and should just pass the arraylist name to System.out.println(). there is no need for type of the array list.
hope this helps...

There are two ways to do this: static and dynamic testing. Static is simpler and less prone to error, but it cannot be an action performed for any other purpose other than to simply verify that this part of your program works properly before moving on with the rest. Dynamic testing is slightly more complicated, but you can test a deck whenever you need to (for when the user modifies the deck in some fashion and you must validate it).
Static testing
The static testing method and the simplest way to do this would be to print out all the cards in a deck and verify it manually. To do that, you would first have to make an addition and a correction. First, you should modify the signature of your tostring method in your Card class to be "toString()" without parameters. This overrides the object method toString() which automatically converts an object to a String. Second, you need to override toString() in your Deck class:
#Override
public void toString() {
StringBuilder sb = new StringBuilder();
for(Card card : FullDeckArray) {
sb.append(card); // calls Card class's toString() method automatically.
sb.append('\n'); // newline character after each card
}
return sb.toString();
}
Now all you have to do is use Deck's toString() method.
public void test() {
System.out.println(this); // calls Deck class's toString() method automatically
}
Dyanmic testing
Testing it dynamically is a little more complicated, but not that much. To test this, how would you go about doing it manually? You'd look for missing cards or duplicates. A good way to test such things are Sets. But before you can use Sets, you must first override hashCode() and equals() methods to redefine how a Card class is considered unique. A card is only equal to another if both rank and suit match.
So add these to your Card class:
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + rank;
result = prime * result + suit;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Card other = (Card) obj;
if (rank != other.rank)
return false;
if (suit != other.suit)
return false;
return true;
}
Now that we have that, we proceed with the actual logic. A simple test would go something like this:
For each card in your deck
If card is not in set
Add card to set
Else
Flag not valid! Duplicate card!
If set does not have exactly 52 cards
Flag not valid! Extra or missing cards!
So it naturally flows that the the code would then be:
public boolean test() {
boolean valid = true;
Set<Card> cardSet = new HashSet<Card>();
for(Card card : FullDeckArray) {
if(!cardSet.contains(card)) {
cardSet.add(card);
} else {
valid = false;
}
}
if(cardSet.size() != 52) {
valid = false;
}
return valid;
}
Also, you should look here for using enums. In addition to making code more readable, it also allows you to add methods like a class, and like a class, add toString() method. Also see jUnit for a decent testing library for Java.

Related

How can I check for duplicate values without making an array?

I have a program that deals 20 cards based on the value of random numbers. So far it works to deal cards such as King of Spades, 2 of Hearts, etc. My job is to check whether or not the cards are duplicate using a method, but without an array. Here is my solution to checking duplicates which doesn't work for obvious reasons:
public class Driver {
public static void main(String [] args) {
for (int i = 0; i < 20; i++){
Cards card1 = new Cards();
Cards card2 = card1;
if (card1 == card2) {
card1 = new Cards();
}
System.out.println(card1);
}
}
}
Here is my support class:
import java.util.Random;
public class Cards {
String hearts = "Hearts";
String diamonds = "Diamonds";
String clubs = "Clubs";
String spades = "Spades";
String suit;
int cardNumber;
String numberName;
String suitName;
Random randomNum = new Random();
public Cards () {
}
public String suit() {
int theRandom = randomNum.nextInt(4);
if (theRandom == 0 ) {
suitName = "hearts";
}
else if ( theRandom == 1) {
suitName = "diamonds";
}
else if (theRandom == 2) {
suitName = "clubs";
}
else {
suitName = "spades";
}
return suitName;
}
public String number() {
int theRandomNum = randomNum.nextInt(12 + 1);
if ( theRandomNum == 1 ) {
numberName = "Ace";
}
else if ( theRandomNum == 2) {
numberName = "2";
}
else if ( theRandomNum == 3) {
numberName = "3";
}
else if ( theRandomNum == 4) {
numberName = "4";
}
else if ( theRandomNum == 5) {
numberName = "5";
}
else if ( theRandomNum == 6) {
numberName = "6";
}
else if ( theRandomNum == 7) {
numberName = "7";
}
else if ( theRandomNum == 8) {
numberName = "8";
}
else if ( theRandomNum == 9) {
numberName = "9";
}
else if ( theRandomNum == 10) {
numberName = "10";
}
else if ( theRandomNum == 11) {
numberName = "Jack";
}
else if ( theRandomNum == 12) {
numberName = "Queen";
}
else if ( theRandomNum == 13) {
numberName = "King";
}
return numberName;
}
public String toString()
{
if (number() == "null") {
return ("3" + " of " + suit());
}
return (number() + " of " + suit());
}
}
For using a large String to store the cards that have been chosen:
String cards = "";
for(int i = 0; i < 20; i++)
{
Cards card = new Cards();
while(cards.contains(card.toString()))
card = new Cards(); //keep generating a random card until it's a new card
cards += card.toString(); //add the card to the string of cards
System.out.println(card);
}
This code would go inside the main method of your Driver class
First your code has a small mistake
int theRandomNum = randomNum.nextInt(12 + 1)
while, determining from your following code you actually mean
int theRandomNum = randomNum.nextInt(12)+1
To store what cards you already had, you can just introduce a String and fill it step by step, always testing if the card you want to accept is not already contained in this String.
//This goes above the loop where you create your cards
String cards = "";
//This goes into the loop
while(cards.contains(card1.toString()){
card1 = new Cards();
}
cards += card1.toString() + "#"; //Using # as a delimiter
System.out.println(card1);
//At the end you could also print your set of cards
System.out.println(cards);
It's not a very nice approach because you're not permitted to use arrays or similar structures but should do its work.
Please also keep in mind that class names are supposed to be singular. So not Cards but Card.

Looping through array just printing classname#hascode

I am trying to work through an assignment and currently stumped as to what my issue could be. I've read through several post and attempted to resolve without success. I know a lot of my code could be simplified, but this is a progression through the text so a lot of stuff has not yet been covered...
This is my Card class
import java.util.Random;
public class Card {
private int suit,face;
private String cardS,cardF;
// Default constructor to generate random number for face and suit
public Card()
{
Random rand = new Random();
suit = rand.nextInt(4)+1;
face = rand.nextInt(13)+1;
}
// Receive card and suit values
public Card(int cardSuit, int cardFace) {
suit = cardSuit;
face = cardFace;
// Define card face and suit values
if(suit == 1){
cardS = "Clubs";
}
else if(suit == 2){
cardS = "Hearts";
}
else if(suit == 3){
cardS = "Spades";
}
else if(suit == 4){
cardS = "Diamonds";
}
if(face == 1){
cardF = "Ace";
}
else if(face == 2){
cardF = "2";
}
else if(face == 3){
cardF = "3";
}
else if(face == 4){
cardF = "4";
}
else if(face == 5){
cardF = "5";
}
else if(face == 6){
cardF = "6";
}
else if(face == 7){
cardF = "7";
}
else if(face == 8){
cardF = "8";
}
else if(face == 9){
cardF = "9";
}
else if(face == 10){
cardF = "10";
}
else if(face == 11){
cardF = "Jack";
}
else if(face == 12){
cardF = "Queen";
}
else if(face == 13){
cardF = "King";
}
//return cardF + " of " + cardS;
}
// Get numerical face value
public int getNumericFace(){
return face;
}
// Get numerical suit value
public int getNumericSuit(){
return suit;
}
}
This is my DeckOfCards class
public class DeckOfCards {
public static final int MAXDECK = 52;
int remainingDeck,suit,face;
String cardS,cardF;
private int myCard;
int cardIndex;
Card[] cardDeck;
public DeckOfCards() {
cardDeck = new Card[MAXDECK];
// Create array of 52 cards
// outer loop cardSuit
// inner loop cardFace
int index = 0;
int maxSuit = 4;
int maxFace = 13;
for (int cardSuit = 1 ; cardSuit <= maxSuit ; cardSuit++)
{
for (int cardFace = 1 ; cardFace <= maxFace ; cardFace++)
{
cardDeck[index] = new Card(cardSuit,cardFace);
index++;
}
}
}
public String getArray()
{
System.out.println(cardDeck[0]);
for (int i = 0 ; i < cardDeck.length ; i++)
{
System.out.println(cardDeck[i]);
}
return "";
}
public String toString()
{
String deckAsString = "";
int i=0;
for (int s = 1; s <= 4 ; s++)
{
for (int c = 1 ; c <= 13 ; c++ )
{
deckAsString += (cardDeck[i] + "");
i++;
}
deckAsString += "\n";
}
return (deckAsString);
}
}
This is my main class... running both methods here have the issue.
public class MainDeck {
public static void main(String[] args) {
DeckOfCards game = new DeckOfCards();
System.out.println("test getArray method");
System.out.println(game.getArray());
System.out.println("test toString method");
System.out.println(game.toString());
}
}
Thanks for your help!
As your toString method in DeckOfCards is using cardDeck array objects and adding them to the returned String:
deckAsString += (cardDeck[i] + "");
So you need to override toString method in Card class also and use it in string manipulations.
Please implement toString() method in your Card class also.

DeckOfCards and HighLow Class incompatible types

I get an incompatible types error when running my code. It is when "playerGuess = d1.deal();"
Thank you in advanced. This main has two other classes that go along with it. The DeckOfCards and Cards Classes.
Card Class
public class Card
{
public final static int ACE = 1;
public final static int TWO = 2;
public final static int THREE = 3;
public final static int FOUR = 4;
public final static int FIVE = 5;
public final static int SIX = 6;
public final static int SEVEN = 7;
public final static int EIGHT = 8;
public final static int NINE = 9;
public final static int TEN = 10;
public final static int JACK = 11;
public final static int QUEEN = 12;
public final static int KING = 13;
public final static int CLUBS = 1;
public final static int DIAMONDS = 2;
public final static int HEARTS = 3;
public final static int SPADES = 4;
private final static int NUM_FACES = 13;
private final static int NUM_SUITS = 4;
private int face, suit;
private String faceName, suitName;
//-----------------------------------------------------------------
// Creates a random card.
//-----------------------------------------------------------------
public Card()
{
face = (int) (Math.random() * NUM_FACES) + 1;
setFaceName();
suit = (int) (Math.random() * NUM_SUITS) + 1;
setSuitName();
}
//-----------------------------------------------------------------
// Creates a card of the specified suit and face value.
//-----------------------------------------------------------------
public Card(int faceValue, int suitValue)
{
face = faceValue;
setFaceName();
suit = suitValue;
setSuitName();
}
//-----------------------------------------------------------------
// Sets the string representation of the face using its stored
// numeric value.
//-----------------------------------------------------------------
private void setFaceName()
{
switch (face)
{
case ACE:
faceName = "Ace";
break;
case TWO:
faceName = "Two";
break;
case THREE:
faceName = "Three";
break;
case FOUR:
faceName = "Four";
break;
case FIVE:
faceName = "Five";
break;
case SIX:
faceName = "Six";
break;
case SEVEN:
faceName = "Seven";
break;
case EIGHT:
faceName = "Eight";
break;
case NINE:
faceName = "Nine";
break;
case TEN:
faceName = "Ten";
break;
case JACK:
faceName = "Jack";
break;
case QUEEN:
faceName = "Queen";
break;
case KING:
faceName = "King";
break;
}
}
//-----------------------------------------------------------------
// Sets the string representation of the suit using its stored
// numeric value.
//-----------------------------------------------------------------
private void setSuitName()
{
switch (suit)
{
case CLUBS:
suitName = "Clubs";
break;
case DIAMONDS:
suitName = "Diamonds";
break;
case HEARTS:
suitName = "Hearts";
break;
case SPADES:
suitName = "Spades";
break;
}
}
//-----------------------------------------------------------------
// Determines if this card is higher than the passed card. The
// second parameter determines if aces should be considered high
// (beats a King) or low (lowest of all cards). Uses the suit
// if both cards have the same face.
//-----------------------------------------------------------------
public boolean isHigherThan(Card card2, boolean aceHigh)
{
boolean result = false;
if (face == card2.getFace())
{
if (suit > card2.getSuit())
result = true;
}
else
{
if (aceHigh && face == ACE)
result = true;
else
if (face > card2.getFace())
result = true;
}
return result;
}
//-----------------------------------------------------------------
// Determines if this card is higher than the passed card,
// assuming that aces should be considered high.
//-----------------------------------------------------------------
public boolean isHigherThan(Card card2)
{
return isHigherThan(card2, true);
}
//-----------------------------------------------------------------
// Returns the face (numeric value) of this card.
//-----------------------------------------------------------------
public int getFace()
{
return face;
}
//-----------------------------------------------------------------
// Returns the suit (numeric value) of this card.
//-----------------------------------------------------------------
public int getSuit()
{
return suit;
}
//-----------------------------------------------------------------
// Returns the face (string value) of this card.
//-----------------------------------------------------------------
public String getFaceName()
{
return faceName;
}
//-----------------------------------------------------------------
// Returns the suit (string value) of this card.
//-----------------------------------------------------------------
public String getSuitName()
{
return suitName;
}
//-----------------------------------------------------------------
// Returns the string representation of this card, including
// both face and suit.
//-----------------------------------------------------------------
public String toString()
{
return faceName + " of " + suitName;
}
}
Deck of Cards Class
public class DeckOfCards
{
private Card[] myCardDeck;
private int nowCard;
public DeckOfCards( ) {
myCardDeck = new Card[ 52 ];
int i = 0;
for ( int suit = Card.SPADES; suit <= Card.DIAMONDS; suit++ )
for ( int pos = 1; pos <= 13; pos++ )
myCardDeck[i++] = new Card(suit, pos);
nowCard = 0;
}
public void shuffle(int n)
{
int i, j, k;
for ( k = 0; k < n; k++ )
{
i = (int) ( 52 * Math.random() );
j = (int) ( 52 * Math.random() );
Card tmp = myCardDeck[i];
myCardDeck[i] = myCardDeck[j];
myCardDeck[j] = tmp;;
}
nowCard = 0;
}
public Card deal()
{
if ( nowCard < 52 )
{
return ( myCardDeck[ nowCard++ ] );
}
else
{
System.out.println("No Cards BRUH");
return ( null );
}
}
public String toString()
{
String s = "";
int Q = 0;
for ( int i = 0; i < 4; i++ )
{
for ( int j = 1; j <= 13; j++ )
s += (myCardDeck[Q++] + " ");
s += "\n";
}
return ( s );
}
public int deckSize()
{
for(int z =0; z < myCardDeck.length && z < 52; z++);
return myCardDeck.length;
}
}
The main driver class (HighLow)
import java.util.*;
public class HighLow
{
public static void main (String [] args)
{
DeckOfCards d1 = new DeckOfCards();
Scanner scan = new Scanner(System.in);
String playerGuess;
Card firstDeal, secondDeal;
int count =0;
d1.shuffle(1);
firstDeal = d1.deal();
while(true)
{
if(d1.deckSize() == 0);
{
System.out.print("Game over! Score: " + count);
break;
}
System.out.print(firstDeal);
System.out.print("Guess if next card will be a high card, or a low card!");
System.out.print("Use H or L");
playerGuess = d1.deal();
if(secondDeal.isHigherThan(firstDeal)&&playerGuess.equals("H"))
{
System.out.print("Nice!!!!");
count++;
firstDeal=secondDeal;
}
else if(firstDeal.isHigherThan(secondDeal) && playerGuess.equals("L"))
{
System.out.println("NICE!!!!");
count++;
firstDeal = secondDeal;
}
else if (firstDeal.isHigherThan(secondDeal) && playerGuess.equals("L"))
{
System.out.print("Good Job!!!!");
count++;
firstDeal = secondDeal;
}
else
{
System.out.println("Sorry, the game is over. But your score is! " + count);
break;
}
}
}}
Thank you!
The method deal() returns a Card:
public Card deal() { ... }
The variable playerGuess is a String:
String playerGuess;
You can't assign a Card to a String:
playerGuess = d1.deal(); // incompatible types
It looks like you want playerGuess to store the user input, so it should be:
playerGuess = scan.next();

How do I set variable to int and String?

I am making a card class, and need to set the face (The number on the card) to the numbers 1-13. However, on a card, a 1 is an ace, a 13 is a king, a 12 is a Queen, and an 11 is a jack. How do I also set the number 1, and 11-13 to a string such as ace, king, queen, or jack? Any help is appreciated!
public void setFace(int f)
{
if(f >= 1 && f <= 13)
face = f;
else
face = 1;
}
public int getFace()
{
return face;
}
I'm assuming you have field like
public int face;
I guess it will work if it's what you meant
public String getFace() {
switch (this.face) {
case 1:
face = "Ace";
break;
case 11:
face = "Jack";
break;
case 12:
face = "Queen";
break;
case 13:
face = "King";
break;
default:
return Integer.toString(face);
break;
}
}
What do you think about this code..?
public void setFace(int f) {
switch (f) {
case 1:
face = 1;
break;
case 11:
face = 1;
break;
case 12:
face = 1;
break;
case 13:
face = 1;
break;
default:
face = f;
break;
}
}
How about using enums?
public enum CardValue {
ACE(1), TWO(2), THREE(3), ..... KING(13);
private int value;
private CardValue(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public CardValue getValueFor(int x) {
// iterate through CardValue enum and return correct instance of the enum
}
}

"Null" logic error after performing if statments [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am a high school student currently taking an introductory computer science course. In class we were assigned with creating a program that would take user input for card notation and return the full description of the card. For example, A user who inputs "AS" would see "Ace of Spades" in the terminal window. However, when my code executes, I get a "null of null" instead of "Ace of Spades" or another card notation.
public class Card
{
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;
}
}
My Tester Class is :
public class CardTester
{
public static void main(String[] args)
{
Card testCard = new Card("AS");
String cardDescription = testCard.getCardDescription();
System.out.print(cardDescription);
}
}
What is causing me to get null?
You're committing a cardinal sin of string comparison in Java.
See this question: How do I compare strings in Java?
You're comparing strings using ==:
rank == "5"
Don't. Use:
if("5".equals(rank)){
instead. The order (as opposed to if(rank.equals("5")) ensures there is no null pointer exception if the string you were comparing was ever to be null.

Categories

Resources