publicclassCard{publicstaticfinalString[]RANKS={null,"Ace","2","3","4","5","6","7","8","9","10","Jack","Queen","King"};publicstaticfinalString[]SUITS={"Clubs","Diamonds","Hearts","Spades"};privatefinalintrank;privatefinalintsuit;/** * Constructs a card of the given rank and suit. * * @param rank the rank * @param suit the suit */publicCard(intrank,intsuit){if(rank<1||rank>13){thrownewIllegalArgumentException("invalid rank: "+rank);}if(suit<0||suit>3){thrownewIllegalArgumentException("invalid suit: "+suit);}this.rank=rank;this.suit=suit;}/** * Constructs a card of the given rank and suit. * * @param rank string representation of the rank * @param suit string representation of the suit */publicCard(Stringrank,Stringsuit){this.rank=parseRank(rank);this.suit=parseSuit(suit);}/** * Compares this card with that card. * * @param that the card to compare * @return -1 if this card comes before that card, 0 if the two cards are * equal, or +1 if this card comes after that card */publicintcompareTo(Cardthat){intresult;if(this.suit<that.suit){result=-1;}elseif(this.suit>that.suit){result=1;}elseif(this.rank<that.rank){result=-1;}elseif(this.rank>that.rank){result=1;}else{result=0;}returnresult;}/** * Returns true if the given card has the same rank and same suit. * * @param obj the other Card * @return true if the two are equal; false otherwise */@Overridepublicbooleanequals(Objectobj){if(objinstanceofCard){Cardthat=(Card)obj;returnthis.rank==that.rank&&this.suit==that.suit;}returnfalse;}publicintgetRank(){returnthis.rank;}publicintgetSuit(){returnthis.suit;}/** * Determines the integer rank from the given string rank. * * @param str the string representation of the rank * @return the rank integer, or -1 if invalid */publicstaticintparseRank(Stringstr){for(inti=0;i<RANKS.length;i++){if(str.equals(RANKS[i])){returni;}}return-1;}/** * Determines the integer suit from the given string suit. * * @param str the string representation of the suit * @return the suit integer, or -1 if invalid */publicstaticintparseSuit(Stringstr){for(inti=0;i<SUITS.length;i++){if(str.equals(SUITS[i])){returni;}}return-1;}/** * Gets the card's index in a sorted deck of 52 cards. * * @return index of the card */publicintposition(){returnthis.suit*13+this.rank-1;}@OverridepublicStringtoString(){returnRANKS[this.rank]+" of "+SUITS[this.suit];}}
importjava.util.Scanner;publicclassUser{publicstaticvoidmain(String[]args){// read input from the userScannerin=newScanner(System.in);System.out.print("Enter a rank: ");StringrankStr=in.nextLine();System.out.print("Enter a suit: ");StringsuitStr=in.nextLine();// try to construct the cardCardcard;try{intrankInt=Integer.parseInt(rankStr);intsuitInt=Integer.parseInt(suitStr);card=newCard(rankInt,suitInt);}catch(NumberFormatExceptionexc){card=newCard(rankStr,suitStr);}System.out.println("Your card is: "+card);}}