Advertisement
Guest User

Untitled

a guest
Nov 19th, 2019
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.56 KB | None | 0 0
  1. public class Card {
  2. public final static String[] SUITS = { "Diamonds", "Clubs", "Hearts", "Spades" };
  3. public final static String[] RANKS = { "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King",
  4. "Ace" };
  5.  
  6. // Declare two private integers, suit and rank.
  7. private int suit;
  8. private int rank;
  9.  
  10. /**
  11. * Call the setSuit and setRank methods, passing the suit and rank arguments respectively.
  12. *
  13. * @param suit, an integer representing the index of the SUITS array
  14. * @param rank, an integer representing the index of the RANKS array
  15. */
  16. public Card(int suit, int rank) {
  17. setSuit(suit);
  18. setRank(rank);
  19. }
  20.  
  21. /**
  22. * Checks if the rank is within the valid range, what is that range? prints an error otherwise. See expected output for details.
  23. *
  24. * @param rank
  25. */
  26. private void setRank(int rank) {
  27. if( rank >= 0 && rank <= 12 ){
  28. this.rank = rank;
  29. }else{
  30. System.out.println("Error: Invalid rank: " + rank);
  31. }
  32. }
  33.  
  34. /**
  35. * Checks if the suit is within the valid range, what is that range? prints an error otherwise. See expected output for details.
  36. */
  37. private void setSuit(int suit) {
  38. if( suit >= 0 && suit <= 3 ){
  39. this.suit = suit;
  40. }else{
  41. System.out.println("Error: Invalid suit: " + suit);
  42. }
  43. }
  44.  
  45. /**
  46. * @return int - the rank value of the Card instance
  47. */
  48. public int getRankIndex() {
  49. return rank;
  50. }
  51.  
  52. /**
  53. * @return The short name of the card, D7 for 7 of Diamands for instance.
  54. * Or, DT for 10 of Diamonds
  55. * Or, DQ for Queen
  56. */
  57. public String getShortName() {
  58. // Hint, how do you get the first character of a String?
  59. String shortName = "";
  60. shortName += SUITS[suit].charAt(0);
  61.  
  62. if( rank == 8 ){
  63. shortName += "T";
  64. }else{
  65. shortName += RANKS[rank].charAt(0);
  66. }
  67. return shortName;
  68. }
  69.  
  70. @Override
  71. public String toString() {
  72. String retVal = "";
  73.  
  74. retVal += RANKS[rank] + " of " + SUITS[suit];
  75.  
  76. return retVal;
  77. }
  78.  
  79. public static void main(String[] args) {
  80. Card c = new Card(-1, 0);
  81. c = new Card(0, -1);
  82. c = new Card(4, 0);
  83. c = new Card(0, 13);
  84.  
  85. c = new Card(2, 10);
  86. System.out.println(c.getShortName());
  87. System.out.println(c);
  88. System.out.println(c.getRankIndex());
  89. }
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement