Click here to Skip to main content
15,896,497 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello guys,

I am having trouble understanding the concept of constructors. I have to create the following program as you can see I have greatly messed up. Any help would be greatly appreciated. Thank you!

Problem 2: Card Object
Create a class that represents a playing card. Playing cards have two attributes, a suit and a rank. Include a public
parameterized constructor that sets the card to have a suit and a rank. Include getters to access the suit and rank, but
you should not include setters to change them once they are created.
Include a test main that demonstrates that your class works.

C#
package getcard;
import java.util.Scanner;
class CardObject{
    private int suit;
    private int rank;

   public CardObject(int new_suit,int new_rank){
       suit=new_suit;
       rank=new_rank;

       }
   public static void ArrayCard(CardObject c){
       String[] suits={"Clubs","Diamonds","Hearts","Spades"};//http://www.oopweb.com/Java/Documents/ThinkCSJav/Volume/chap11.htm
       String[] ranks={"","Ace","2","3","4","5","6","7","8","9","10","Jack","Queen","King"};
       Scanner in=new Scanner(System.in);
        System.out.println("Enter an integer from 1 to 4 for a suit");
        int new_suit=in.nextInt();
        System.out.println("Enter an integer from 1 to 13 for a rank");
        int new_rank=in.nextInt();
        System.out.println("Your card is "+ranks[c.rank]+ "of" +suits[c.suit]);
Posted

1 solution

Rather than using an integer value for the suits, you should use enum types. Your string values should also be part of your class, that allows the class's getter method to return the card details. See http://docs.oracle.com/javase/tutorial/java/index.html[^] for some further help.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900