• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EST 05:46
CET 11:46
KST 19:46
  • Home
  • Forum
  • Calendar
  • Streams
  • Liquipedia
  • Features
  • Store
  • EPT
  • TL+
  • StarCraft 2
  • Brood War
  • Smash
  • Heroes
  • Counter-Strike
  • Overwatch
  • Liquibet
  • Fantasy StarCraft
  • TLPD
  • StarCraft 2
  • Brood War
  • Blogs
Forum Sidebar
Events/Features
News
Featured News
Rongyi Cup S3 - Preview & Info3herO wins SC2 All-Star Invitational14SC2 All-Star Invitational: Tournament Preview5RSL Revival - 2025 Season Finals Preview8RSL Season 3 - Playoffs Preview0
Community News
Weekly Cups (Jan 19-25): Bunny, Trigger, MaxPax win1Weekly Cups (Jan 12-18): herO, MaxPax, Solar win0BSL Season 2025 - Full Overview and Conclusion8Weekly Cups (Jan 5-11): Clem wins big offline, Trigger upsets4$21,000 Rongyi Cup Season 3 announced (Jan 22-Feb 7)25
StarCraft 2
General
Oliveira Would Have Returned If EWC Continued Weekly Cups (Jan 19-25): Bunny, Trigger, MaxPax win StarCraft 2 not at the Esports World Cup 2026 herO wins SC2 All-Star Invitational PhD study /w SC2 - help with a survey!
Tourneys
$21,000 Rongyi Cup Season 3 announced (Jan 22-Feb 7) OSC Season 13 World Championship $70 Prize Pool Ladder Legends Academy Weekly Open! SC2 All-Star Invitational: Jan 17-18 Sparkling Tuna Cup - Weekly Open Tournament
Strategy
Simple Questions Simple Answers
Custom Maps
[A] Starcraft Sound Mod
External Content
Mutation # 510 Safety Violation Mutation # 509 Doomsday Report Mutation # 508 Violent Night Mutation # 507 Well Trained
Brood War
General
[ASL21] Potential Map Candidates BGH Auto Balance -> http://bghmmr.eu/ Which foreign pros are considered the best? Gypsy to Korea Fantasy's Q&A video
Tourneys
[Megathread] Daily Proleagues Azhi's Colosseum - Season 2 Small VOD Thread 2.0 [BSL21] Non-Korean Championship - Starts Jan 10
Strategy
Current Meta Simple Questions, Simple Answers Soma's 9 hatch build from ASL Game 2 Game Theory for Starcraft
Other Games
General Games
Beyond All Reason Nintendo Switch Thread Battle Aces/David Kim RTS Megathread Stormgate/Frost Giant Megathread Awesome Games Done Quick 2026!
Dota 2
Official 'what is Dota anymore' discussion
League of Legends
Bring back your lost lover Australia+27734009912
Heroes of the Storm
Simple Questions, Simple Answers Heroes of the Storm 2.0
Hearthstone
Deck construction bug Heroes of StarCraft mini-set
TL Mafia
Vanilla Mini Mafia Mafia Game Mode Feedback/Ideas
Community
General
US Politics Mega-thread YouTube Thread Russo-Ukrainian War Thread Canadian Politics Mega-thread European Politico-economics QA Mega-thread
Fan Clubs
The herO Fan Club! The IdrA Fan Club
Media & Entertainment
Anime Discussion Thread [Manga] One Piece
Sports
2024 - 2026 Football Thread
World Cup 2022
Tech Support
Computer Build, Upgrade & Buying Resource Thread
TL Community
The Automated Ban List
Blogs
How Esports Advertising Shap…
TrAiDoS
My 2025 Magic: The Gathering…
DARKING
Life Update and thoughts.
FuDDx
How do archons sleep?
8882
James Bond movies ranking - pa…
Topin
Customize Sidebar...

Website Feedback

Closed Threads



Active: 1671 users

The Big Programming Thread - Page 253

Forum Index > General Forum
Post a Reply
Prev 1 251 252 253 254 255 1032 Next
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.
ranshaked
Profile Blog Joined August 2010
United States870 Posts
February 22 2013 19:07 GMT
#5041

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
ranshaked
Profile Blog Joined August 2010
United States870 Posts
Last Edited: 2013-02-22 19:13:11
February 22 2013 19:12 GMT
#5042
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
adwodon
Profile Blog Joined September 2010
United Kingdom592 Posts
Last Edited: 2013-02-22 19:29:53
February 22 2013 19:22 GMT
#5043
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 ==
adwodon
Profile Blog Joined September 2010
United Kingdom592 Posts
Last Edited: 2013-02-22 19:23:57
February 22 2013 19:23 GMT
#5044
sorry hit reply instead of edit.
ranshaked
Profile Blog Joined August 2010
United States870 Posts
February 22 2013 19:42 GMT
#5045
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
DumJumJmyWum
Profile Joined March 2011
United States75 Posts
Last Edited: 2013-02-22 19:57:19
February 22 2013 19:56 GMT
#5046
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
ranshaked
Profile Blog Joined August 2010
United States870 Posts
February 22 2013 20:20 GMT
#5047
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.
myzael
Profile Blog Joined November 2008
Poland605 Posts
Last Edited: 2013-02-22 20:23:49
February 22 2013 20:23 GMT
#5048
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.
ranshaked
Profile Blog Joined August 2010
United States870 Posts
February 22 2013 20:33 GMT
#5049
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?




myzael
Profile Blog Joined November 2008
Poland605 Posts
Last Edited: 2013-02-22 22:58:19
February 22 2013 22:57 GMT
#5050
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
Craton
Profile Blog Joined December 2009
United States17274 Posts
February 22 2013 23:05 GMT
#5051
Nobody here ever needs PL/SQL help, which is pretty much all I do these days.
twitch.tv/cratonz
CecilSunkure
Profile Blog Joined May 2010
United States2829 Posts
Last Edited: 2013-02-22 23:26:19
February 22 2013 23:23 GMT
#5052
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;
}
}
killa_robot
Profile Joined May 2010
Canada1884 Posts
Last Edited: 2013-02-22 23:44:04
February 22 2013 23:42 GMT
#5053
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.
teamamerica
Profile Blog Joined July 2010
United States958 Posts
February 23 2013 00:27 GMT
#5054
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.
RIP GOMTV. RIP PROLEAGUE.
phar
Profile Joined August 2011
United States1080 Posts
February 23 2013 02:27 GMT
#5055
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
}
}
Who after all is today speaking about the destruction of the Armenians?
Abductedonut
Profile Blog Joined December 2010
United States324 Posts
February 23 2013 06:13 GMT
#5056
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)
phar
Profile Joined August 2011
United States1080 Posts
Last Edited: 2013-02-23 06:29:23
February 23 2013 06:27 GMT
#5057
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...
Who after all is today speaking about the destruction of the Armenians?
teamamerica
Profile Blog Joined July 2010
United States958 Posts
February 23 2013 07:17 GMT
#5058
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().

RIP GOMTV. RIP PROLEAGUE.
tec27
Profile Blog Joined June 2004
United States3702 Posts
February 23 2013 10:15 GMT
#5059
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.
Can you jam with the console cowboys in cyberspace?
phar
Profile Joined August 2011
United States1080 Posts
February 23 2013 19:19 GMT
#5060
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.
Who after all is today speaking about the destruction of the Armenians?
Prev 1 251 252 253 254 255 1032 Next
Please log in or register to reply.
Live Events Refresh
Replay Cast
09:00
Rongyi Cup S3 - Playoffs Day 1
CranKy Ducklings93
LiquipediaDiscussion
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
RotterdaM 288
SortOf 158
Rex 21
StarCraft: Brood War
Calm 2008
Rain 1486
Hyuk 1303
Flash 1286
GuemChi 578
Jaedong 530
Soma 310
Hyun 305
Stork 281
BeSt 249
[ Show more ]
Mong 205
JulyZerg 199
Larva 159
ZerO 158
Light 153
Killer 152
Snow 126
Rush 92
EffOrt 82
Dewaltoss 62
Noble 52
hero 51
Backho 41
Hm[arnc] 36
Sacsri 30
Shuttle 29
ToSsGirL 27
HiyA 26
[sc1f]eonzerg 24
soO 22
sorry 19
zelot 18
GoRush 17
Bale 13
Dota 2
Gorgc3227
Fuzer 153
XcaliburYe129
NeuroSwarm90
League of Legends
JimRising 771
C9.Mang0360
Counter-Strike
zeus604
Other Games
singsing1665
Liquid`RaSZi886
olofmeister859
ceh9536
crisheroes257
Sick181
Pyrionflax142
Mew2King82
B2W.Neo31
Organizations
StarCraft: Brood War
Kim Chul Min (afreeca) 939
Other Games
gamesdonequick860
StarCraft: Brood War
lovetv 8
StarCraft 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
sctven
[ Show 15 non-featured ]
StarCraft 2
• LUISG 24
• AfreecaTV YouTube
• intothetv
• Kozan
• IndyKCrew
• LaughNgamezSOOP
• Migwel
• sooper7s
StarCraft: Brood War
• iopq 7
• BSLYoutube
• STPLYoutube
• ZZZeroYoutube
League of Legends
• Nemesis6065
• Lourlo1066
• Stunt492
Upcoming Events
RongYI Cup
14m
Clem vs TriGGeR
Maru vs Creator
RotterdaM288
WardiTV106
Rex21
WardiTV Invitational
3h 14m
PiGosaur Cup
14h 14m
Replay Cast
22h 14m
RongYI Cup
1d
herO vs Solar
WardiTV Invitational
1d 3h
The PondCast
1d 22h
HomeStory Cup
3 days
Korean StarCraft League
3 days
HomeStory Cup
4 days
[ Show More ]
Replay Cast
4 days
HomeStory Cup
5 days
Replay Cast
5 days
Replay Cast
6 days
Liquipedia Results

Completed

Proleague 2026-01-26
OSC Championship Season 13
Underdog Cup #3

Ongoing

CSL 2025 WINTER (S19)
KCM Race Survival 2026 Season 1
Acropolis #4 - TS4
Rongyi Cup S3
BLAST Bounty Winter 2026
BLAST Bounty Winter Qual
eXTREMESLAND 2025
SL Budapest Major 2025
ESL Impact League Season 8
BLAST Rivals Fall 2025

Upcoming

Escore Tournament S1: W6
Escore Tournament S1: W7
Acropolis #4
IPSL Spring 2026
uThermal 2v2 2026 Main Event
Bellum Gens Elite Stara Zagora 2026
LiuLi Cup: 2025 Grand Finals
HSC XXVIII
Nations Cup 2026
PGL Bucharest 2026
Stake Ranked Episode 1
BLAST Open Spring 2026
ESL Pro League Season 23
ESL Pro League Season 23
PGL Cluj-Napoca 2026
IEM Kraków 2026
TLPD

1. ByuN
2. TY
3. Dark
4. Solar
5. Stats
6. Nerchio
7. sOs
8. soO
9. INnoVation
10. Elazer
1. Rain
2. Flash
3. EffOrt
4. Last
5. Bisu
6. Soulkey
7. Mini
8. Sharp
Sidebar Settings...

Advertising | Privacy Policy | Terms Of Use | Contact Us

Original banner artwork: Jim Warren
The contents of this webpage are copyright © 2026 TLnet. All Rights Reserved.