recently started learning java, going through the official tutorial and would like to check that the below code is a valid and correct solution to the following exercise ( exercise 1
class Card{
// fields -------------------------------------------------------------------------------------------------------------
private static final String[] SUITS = {"Hearts", "Diamonds", "Spades", "Clubs"};
private static final String[] RANKS = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};
private String mySuit;
private String myRank;
private int cardSuit;
private int cardRank;
private boolean cardValid = false;
//constructors ---------------------------------------------------------------------------------------------------------
public Card (int suit, int rank){
cardSuit = suit;
cardRank = rank;
setMyCard(); // if card valid then set values of mySuit AND myRank, else will print warning message
}
// methods ------------------------------------------------------------------------------------------------------------
public String getCard(){
String returnString = "";
if (cardValid == true){
String suit = getSuit();
String rank = getRank();
returnString = ("Your card is the " + rank + " of " + suit + "!");
}
return returnString;
}
public String getSuit(){
return mySuit;
}
public String getRank(){
return myRank;
}
public boolean isValidSuit(){
// check suit passed to constructor is valid -- i.e 1 to 4
if (cardSuit >=1 && cardSuit <= 4){
return true;
}
else {return false;}
}
public boolean isValidRank(){
// check rank passed to constructor is valid -- i.e 1 to 13
if (cardRank >=1 && cardRank <= 13){
return true;
}
else {return false;}
}
public void setMyCard(){
// if suit AND rank valid, then set mySuit AND myRank to valid string from suits[] and ranks[]
if ( isValidSuit() && isValidRank() ){
mySuit = SUITS[cardSuit - 1];
myRank = RANKS[cardRank - 1];
cardValid = true;
} else{ System.out.println("Invalid card");}
}
public static void main(String[] args){
Card newCard = new Card(3, 1); // create new ace of spades card
System.out.print(newCard.getCard()); // print info about card
System.out.println();
}
}