|
Thread Rules 1. This is not a "do my homework for me" thread. If you have specific questions, ask, but don't post an assignment or homework problem and expect an exact solution. 2. No recruiting for your cockamamie projects (you won't replace facebook with 3 dudes you found on the internet and $20) 3. If you can't articulate why a language is bad, don't start slinging shit about it. Just remember that nothing is worse than making CSS IE6 compatible. 4. Use [code] tags to format code blocks. |
public Card dealCard() { while( currentCard < 5) { String currentFace = deck[currentCard].getface(); System.out.printf("%s\n", deck[currentCard]); int sameCardsKing=0, sameCardsQueen=0, sameCardsJack=0, sameCards10=0, sameCards9=0, sameCards8=0, sameCards7=0, sameCards6=0, sameCards5=0; int sameCards4=0, sameCards3=0, sameCards2=0, sameCardsAce=0; if(currentFace == "Ace");{ //int sameCardsAce=0; sameCardsAce++; if(sameCardsAce==2) System.out.println("You have a pair"); } if(currentFace == "King");{ //int sameCardsKing=0; sameCardsKing++; if(sameCardsKing==2) System.out.println("You have a pair"); } if(currentFace == "Queen");{ //int sameCardsQueen=0; sameCardsQueen++; if(sameCardsQueen==2) System.out.println("You have a pair"); } if(currentFace == "Jack");{ //int sameCardsJack=0; sameCardsJack++; if(sameCardsJack==2) System.out.println("You have a pair"); } if(currentFace == "10");{ //int sameCards10=0; sameCards10++; if(sameCards10==2) System.out.println("You have a pair"); } if(currentFace == "9");{ //int sameCards9=0; sameCards9++; if(sameCards9==2) System.out.println("You have a pair"); } if(currentFace == "8");{ //int sameCards8=0; sameCards8++; if(sameCards8==2) System.out.println("You have a pair"); } if(currentFace == "7");{ //int sameCards7=0; sameCards7++; if(sameCards7==2) System.out.println("You have a pair"); } if(currentFace == "6");{ //int sameCards6=0; sameCards6++; if(sameCards6==2) System.out.println("You have a pair"); } if(currentFace == "5");{ //int sameCards5=0; sameCards5++; if(sameCards5==2) System.out.println("You have a pair"); } if(currentFace == "4");{ //int sameCards4=0; sameCards4++; if(sameCards4==2) System.out.println("You have a pair"); } if(currentFace == "3");{ //int sameCards3=0; sameCards3++; if(sameCards3==2) System.out.println("You have a pair"); } if(currentFace == "2");{ //int sameCards2=0; sameCards2++; if(sameCards2==2) System.out.println("You have a pair"); } //System.out.println(currentFace);
This is what I'm TRYING to do. I know that this isn't effective OR efficient, but I wanted to test to see if it would even read the String face. It doesn't work. It just prints the cards out, which leads me to believe that it's not comparing the sameCards to the face value or my while loop isn't working properly
|
On February 23 2013 03:59 Blisse wrote:Show nested quote +On February 23 2013 01:49 ranshaked wrote: Hey guys! I need a little help in Java. I'm trying to convert a String to specific ints. It has to do with a card game, so I have face values 2-10, jack, queen, king, ace. I'm using a method called getface(): and I can print out the face values fine, but I need to convert them to ints in order to compare them easier in order to determine the winner of a hand.
I've tried: Switch statements (only to find out that you can't use case 'Ace': faceValue = 14;...apparently it only works with ints!) If statements (doesn't work, it won't let me force the switch) Integer.parseInt(string) (doesn't work, it throws a bunch of errors)
Is there another way to convert the face value from a String to it's equivalent int? The performance of a system that has to use a switch statement every time you want to compare card values is going to be unnecessarily bad. This is a case where you don't want to use strings to store the card. Instead, use ints for all the cards, and only convert them to strings when you need to display it. :/ If you do it that way, you can simply use a single List with all the names of the strings in the correct index, so faceString[1] returns "Ace". This would be more of a design issue/solution. See this is a major problem because our Class Card has the card set-up using Strings for the face value and suit. I'm pretty sure we can't change this. I'm taking this from my book, but this is what I've got as my Card class.
public class Card { private String face; //instance variable private String suit; //instance variable public Card( String cardFace, String cardSuit) { face = cardFace; suit = cardSuit; } public String toString() { return face + " of " + suit; } public String getface() { return face; }
public String getsuit() { return suit; } }
I understand that I could set up the string with all of the suits and faces, then pass it as an int, then return an array of it
Something like:
private int face, suit;
private static String[] suits = { "hearts", "spades", "diamonds", "clubs" }; private static String[] aces = { "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King" };
public static String faceAsString( int face ) { return faces[face]; }
Card(int face, int suit) { this.face=face; this.suit=suit; }
public String toString() { return faces[face] + " of " + suits[suit]; }
public short getFace() { return face; }
public short getSuit() { return suit; } }
This would work, but I really don't think I'm allowed to use this because it completely changes the stuff we are given
|
On February 23 2013 04:07 ranshaked wrote:+ Show Spoiler + public Card dealCard() { while( currentCard < 5) { String currentFace = deck[currentCard].getface(); System.out.printf("%s\n", deck[currentCard] ; int sameCardsKing=0, sameCardsQueen=0, sameCardsJack=0, sameCards10=0, sameCards9=0, sameCards8=0, sameCards7=0, sameCards6=0, sameCards5=0; int sameCards4=0, sameCards3=0, sameCards2=0, sameCardsAce=0; if(currentFace == "Ace");{ //int sameCardsAce=0; sameCardsAce++; if(sameCardsAce==2) System.out.println("You have a pair"); } if(currentFace == "King");{ //int sameCardsKing=0; sameCardsKing++; if(sameCardsKing==2) System.out.println("You have a pair"); } if(currentFace == "Queen");{ //int sameCardsQueen=0; sameCardsQueen++; if(sameCardsQueen==2) System.out.println("You have a pair"); } if(currentFace == "Jack");{ //int sameCardsJack=0; sameCardsJack++; if(sameCardsJack==2) System.out.println("You have a pair"); } if(currentFace == "10");{ //int sameCards10=0; sameCards10++; if(sameCards10==2) System.out.println("You have a pair"); } if(currentFace == "9");{ //int sameCards9=0; sameCards9++; if(sameCards9==2) System.out.println("You have a pair"); } if(currentFace == "8");{ //int sameCards8=0; sameCards8++; if(sameCards8==2) System.out.println("You have a pair"); } if(currentFace == "7");{ //int sameCards7=0; sameCards7++; if(sameCards7==2) System.out.println("You have a pair"); } if(currentFace == "6");{ //int sameCards6=0; sameCards6++; if(sameCards6==2) System.out.println("You have a pair"); } if(currentFace == "5");{ //int sameCards5=0; sameCards5++; if(sameCards5==2) System.out.println("You have a pair"); } if(currentFace == "4");{ //int sameCards4=0; sameCards4++; if(sameCards4==2) System.out.println("You have a pair"); } if(currentFace == "3");{ //int sameCards3=0; sameCards3++; if(sameCards3==2) System.out.println("You have a pair"); } if(currentFace == "2");{ //int sameCards2=0; sameCards2++; if(sameCards2==2) System.out.println("You have a pair"); } //System.out.println(currentFace);
This is what I'm TRYING to do. I know that this isn't effective OR efficient, but I wanted to test to see if it would even read the String face. It doesn't work. It just prints the cards out, which leads me to believe that it's not comparing the sameCards to the face value or my while loop isn't working properly
strcmp() is your friend.
to be honest though this seems like something you could #define nicely like #define ACE 0 #define ONE 1 ... #define KING 13
Then just use that as your 'face' value and just == the ints, you could also have an int array instead of all those different variables just do something like:
int array[14] = {0}
array[ACE]++
which is much clearer and easier to make sense of than all those variables.
Also don't you have to do TEXT("blah") or is that just a C / Win32 thing??
Edit: Just saw your second post and I'm shouting C at your when you're doing Java. My bad, long day but the idea still stands, you can't compare strings like that. It will compare the address of the String I think ( I dont know Java very well ), there will be some kind of string compare function that you should use over ==
|
sorry hit reply instead of edit.
|
On February 23 2013 04:22 adwodon wrote:Show nested quote +On February 23 2013 04:07 ranshaked wrote:+ Show Spoiler + public Card dealCard() { while( currentCard < 5) { String currentFace = deck[currentCard].getface(); System.out.printf("%s\n", deck[currentCard] ; int sameCardsKing=0, sameCardsQueen=0, sameCardsJack=0, sameCards10=0, sameCards9=0, sameCards8=0, sameCards7=0, sameCards6=0, sameCards5=0; int sameCards4=0, sameCards3=0, sameCards2=0, sameCardsAce=0; if(currentFace == "Ace");{ //int sameCardsAce=0; sameCardsAce++; if(sameCardsAce==2) System.out.println("You have a pair"); } if(currentFace == "King");{ //int sameCardsKing=0; sameCardsKing++; if(sameCardsKing==2) System.out.println("You have a pair"); } if(currentFace == "Queen");{ //int sameCardsQueen=0; sameCardsQueen++; if(sameCardsQueen==2) System.out.println("You have a pair"); } if(currentFace == "Jack");{ //int sameCardsJack=0; sameCardsJack++; if(sameCardsJack==2) System.out.println("You have a pair"); } if(currentFace == "10");{ //int sameCards10=0; sameCards10++; if(sameCards10==2) System.out.println("You have a pair"); } if(currentFace == "9");{ //int sameCards9=0; sameCards9++; if(sameCards9==2) System.out.println("You have a pair"); } if(currentFace == "8");{ //int sameCards8=0; sameCards8++; if(sameCards8==2) System.out.println("You have a pair"); } if(currentFace == "7");{ //int sameCards7=0; sameCards7++; if(sameCards7==2) System.out.println("You have a pair"); } if(currentFace == "6");{ //int sameCards6=0; sameCards6++; if(sameCards6==2) System.out.println("You have a pair"); } if(currentFace == "5");{ //int sameCards5=0; sameCards5++; if(sameCards5==2) System.out.println("You have a pair"); } if(currentFace == "4");{ //int sameCards4=0; sameCards4++; if(sameCards4==2) System.out.println("You have a pair"); } if(currentFace == "3");{ //int sameCards3=0; sameCards3++; if(sameCards3==2) System.out.println("You have a pair"); } if(currentFace == "2");{ //int sameCards2=0; sameCards2++; if(sameCards2==2) System.out.println("You have a pair"); } //System.out.println(currentFace);
This is what I'm TRYING to do. I know that this isn't effective OR efficient, but I wanted to test to see if it would even read the String face. It doesn't work. It just prints the cards out, which leads me to believe that it's not comparing the sameCards to the face value or my while loop isn't working properly strcmp() is your friend. to be honest though this seems like something you could #define nicely like #define ACE 0 #define ONE 1 ... #define KING 13 Then just use that as your 'face' value and just == the ints, you could also have an int array instead of all those different variables just do something like: int array[14] = {0} array[ACE]++ which is much clearer and easier to make sense of than all those variables. Also don't you have to do TEXT("blah") or is that just a C / Win32 thing?? Edit: Just saw your second post and I'm shouting C at your when you're doing Java. My bad, long day but the idea still stands, you can't compare strings like that. It will compare the address of the String I think ( I dont know Java very well ), there will be some kind of string compare function that you should use over == I really liked C lol. I'm not understanding this object oriented crap very well.
Umm, you can use different print functions in java which is pretty neat. You can print the actual object instead of needing the quotes
|
On February 23 2013 04:42 ranshaked wrote:Show nested quote +On February 23 2013 04:22 adwodon wrote:On February 23 2013 04:07 ranshaked wrote:+ Show Spoiler + public Card dealCard() { while( currentCard < 5) { String currentFace = deck[currentCard].getface(); System.out.printf("%s\n", deck[currentCard] ; int sameCardsKing=0, sameCardsQueen=0, sameCardsJack=0, sameCards10=0, sameCards9=0, sameCards8=0, sameCards7=0, sameCards6=0, sameCards5=0; int sameCards4=0, sameCards3=0, sameCards2=0, sameCardsAce=0; if(currentFace == "Ace");{ //int sameCardsAce=0; sameCardsAce++; if(sameCardsAce==2) System.out.println("You have a pair"); } if(currentFace == "King");{ //int sameCardsKing=0; sameCardsKing++; if(sameCardsKing==2) System.out.println("You have a pair"); } if(currentFace == "Queen");{ //int sameCardsQueen=0; sameCardsQueen++; if(sameCardsQueen==2) System.out.println("You have a pair"); } if(currentFace == "Jack");{ //int sameCardsJack=0; sameCardsJack++; if(sameCardsJack==2) System.out.println("You have a pair"); } if(currentFace == "10");{ //int sameCards10=0; sameCards10++; if(sameCards10==2) System.out.println("You have a pair"); } if(currentFace == "9");{ //int sameCards9=0; sameCards9++; if(sameCards9==2) System.out.println("You have a pair"); } if(currentFace == "8");{ //int sameCards8=0; sameCards8++; if(sameCards8==2) System.out.println("You have a pair"); } if(currentFace == "7");{ //int sameCards7=0; sameCards7++; if(sameCards7==2) System.out.println("You have a pair"); } if(currentFace == "6");{ //int sameCards6=0; sameCards6++; if(sameCards6==2) System.out.println("You have a pair"); } if(currentFace == "5");{ //int sameCards5=0; sameCards5++; if(sameCards5==2) System.out.println("You have a pair"); } if(currentFace == "4");{ //int sameCards4=0; sameCards4++; if(sameCards4==2) System.out.println("You have a pair"); } if(currentFace == "3");{ //int sameCards3=0; sameCards3++; if(sameCards3==2) System.out.println("You have a pair"); } if(currentFace == "2");{ //int sameCards2=0; sameCards2++; if(sameCards2==2) System.out.println("You have a pair"); } //System.out.println(currentFace);
This is what I'm TRYING to do. I know that this isn't effective OR efficient, but I wanted to test to see if it would even read the String face. It doesn't work. It just prints the cards out, which leads me to believe that it's not comparing the sameCards to the face value or my while loop isn't working properly strcmp() is your friend. to be honest though this seems like something you could #define nicely like #define ACE 0 #define ONE 1 ... #define KING 13 Then just use that as your 'face' value and just == the ints, you could also have an int array instead of all those different variables just do something like: int array[14] = {0} array[ACE]++ which is much clearer and easier to make sense of than all those variables. Also don't you have to do TEXT("blah") or is that just a C / Win32 thing?? Edit: Just saw your second post and I'm shouting C at your when you're doing Java. My bad, long day but the idea still stands, you can't compare strings like that. It will compare the address of the String I think ( I dont know Java very well ), there will be some kind of string compare function that you should use over == I really liked C lol. I'm not understanding this object oriented crap very well. Umm, you can use different print functions in java which is pretty neat. You can print the actual object instead of needing the quotes
Just wanted to mention in java, you want to use "blah".equals("6") and not == because == is checking whether they refer to the same object.
Also, I finally decided to look into whether switch statements were really slower than if/else since I have seen a few people mention it (including one of my professors though in reference to C++). Apparently in java, this is not the case. http://stackoverflow.com/questions/6705955/why-switch-is-faster-than-if
|
On February 23 2013 04:56 DumJumJmyWum wrote:Show nested quote +On February 23 2013 04:42 ranshaked wrote:On February 23 2013 04:22 adwodon wrote:On February 23 2013 04:07 ranshaked wrote:+ Show Spoiler + public Card dealCard() { while( currentCard < 5) { String currentFace = deck[currentCard].getface(); System.out.printf("%s\n", deck[currentCard] ; int sameCardsKing=0, sameCardsQueen=0, sameCardsJack=0, sameCards10=0, sameCards9=0, sameCards8=0, sameCards7=0, sameCards6=0, sameCards5=0; int sameCards4=0, sameCards3=0, sameCards2=0, sameCardsAce=0; if(currentFace == "Ace");{ //int sameCardsAce=0; sameCardsAce++; if(sameCardsAce==2) System.out.println("You have a pair"); } if(currentFace == "King");{ //int sameCardsKing=0; sameCardsKing++; if(sameCardsKing==2) System.out.println("You have a pair"); } if(currentFace == "Queen");{ //int sameCardsQueen=0; sameCardsQueen++; if(sameCardsQueen==2) System.out.println("You have a pair"); } if(currentFace == "Jack");{ //int sameCardsJack=0; sameCardsJack++; if(sameCardsJack==2) System.out.println("You have a pair"); } if(currentFace == "10");{ //int sameCards10=0; sameCards10++; if(sameCards10==2) System.out.println("You have a pair"); } if(currentFace == "9");{ //int sameCards9=0; sameCards9++; if(sameCards9==2) System.out.println("You have a pair"); } if(currentFace == "8");{ //int sameCards8=0; sameCards8++; if(sameCards8==2) System.out.println("You have a pair"); } if(currentFace == "7");{ //int sameCards7=0; sameCards7++; if(sameCards7==2) System.out.println("You have a pair"); } if(currentFace == "6");{ //int sameCards6=0; sameCards6++; if(sameCards6==2) System.out.println("You have a pair"); } if(currentFace == "5");{ //int sameCards5=0; sameCards5++; if(sameCards5==2) System.out.println("You have a pair"); } if(currentFace == "4");{ //int sameCards4=0; sameCards4++; if(sameCards4==2) System.out.println("You have a pair"); } if(currentFace == "3");{ //int sameCards3=0; sameCards3++; if(sameCards3==2) System.out.println("You have a pair"); } if(currentFace == "2");{ //int sameCards2=0; sameCards2++; if(sameCards2==2) System.out.println("You have a pair"); } //System.out.println(currentFace);
This is what I'm TRYING to do. I know that this isn't effective OR efficient, but I wanted to test to see if it would even read the String face. It doesn't work. It just prints the cards out, which leads me to believe that it's not comparing the sameCards to the face value or my while loop isn't working properly strcmp() is your friend. to be honest though this seems like something you could #define nicely like #define ACE 0 #define ONE 1 ... #define KING 13 Then just use that as your 'face' value and just == the ints, you could also have an int array instead of all those different variables just do something like: int array[14] = {0} array[ACE]++ which is much clearer and easier to make sense of than all those variables. Also don't you have to do TEXT("blah") or is that just a C / Win32 thing?? Edit: Just saw your second post and I'm shouting C at your when you're doing Java. My bad, long day but the idea still stands, you can't compare strings like that. It will compare the address of the String I think ( I dont know Java very well ), there will be some kind of string compare function that you should use over == I really liked C lol. I'm not understanding this object oriented crap very well. Umm, you can use different print functions in java which is pretty neat. You can print the actual object instead of needing the quotes Just wanted to mention in java, you want to use "blah".equals("6") and not == because == is checking whether they refer to the same object. Also, I finally decided to look into whether switch statements were really slower than if/else since I have seen a few people mention it (including one of my professors though in reference to C++). Apparently in java, this is not the case. http://stackoverflow.com/questions/6705955/why-switch-is-faster-than-if Yeah, I figured out the .equals stuff a few ago. I can't force the damn thing to switch.
Sigh, I've been working on just this conversion since 9am. I even went to the tutoring session (no TA showed up), and I'm just completely stuck.
|
Why not just use enums?
Sth like that:
public enum Face { TWO, THREE, ...., ACE }
Just by defining the enum elements in proper order, you fuel the built-in comparator , so Face.THREE.compareTo(Face.TWO) would return a positive integer, Face.TWO.compareTo(Face.TWO) would return a 0 and so on.
|
On February 23 2013 05:23 myzael wrote:Why not just use enums? Sth like that: public enum Face { TWO, THREE, ...., ACE }
Just by defining the enum elements in proper order, you fuel the built-in comparator , so Face.THREE.compareTo(Face.TWO) would return a positive integer, Face.TWO.compareTo(Face.TWO) would return a 0 and so on.
I'm not quite sure, but I'm choosing these cards out of a deck that has been randomized.
If anyone can help me in PM so I don't clutter this that would be great.
If I did
private enum Face { TWO, THREE,FOUR,FIVE,SIX,SEVEN,EIGHT,NINE,TEN,JACK,QUEEN,KING,ACE}//like this? //or like this private enum Face{2,3,4,5,6,7,8,9,10,11,12,13,14}
//then do switch(Face) case 2: faceValue=2; break; //idk?
|
Do you need specific integer values of card faces or just to compare card faces between them? What is the overall goal?
Enum names must be valid java variable names, so 2, 3, etc won't work...
Missed the PM part. Feel free to PM me, I have a help a noobie day
|
Nobody here ever needs PL/SQL help, which is pretty much all I do these days.
|
Here I wrote this for you guys in C, I'm sure a Java equivalent can be concocted pretty easily:
// Returns -1 if lhs is larger, 0 if equavilant, and 1 if rhs is larger // Assumes lhs and rhs are both strings with only decimal digits, e.g. "123" or "12005" // Also assumes there are no preceding zeros like so: "0052" int IntegerAsStringCompare( const char *lhs, const char *rhs ) { int lhs_len = strlen( lhs ); int rhs_len = strlen( rhs ); // Early out with string lengths if(lhs_len > rhs_len) return -1; else if(rhs_len > lhs_len) return 1;
// Strings are equal length, compare each digit one by one else { // lhs and rhs are equal length, so no need for comparison // to have lhs && rhs while(lhs) { if(*lhs > *rhs) return -1; else if(*rhs > *lhs) return 1; ++lhs; ++rhs; } // Our numbers are equivalent return 0; } }
|
Ignore the static declaration (just needed to run with the main)
import java.util.Random;
public class Card { //The variables static String names[] = {"Ace","Two","Three","Four","Five","Six","Seven", "Eight","Nine","Ten","Jack","Queen","King"}; static int values[] = {1,2,3,4,5,6,7,8,9,10,11,12,13}; //Const value static final int THIRTEEN = 13; //Function to make the comparison static public int getValue(String value) { int returnValue = 0; for(int x = 0; x < THIRTEEN;x++) { if(names[x].equals(value)) { returnValue = values[x]; break; } } return returnValue; } //-----------------------------------------------------------------------------------
//Test to run the program static public void RunTest() { Random r = new Random(); int index = 0; String temp = ""; for(int x = 0; x < 100; x++) { index = r.nextInt(13); temp = names[index]; System.out.println(temp + " - " + getValue(temp)); } }
//Main public static void main(String args[]) { RunTest(); }
The function to make the comparison is what you want I believe. Basically, we hold the predefined card names and values in arrays (i made two separate array for simplicity, but a 2 dimensional array would have made more sense).
We are handed a string value, we loop through our array of strings, to see if it exists. If it does, we take the index number, and get the value of that string, from the value array, using that index number (Index 0 = Ace/1, Index 1 = Two/2, etc). The "break" in the code just tells the function to exit the loop prematurely, since we found a match and therefore no longer need to loop any further.
The test program just shows you it works. You could do this a lot of different ways, and I'm not sure of your ultimate goal here, but the function provided should be what you want.
|
I saw earlier someone mentioned enums and you weren't sure how to convert your Strings to enums. You do this with the method valueOf(String). The cavaet is that valueOf simply looks at the name of the enum as you defined it, and they're typically in all caps. However, you can get around this problem by simply converting the String you're trying to lookup to caps before doing the valueOf() call.
+ Show Spoiler [Code] + import java.util.LinkedHashSet; import java.util.Set;
public class Cards { public enum Rank { ACE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING } private static void testMe () { //LinkedHashSet to maintain order Set<String> rankStrings = new LinkedHashSet<String>(); rankStrings.add("Ace"); rankStrings.add("Two"); rankStrings.add("Three"); rankStrings.add("Four"); rankStrings.add("Five"); rankStrings.add("Six"); rankStrings.add("Seven"); rankStrings.add("Eight"); rankStrings.add("Nine"); rankStrings.add("Ten"); rankStrings.add("Jack"); rankStrings.add("Queen"); rankStrings.add("King"); for (String rank: rankStrings) System.out.printf("%s has value %d\n", rank, Rank.valueOf(rank.toUpperCase()).ordinal()); } public static void main (String [] args) { testMe(); }
}
Which produces the output: + Show Spoiler [Output] + Ace has value 0 Two has value 1 Three has value 2 Four has value 3 Five has value 4 Six has value 5 Seven has value 6 Eight has value 7 Nine has value 8 Ten has value 9 Jack has value 10 Queen has value 11 King has value 12
There are a few benefits to Enums, namely their type safety. A constructor that takes (Rank, Suit) is easier to understand and harder to pass the wrong values into than a constructor that takes (int, int) or (String, String). If you try to create an enum out of an invalid String (e.g. valueOf("Zebra")), it'll throw an exception instead of making you check. If you had written a constructor that takes in (int, int), you'd have to make sure someone doesn't pass in -99 or some other nonsense number.
For your specific case, you can easily compare enum values by using the enum.compareTo(enum) method.
You can use them in switch statements, and you can also attach additional values to enums easily (e.g. if you were to assign each card a specific weight beyond their natural ordering).
If you want to read more, I'd take a look at the java tutorial about them.
|
You can put arbitrary stuff into an enum. You don't need to use valueOf(String), you can just define a new method fromString(String) or something.
enum Foo { ACE("ace"), TWO("two"), ....
private final String name;
Foo(String name) { this.name = name }
static Foo fromString(String string) { ... do some shit here } }
|
I'm sorry, maybe I'm retarded, but if you're using Java why not just use a hashmap?
A hashmap will map Strings to Integers, so all you'd have to say in hashmap.get("Ace") or hashmap.get("King")...
They're optimized for setting and retrieving, they're really easy to debug and are perfect for this situation. Am i missing something here?
Also, I never understood these ridiculous worries about "performance" between using a switch and an if. I understand concerns about using an algorithms that's O(logn) vs one that's O(n) for finding primes in the range of trillions... I get that. The performance gains between using if/else vs switch are so minuscule they are almost irrelevant. In fact, I'd use a switch just because it's so much more readable. (Actually I'd use function pointers, but that's besides the point)
|
You are exactly right, performance arguments like this are always pointless. Even if this were not for a class (which it must be), arguing against a switch statement is silly. Unless you've gone through and figured out that that segment of code is bottlenecking you on CPU, refactoring out a switch statement is a waste of time. (You're more likely to find CPU hits on large string serializations for debug print statements than for a switch)
As for which solution is the right one (enum switch, hash, whatever), it's entirely up to what the asker has been exposed to in class. If he's weeks ahead of even learning about what a hashmap / dictionary is, then it's maybe not the best use of his time to explore that right now. If they've learned enums, an enum with a string field is a natural extension. If they've already covered hashmap, then yea...
|
Yo Phar I'm wondering how you implement the fromString (String...) method without using either some dictionary or looping through every enum every lookup (e.g. looping over values() and checking to see which one has a matching String). I was going to recommend the same idea except for this problem. Is there any way to invoke the Foo constructor - I thought it was only private but when I tried to code it up, I got errors for calling it in a method similar to fromString().
|
On February 23 2013 16:17 teamamerica wrote: Yo Phar I'm wondering how you implement the fromString (String...) method without using either some dictionary or looping through every enum every lookup (e.g. looping over values() and checking to see which one has a matching String). I was going to recommend the same idea except for this problem. Is there any way to invoke the Foo constructor - I thought it was only private but when I tried to code it up, I got errors for calling it in a method similar to fromString().
Enums are a tad weird compared to regular classes. The constructor is used to create the static enum entries (so in the case of phar's example, you can see the constructor being called for ACE and TWO). These enum entries then have all the methods you placed in the enum definition, but you won't be able to construct new ones at runtime. You have a lot of options as to how to implement the fromString method (a lot of the stuff people mentioned outside of the enum implementation applies here). I think the easiest way is probably using a hashmap, which would look like:
public enum Card { ACE("Ace", 1), TWO("Two", 2), THREE("Three", 3) // etc. ;
private static final HashMap<String,Card> mNameMap = new HashMap<String,Card>(); static { for(Card c : EnumSet.allOf(Card.class)) { mNameMap.put(c.getName().toLowerCase(), c); } }
private final String mName; private final int mValue;
Card(String name, int value) { mName = name; mValue = value; }
public String getName() { return mName; }
public int getValue() { return mValue; }
public static Card fromString(String name) { return mNameMap.get(name.toLowerCase()); } }
This doesn't provide a whole lot of functionality over using valueOf, but it does keep the knowledge of how your card names are mapped (lowercase, in this case) completely internal to your enum instead of leaking that info everywhere you use it.
|
Yes exactly, and I would recommend trying this only if whoever asked the question just learned enums and is supposed to be using them to solve this question. It's a little trick you can do with enums that will make the assignment marginally less boring. It's by no means the best of designs (to be frank, I just finished refactoring some 2-year old code to get rid of this exact pattern because it suuucckked).
I'm just kind of guessing as to whether or not they learned enums in preparation for this.
|
|
|
|
|
|