Solved

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

Posted on 2011-09-06
12
233 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
  • 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
 

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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Problem to start Neon 20 85
eclipse formatting 6 71
Groovy:unable to resolve class error 2 68
Java Server Faces parameter pass? 6 39
Navigation is an important part of web design from a usability perspective. But it is often a pain when it comes to a developer’s perspective. By navigation, it often means menuing. This is less theory and more practical of how to get a specific gro…
The purpose of this article is to demonstrate how we can use conditional statements using Python.
The viewer will learn how to implement Singleton Design Pattern in Java.
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

911 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

Need Help in Real-Time?

Connect with top rated Experts

26 Experts available now in Live!

Get 1:1 Help Now