[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
Solved

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

Posted on 2011-09-06
12
Medium Priority
?
243 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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 

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 2000 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

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

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

Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
The purpose of this article is to demonstrate how we can use conditional statements using Python.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…
Suggested Courses

656 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