CardGame is a game of mental skill, built on the simple premise of adding and removing the cards from the top of the card pile.
The details of the class CardGame are given below:
Class name: CardGame
Data members/instance variables:
cards[]: array to store integers as cards
cap: to store the maximum capacity of array
top: to store the index of the topmost element of the array
Methods/Member functions:
CardGame(int cc): constructor to initialize cap = cc and top = -1
void addCard(int v): to add the card at the top index if possible, otherwise display the message “CARD PILE IS FULL”
int drawCard(): to remove and return the card from the top index of the card pile, if any, else return the value -9999
void display(): to display all the cards of card pile
(i) Specify the class CardGame giving details of the functions void addCard(int) and int drawCard(). Assume that the other functions have been defined. The main() function and algorithm need not be written.
import java.util.Scanner;
class CardGame{
int cards[];
int cap;
int top;
public CardGame(int cc){
cap = cc;
top = -1;
cards = new int[cap];
}
public void addCard(int v){
if(top + 1 == cap)
System.out.println("CARD PILE IS FULL");
else
cards[++top] = v;
}
public int drawCard(){
if(top == -1)
return -9999;
return cards[top--];
}
public void display(){
if(top == -1)
System.out.println("CARD PILE IS EMPTY");
else{
for(int i = top; i >= 0; i--){
if(i == top)
System.out.println(cards[i] + "<--top");
else
System.out.println(cards[i]);
}
}
}
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("CARD PILE CAPACITY: ");
int c = Integer.parseInt(in.nextLine());
CardGame obj = new CardGame(c);
while(true){
System.out.println("1. ADD CARD");
System.out.println("2. DRAW CARD");
System.out.println("3. DISPLAY CARDS");
System.out.print("ENTER YOUR CHOICE: ");
int choice = Integer.parseInt(in.nextLine());
switch(choice){
case 1:
System.out.print("CARD VALUE: ");
int v = Integer.parseInt(in.nextLine());
obj.addCard(v);
break;
case 2:
v = obj.drawCard();
if(v == -9999)
System.out.println("CARD PILE IS EMPTY");
else
System.out.println("DRAWN CARD: " + v);
break;
case 3:
obj.display();
break;
default:
System.out.println("BYE");
return;
}
}
}
}
(ii) Name the entity described above and state its principle.
The entity described above is the stack data structure. It is based on the LIFO (Last In First Out) principle.