Solved

How do I change char to string using a switch statement with a toString() method?

Posted on 2011-09-06
12
238 Views
Last Modified: 2012-05-12
I am fairly new java.

public class Card
{
   
    private String rank;//card rank: a number between 2 and 10, or Jack, Queen, King or Ace
    private char suit;//card suit: S,C,H,or D
    private static String[] Ranks={"2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace"};
    private static char[] Suites={'C','H','D','S'};
     
    /**
     * Constructor for objects of class Card
     */
    public Card()
    {
        rank="2";
        suit='H';
       
    }
   
    public Card(String rank, char suit)
    {
        this.rank=rank;
        this.suit=suit;
    }
     public String getRank()
    {
        return rank;
    }
   
    public char getSuit()
    {
        return suit;
    }
   
    public void setRank(String rank)
    {
        this.rank=rank;
    }
   
    public void setSuit(char suit)
    {
        this.suit=suit;
    }
    //Returns an array of possible card ranks
    public static String[] getPossibleRanks()
    {
        return Ranks;
    }
    //Returns an array of possible card suits
    public static char[] getPossibleSuits()
 {
        return Suites;
    }
   
    public String toString()
    {
        String rank;
        char suit;
       
        switch(suit)
        {
            case 'H': return "Hearts";
            break;
   
        }
}

}
0
Comment
Question by:ryanbecker24
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
  • 3
12 Comments
 
LVL 47

Expert Comment

by:for_yan
ID: 36491310
Change char to String you don't need a switch

jaust say

char charC='c';
String stringC = "" + charC;

(contcatenate with empty string).
If that's waht yo need
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36491322
And why not use strings form the beginnig:

  private static String[] Suites={"C","H","D","S"};
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36491345

Of course you can do this also:
  switch(suit)
        {
            case 'H':
        return "Hearts";
                    case 'C':
        return "Clubs";
           case 'D':
        returns "Diamonds";
         case 'S':
            return "Spades";
   
   
        }
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:ryanbecker24
ID: 36491353
I am having trouble trying to create the toString() method. Also, in the constructor public Card() when I play with the objects it shows "2" how can I just get it to show 2?
0
 

Author Comment

by:ryanbecker24
ID: 36491362
The string representation has to read 2 of Hearts, 3 of Spades, Jack of Diamonds, etc.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36491382
post your full code with main etc., so that I can execute it myslef and
understand what you mean by "shows "2""
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36491426

One simple way is ato add one more array:
import java.util.ArrayList;
import java.util.Random;

public class Card
{
	private int rank, suit;

	private static String[] suits = { "h", "s", "d", "c" };
	private static String[] ranks  = { "A", "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K" };
    private static String [] names = {"of Haerts", "of Spades", "of Diamonsds", "of Clubs"};


	Card(int suit, int rank)
	{
		this.rank=rank;
		this.suit=suit;
	}

    Card(String s){
        for(int i=0; i<ranks.length; i++){
            if(s.substring(0,1).equals(ranks[i])){
                this.rank = i;
            }
        }
           for(int i=0; i<suits.length; i++){
            if(s.substring(0,1).equals(suits[i])){
                this.suit = i;
            }
        }


    }

	public @Override String toString()
	{


		 // return ranks[rank] +  suits[suit];
        return ranks[rank] + " "+ names[suit];
	}

	public int getRank() {
		 return rank;
	}

	public int getSuit() {
		return suit;
	}

}

class Hand {

    ArrayList<Card> cards;

    Hand(String s) {

        cards = new ArrayList<Card>();

        String [] cardStrings = s.split("\\s+");
        for(int j=0; j<cardStrings.length; j++){
            cards.add(new Card(cardStrings[j]));

        }

    }

    Hand (ArrayList <Card> cards){
        this.cards = cards;
    }

    public ArrayList getCards(){
        return cards;
    }

    public String toString(){
        String s = "";
        for(Card c : cards){
            s += c.toString() + " ";
        }
        return s;
    }

}
 class Deck {
	private Card[] cards;
	int i;

	Deck()
	{
		i=51;
		cards = new Card[52];
		int x=0;
		for (int a=0; a<=3; a++)
		{
			for (int b=0; b<=12; b++)
			 {
			   cards[x] = new Card(a,b);
			   x++;
			 }
		}
	}

	public Card drawFromDeck()
	{
		Random generator = new Random();
		int index=0;

		index = generator.nextInt( i );

		Card temp = cards[index];
		cards[index]=cards[i];
		cards[i]=null;
		i--;
		return temp;
	}
}

class Play {


    public static void main(String[] args) {

       
        Deck deck = new Deck();
        ArrayList <Card>cards = new ArrayList<Card>();
        for(int j=0; j<5; j++){
            cards.add(deck.drawFromDeck());
            
        }

        Hand h = new Hand(cards);
        System.out.println(h.toString());

  }

}

Open in new window



Output:

T of Spades J of Haerts 8 of Diamonsds 7 of Diamonsds 2 of Clubs 

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 36491466

Or you can do it this way if you prefer switch :
import java.util.ArrayList;
import java.util.Random;

public class Card
{
	private int rank, suit;

	private static String[] suits = { "h", "s", "d", "c" };
	private static String[] ranks  = { "A", "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K" };
    private static String [] names = {"of Haerts", "of Spades", "of Diamonsds", "of Clubs"};


	Card(int suit, int rank)
	{
		this.rank=rank;
		this.suit=suit;
	}

    Card(String s){
        for(int i=0; i<ranks.length; i++){
            if(s.substring(0,1).equals(ranks[i])){
                this.rank = i;
            }
        }
           for(int i=0; i<suits.length; i++){
            if(s.substring(0,1).equals(suits[i])){
                this.suit = i;
            }
        }


    }

	public @Override String toString()
	{


        String suitName = "";
        switch  (suit){
        case 0:
         suitName = " of Hearts";
            break;
         case 1:
            suitName = " of Spades";
             break;
              case 2:
                suitName = " of Diamonds";
                  break;
                  case 3:
                   suitName = " of Clubs";


    }


		 // return ranks[rank] +  suits[suit];
     //   return ranks[rank] + " "+ names[suit];

         return ranks[rank] + " "+ suitName;
	}

	public int getRank() {
		 return rank;
	}

	public int getSuit() {
		return suit;
	}

}

class Hand {

    ArrayList<Card> cards;

    Hand(String s) {

        cards = new ArrayList<Card>();

        String [] cardStrings = s.split("\\s+");
        for(int j=0; j<cardStrings.length; j++){
            cards.add(new Card(cardStrings[j]));

        }

    }

    Hand (ArrayList <Card> cards){
        this.cards = cards;
    }

    public ArrayList getCards(){
        return cards;
    }

    public String toString(){
        String s = "";
        for(Card c : cards){
            s += c.toString() + " ";
        }
        return s;
    }

}
 class Deck {
	private Card[] cards;
	int i;

	Deck()
	{
		i=51;
		cards = new Card[52];
		int x=0;
		for (int a=0; a<=3; a++)
		{
			for (int b=0; b<=12; b++)
			 {
			   cards[x] = new Card(a,b);
			   x++;
			 }
		}
	}

	public Card drawFromDeck()
	{
		Random generator = new Random();
		int index=0;

		index = generator.nextInt( i );

		Card temp = cards[index];
		cards[index]=cards[i];
		cards[i]=null;
		i--;
		return temp;
	}
}

class Play {


    public static void main(String[] args) {

       
        Deck deck = new Deck();
        ArrayList <Card>cards = new ArrayList<Card>();
        for(int j=0; j<5; j++){
            cards.add(deck.drawFromDeck());
            
        }

        Hand h = new Hand(cards);
        System.out.println(h.toString());

  }

}

Open in new window

0
 

Author Comment

by:ryanbecker24
ID: 36491478
That is my full code. I am using bluej and I don't have to use a main method. In my constructor public Card() it shows "2" with quotes unlike 'H' which shows as H. I typed in switch method and it doesn't work it gives me an error. It reads 'variable suit might not have not been initialized'.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36491512
Look at my switch method based on int index suit rahter than char
weven though char should work eairther
let me try
0
 
LVL 47

Accepted Solution

by:
for_yan earned 500 total points
ID: 36491536

This is with switch on char:


what is bluej ?

import java.util.ArrayList;
import java.util.Random;

public class Card
{
	private int rank, suit;

	private static char[] suits = { 'H', 'S', 'D', 'C' };
	private static String[] ranks  = { "A", "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K" };
    private static String [] names = {"of Haerts", "of Spades", "of Diamonsds", "of Clubs"};


	Card(int suit, int rank)
	{
		this.rank=rank;
		this.suit=suit;
	}

    Card(String s){
        for(int i=0; i<ranks.length; i++){
            if(s.substring(0,1).equals(ranks[i])){
                this.rank = i;
            }
        }
           for(int i=0; i<suits.length; i++){
            if(s.substring(0,1).equals(suits[i])){
                this.suit = i;
            }
        }


    }

	public @Override String toString()
	{


        String suitName = "";
        switch  (suits[suit]){
        case 'H':
         suitName = " of Hearts";
            break;
         case 'S':
            suitName = " of Spades";
             break;
              case 'D':
                suitName = " of Diamonds";
                  break;
                  case 'C':
                   suitName = " of Clubs";


    }


		 // return ranks[rank] +  suits[suit];
     //   return ranks[rank] + " "+ names[suit];

         return ranks[rank] + " "+ suitName;
	}

	public int getRank() {
		 return rank;
	}

	public int getSuit() {
		return suit;
	}

}

class Hand {

    ArrayList<Card> cards;

    Hand(String s) {

        cards = new ArrayList<Card>();

        String [] cardStrings = s.split("\\s+");
        for(int j=0; j<cardStrings.length; j++){
            cards.add(new Card(cardStrings[j]));

        }

    }

    Hand (ArrayList <Card> cards){
        this.cards = cards;
    }

    public ArrayList getCards(){
        return cards;
    }

    public String toString(){
        String s = "";
        for(Card c : cards){
            s += c.toString() + " ";
        }
        return s;
    }

}
 class Deck {
	private Card[] cards;
	int i;

	Deck()
	{
		i=51;
		cards = new Card[52];
		int x=0;
		for (int a=0; a<=3; a++)
		{
			for (int b=0; b<=12; b++)
			 {
			   cards[x] = new Card(a,b);
			   x++;
			 }
		}
	}

	public Card drawFromDeck()
	{
		Random generator = new Random();
		int index=0;

		index = generator.nextInt( i );

		Card temp = cards[index];
		cards[index]=cards[i];
		cards[i]=null;
		i--;
		return temp;
	}
}

class Play {


    public static void main(String[] args) {

       
        Deck deck = new Deck();
        ArrayList <Card>cards = new ArrayList<Card>();
        for(int j=0; j<5; j++){
            cards.add(deck.drawFromDeck());
            
        }

        Hand h = new Hand(cards);
        System.out.println(h.toString());

  }

}

Open in new window

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 36491974
You'd be much better making it type safe and using enum. A Card class is a classic case for the use of enum. See the Card class here:

http://download.oracle.com/javase/1,5.0/docs/guide/language/enums.html
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
jdbc error in jsp application 20 71
ejb on wildfly 5 45
JAVA API design with micro service cloud in mind 1 76
How to fix  socket closed error 11 25
Whether you’re a college noob or a soon-to-be pro, these tips are sure to help you in your journey to becoming a programming ninja and stand out from the crowd.
In this post we will learn different types of Android Layout and some basics of an Android App.
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

740 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question