Question

In: Computer Science

Java OVERVIEW This program primarily focuses on the implementation of a ArrayList type interface and the...

Java

OVERVIEW
This program primarily focuses on the implementation of a ArrayList type interface and the
necessary methods to implement the ArrayList. It also includes polymorphism and class
comparison.
INSTRUCTIONS
Your deliverable will be to turn in three files. The files will be named Card.java,
PremiumCard.java and the last file will be called CardArrayList.java.
For this assignment, any use of a data control structure other than a simple Arrary or String will
result in no credit. I am aware that this assignment could be done quite simply by the Collections
implementation of an ArrayList<> but the point of the assignment is to do it without the standard
implementation to get a feel for how they work “under the hood”.
COLLECTABLE CARD
While the primary goal of this assignment will be the implementation and use of a custom
ArrayList. The particular implementation we will use will focus on the idea of a simple collectable
card game.
For our card game, we will assume that every card has two values expressed as integers. Each
card will have power and a toughness rating. These numbers need to be a minimum of 1 and a
maximum of 100.
Cards then have a calculated cost attribute that comes from the formula below.
cost=[ ((2*power+toughness)^1/2)*10]
Rounded up to the nearest integer.

When comparing two cards, the one with the higher cost comes after the other unless they have
the same cost, in which case the one with the higher power comes after the other. If both cost and
power are equal then the higher toughness comes after. Only if all three values are equal would
the cards be considered equal.
{1,1:18|} < {1,2:20} < {2,1:23} < {5,5:39} < {5,6:40} < {5,7:42} < {6,5:42}
In addition there are some cards that are considered Premium cards. In a different problem,
these would be drawn graphically different on the screen, but for our purposes there will only be
a slight difference in the output of the card information. But this will give you some practice in
polymorphism.
PROGRAM DESCRIPTION
In this assignment you will construct an ArrayList that can manage a set of Cards which includes
both normal and premium cards. You will implement the various methods that are required in
order to make the ArrayList function.
A sample program will be provided for you to test with, but you may want to alter it to check
different functionality of your ArrayList.
YOUR INSTRUCTIONS
You will write the following classes, implementing the necessary methods as appropriate.
NECESSARY METHODS – CARD CLASS
The Card class will be your primary class to contain one particular card. It should have two interior fields
for power and toughness and should calculate the cost as needed. Do not store the cost as a field!’
Cards should correctly implement the comparable interface to other Cards as discussed in class using the
ordering described above.
PUBLIC CARD()
In the Card() constructor you create a random card with a random power and a random toughness within
the acceptable bounds given above.

PUBLIC CARD(INT X)
In the Card(int x) constructor you create a card that has equal power and toughness as long as the x
in within the proper bounds. If the input value is outside the bounds, then throw an appropriate exception.
PUBLIC CARD(INT P, INT T)
In the Card(int Power, int Toughness) constructor you create a card that has power and
toughness equal to the input values as long as they are within the proper bounds. If either input value is
outside the bounds, then throw an appropriate exception.
PUBLIC INT GETPOWER()
The getPower() should return the current power.
PUBLIC INT GETTOUGHNESS()
The getToughness() should return the current toughness.
PUBLIC INT GETCOST()
The getCost() should return the current cost, calculated by the current values.
PUBLIC STRING TOSTRING()
In the toString() should return a string that shows the current power, toughness, and cost of the card
in the form “ [12/30:74] ” where the first number is the power and the second number is the toughness
and the number after the “:” is the calculated cost.
PUBLIC VOID WEAKEN()
The weaken method should reduce the power and toughness of the card by 2 permanently. Note it still
needs to stay above 0.
PUBLIC VOID BOOST()
The boost() method should increase the power and toughness of the card by 2 permanently. Note it still
needs to stay below 101.

NECESSARY METHODS – PREMIUM CARD CLASS
The PremiumCard class will be a secondary type of card. In a more advanced program there would be
some extra work to implement this type of card graphically, but for this assignment, there is only one
overridden function that you need to implement. All other methods from card should work the same,
including comparison. However, you might have to include constructors that call the constructors from
Card .
PUBLIC STRING TOSTRING()
In the toString() for PremiumCards should return a string that shows the current power and toughness
of the card in the form “ {{12/30:74}} ” where the first number is the power and the second number is
the toughness and the last number is the cost.
NECESSARY METHODS – CARDARRAYLIST CLASS
The CardArrayList is the primary focus of this assignment. In it you will maintain a list of cards,
allowing for all the methods listed below to manage a list of cards.
The basic idea of the CardArrayList will be to keep track of an internal array of cards and a list of how
many of the array slots are currently being used. As values are added/removed to the internal array, you
will update the “size” field to keep track of how many are being used.
Should the user try to add a value to the array that would cause it to overflow, then you will need to
implement routines to create an array that is double the size of the current array, then copy the current array
into the new array, then replace the old array with the new array. When that is done, then you may complete
the original operation that caused the resize.
However, we want to be able to change the type of list in the future, so your CardArrayList will need
to implement the CardList interface in order to work. So while the CardList interface is provided for
you, you will need to make sure that your program properly implements it.
PUBLIC CARDARRAYLIST ()
In the CardArrayList() constructor should create an initial array of size 10, and set the internal size
counter to zero to represent that none of the spaces are currently being used.
PUBLIC CARDARRAYLIST (INT X)
In the CardArrayList() constructor should create an initial array of size x, and set the internal size
counter to zero to represent that none of the spaces are currently being used. If x is less than one, throw an
appropriate exception.

PUBLIC STRING TOSTRING ()
The toString() method should print the current values of the arraylist being stored. It should surround
the entire arraylist inside [0: :size] with commas between the values. A sample output might look like.
[0: [2/3:27],[4/10:43],[5/4:38],{{10/10:55}},[3/4:32],{{8/8:49}} :6]
Note the 6 to show the current size. If the array is empty it should print out:
[0: :0]
PUBLIC INT SIZE ()
In the size() method, you should return the current number of elements being stored in the array. Not
the size of the array, but how many elements it is currently holding.
PUBLIC VOID ADD (CARD X)
In the add() method, you should add the card provided to the array list in the last empty location and
increment the size counter. Note that this may require a resize before running.
PUBLIC CARD REMOVE ()
In the remove() method, you should return the last element from the array list. You should then
decrement the size counter by one to show that we don’t care about that element anymore. You don’t
actually have to delete it, it effectively gets removed by being ignored.
Make sure to return the Card as you exit however so it can be used by the internal program.
PUBLIC CARD GET (INT X)
In the get(int x) method, you should return the card located in the array at the x location. This
method does not delete the element; it just returns the current value. If x is outside the bounds of the array,
throw an appropriate exception.

PUBLIC INT INDEXOF (CARD X)
In the indexOf() method, you should return the location of the first card that is “equal” to the card that
is provided. If it isn’t found, return -1. Note that the card found may not match the card given precisely
due to the unusual comparison of cards.
PUBLIC VOID ADD (INT L, CARD X)
In the add(location,x) method, you should add the card(x) provided to the array list in location x.
However because the location is inside the array, you will need to move everything after the location over
one spot. So you will need to move everything to make room, then add x into location. Note that this may
require a resize before running. Make sure that x is inside the current array OR at the end, do not extend
the array more than one value. Make sure to alter the size counter as appropriate. If x is outside the bounds
of the array plus one, throw an appropriate exception.
PUBLIC CARD REMOVE (INT J)
In the remove(int j) method, you should remove the element from the array list in location j and then
return it. However in this method, the item may be in the middle of the array, so you will need to store the
item, then move everything after the item to the left one spot, then adjust the size counter. If j is outside the
bounds of the array in use, throw an appropriate exception.
Make sure to return the Card as you exit however so it can be used by the internal program. Hint: you will
need a temp holder to hold the return card while you are readjusting the array.
PUBLIC VOID SORT ()
The sort() method should simply sort the array from smallest to largest. However I want you to
implement your own version of the merge sort. Do not use Arrays.sort().
Also, keep in mind that you will not be sorting the entire array. Your array might be size 100 but you are
only using 60 elements currently. Your merge sort should take into account that you are only sorting a
section of an array.
PUBLIC VOID SHUFFLE()
The shuffle() method should shuffle the array into a non-ordered arrangement. One way of doing this
is picking two random numbers within the size of the array, and then swapping those two values. Then
repeat this process a bunch of times. (For example five times the number of elements in the arraylist). Also
make sure that you are only shuffling the part of the array that you are using, and not the "empty" array
elements.
Note that this isn’t mathematically a good shuffle, but it will work for our purposes.

PRIVATE BOOLEAN ISROOM ()
A good idea for your class is to create a private isRoom() method that will check to see if adding one
more element will require the array to grow. This way you can use this method before accidently adding a
value that will cause and overflow.
PRIVATE VOID EXPAND()
A good idea for your class is to create a private expand() method that will double the size of your array
and then copy the old array into the new array for storage. This should not change the value of the size
counter, just make it big enough for added storage.
PRIVATE VOID SWAP(INT A, INT B)
A good idea for your class is to create a private swap(a,b) method that will swap two cards around as
necessary. Helpful for methods above.
PUBLIC VOID CLEAR()
clear() method should reset your size and array back to an initial size(10), basically deleting the entire
arrayList.
NOTES
Chapter 15 contains a number of ideas on how to implement an ArrayList of numbers, so do not be afraid
to consult the chapter for hints/ideas.
The testing program is divided up into stages. Comment out the stages that you haven’t finished and work
on things step by step.
STYLE GUIDELINES AND GRADING:
Part of your grade will come from appropriately utilizing object methods.
Your class may have other methods besides those specified, but any other methods you add should be
private.
You should follow good general style guidelines such as: making fields private and avoiding unnecessary
fields; declaring collection variables using interface types; appropriately using control structures like

loops and if/else; properly using indentation, good variable names and types; and not having any lines of
code longer than 100 characters.
Comment your code descriptively in your own words at the top of your class, each method, and on
complex sections of your code. Comments should explain each method's behavior, parameters, return, and
exceptions.

Solutions

Expert Solution

Solution :

Below is the code for all 3 class with proper comments. I modified shuffle method in CardsArrayList.java class since it is better way to do it. please rate my answer

Card.java

package cards;

import java.util.Random;

/**
* Card class
*
*/
public class Card {

private int power;
private int toughness;

/**
* Empty Constructor
*/
public Card() {
power = new Random().nextInt(1000);
toughness = new Random().nextInt(1000);
}

/**
* Constructor takes in value and create new card
*
* @param x
* @throws Exception
*/
public Card(int x) throws Exception {
if (x <= 1 && x >= 1000) {
throw new Exception("power/toughness is out of bounds 1 and 1000");
} else {
power = x;
toughness = x;
}

}

/**
* Constructor takes in value for power and toughness and create new card
*
* @param x
* @throws Exception
*/
public Card(int p, int t) throws Exception {
if ((p <= 1 && p >= 1000) || (t <= 1 && t >= 1000)) {
throw new Exception("power/toughness is out of bounds 1 and 1000");
} else {
power = p;
toughness = t;
}
}

/**
* method returns power of card
*
* @return power
*/

public int getPower() {
return power;
}

/**
* method returns toughness of card
*
* @return toughness
*/
public int getToughness() {
return toughness;
}

/**
* method returns cost of card
*
* @return cost
*/
public int getCost() {
return (int) Math.sqrt((1.5 * power) + (0.9 * toughness));
}

/*
* (non-Javadoc)
*
* @see java.lang.Object#toString() */
public String toString() {
return "[" + power + "/" + toughness + "]";
}

/**
* method reduces power and toughness of card by ten percent
*/
public void weaken() {
power = (int) (power - power * 0.1);
toughness = (int) (toughness - toughness * 0.1);

}

/**
* method increases power and toughness of card by ten percent
*/
public void boost() {
power = (int) (power + power * 0.1);
toughness = (int) (toughness + toughness * 0.1);
}

}

PremiumCard.java

package cards;

import java.util.Random;
/**
*
* Premium card class
* @author
*
*/
public class PremiumCard extends Card {

private int power;
private int toughness;

/**
* Empty Constructor
*/
public PremiumCard() {
super();
power = new Random().nextInt(1000);
toughness = new Random().nextInt(1000);
}

/**
* Constructor takes in value and create new card
*
* @param x
* @throws Exception
*/
public PremiumCard(int x) throws Exception {
super(x);
if (x <= 1 && x >= 1000) {
throw new Exception("power/toughness is out of bounds 1 and 1000");
} else {
power = x;
toughness = x;
}
}

/**
* Constructor takes in value for power and toughness and create new card
*
* @param x
* @throws Exception
*/
public PremiumCard(int p, int t) throws Exception {
super(p, t);
if ((p <= 1 && p >= 1000) || (t <= 1 && t >= 1000)) {
throw new Exception("power/toughness is out of bounds 1 and 1000");
} else {
power = p;
toughness = t;
}
}

/**
* method returns power of card
*
* @return power
*/
public int getPower() {
return power;
}

/**
* method returns toughness of card
*
* @return toughness
*/
public int getToughness() {
return toughness;
}

/*  
* method returns cost of card
*
* @return cost
*/

public int getCost() {
return (int) Math.sqrt((1.5 * power) + (0.9 * toughness));
}

/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
public String toString() {
return "{{" + power + "/" + toughness + "}}";
}

/**
* method reduces power and toughness of card by ten percent
*/
public void weaken() {
power = (int) (power - power * 0.1);
toughness = (int) (toughness - toughness * 0.1);

}

/**
* method increases power and toughness of card by ten percent
*/
public void boost() {
power = (int) (power + power * 0.1);
toughness = (int) (toughness + toughness * 0.1);
}
}

CardsArrayList.java

package cards;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
* Cards ArrayList class
*
* @author
*
*/
public class CardArrayList {

private int sizeCounter;
private Card[] cards;

/**
* Default constructor
*/
public CardArrayList() {
cards = new Card[10];
sizeCounter = 0;
}

/**
* Constructor that takes in a value and create a new cards array of same
* size
*
* @param x
*/
public CardArrayList(int x) {
if (x < 0) {
System.out.println("Error");
} else {
cards = new Card[x];
sizeCounter = 0;

}
}

/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*
* method returns string
*/
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("[0");
int length = cards.length;
for (int i = 0; i < length; i++) {
if (cards[i] != null) {

builder.append(cards[i].toString());
builder.append(",");
}
}
builder.deleteCharAt(builder.length() - 1);
builder.append(":" + length);

return builder.toString();
}

/**
* return current number of elements of arraylist being stored

*
* @return
*/

public int size() {
int length = cards.length;
int filled = 0;
for (int i = 0; i < length; i++) {
if (cards[i] != null) {
filled = filled + 1;

}
}

return filled;
}

/**
* Adds card provided to array list in last empty location and increments
* size counter
* @param x

public void add(Card x) {
int length = cards.length;
for (int i = 0; i < length; i++) {
if (cards[i] == null) {
cards[i] = x;

break;
}
}
sizeCounter++;
}

/**
* Returns last element of array list
*
* @return
*/
public Card remove() {
int temp = sizeCounter;
sizeCounter = sizeCounter - 1;
return cards[temp - 1];
}

/**
* Returns card located at location x in the array
*
* @param x
* @return
*/
public Card get(int x) {
if (x > cards.length - 1) {
System.out.println("Invalid Location");
return null;
} else {
return cards[x];
}
}


* Returns index of given card in the array
* @param x
* @return
*/
public int indexOf(Card x) {
for (int i = 0; i < cards.length; i++) {
if (x.toString() == cards[i].toString()) {
return i;
}
}

return -1;
}

/**
* Adds card to specified location in the array,shifts all cards to right by
* one location if given location is in middle
* @param l
* @param x
*/
public void add(int l, Card x) {
if (isRoom() == false) {
expand();

}
for (int i = 0; i < cards.length; i++) {
if (i == l) {
for (int j = i; j < cards.length; j++) {
cards[j + 1] = cards[j];
}

cards[i] = x;
sizeCounter++; }   

}

}

  
* Removes card to specified location in the array,shifts all cards to left
* by one location if given location is in middle
* @param l
* @param x
*/
public Card remove(int j) {
Card card = null;
for (int i = 0; i < cards.length; i++) {
if (j == i) {
card = cards[i];

for (int k = i; k < cards.length; k++) {
cards[k] = cards[k + 1];
sizeCounter--;
}
}
}

return card;
}

/**
* Sorts array elements in descending order
*/
public void sort() {
Arrays.sort(cards, Collections.reverseOrder());
}

/**
* Shuffles elements in cards array
*/
public void shuffle() {
List<Card> list = Arrays.asList(cards);
Collections.shuffle(list);
}

/**
* Checks if there is space in array ,returns false if not
*
* @return
*/
private boolean isRoom() {
if (sizeCounter == cards.length) {
return false;
}
return true;
}

/**
* doubles the size of array
*/
private void expand() {
cards = Arrays.copyOf(cards, cards.length * 2);
}

/**
* Swaps two elements of array
*
* @param a
* @param b
*/
private void swap(int a, int b) {
Card temp = null;
temp = cards[a];
cards[a] = cards[b];
cards[b] = temp;
}

public void clear() {

cards = new Card[10];
}

}

Thank you sir..!


Related Solutions

Is List type is an interface in the Java collections framework? Classes Vector, ArrayList, and LinkedList...
Is List type is an interface in the Java collections framework? Classes Vector, ArrayList, and LinkedList are the same data structure but implement data storage in different ways. Classes, that implement Map interface in Java collections framework are used for storing what type of data? Declare and instantiate a list of elements of type String. Name this list myArray. what type of data structure is Stack? LinkedList data structure in Java collections is implemented as doubly linked lists. In PriorityQueue...
JAVA: when input is type ArrayList<ArrayList<Integer>> how to use java to get this solution [ [a,b,c]...
JAVA: when input is type ArrayList<ArrayList<Integer>> how to use java to get this solution [ [a,b,c] , [d,e], [f] ] ----> [ [a,d,f], [a,e,f], [b,d,f], [b,e,f], [c,d,f], [c,e,f]] [ [a,b], [a,b,c]] ----->[[a,a],[a,b],[a,c], [b,a],[b,b],[b,c] assuming abc are integer Thanks in advance!
JAVA - Write a program that creates an ArrayList and adds an Account object, a Date...
JAVA - Write a program that creates an ArrayList and adds an Account object, a Date object, a ClockWithAudio object, a BMI object, a Day object, and a FigurePane object. Then display all elements in the list. Assume that all classes (i.e. Date, Account, etc.) have their own no-argument constructor.
Java The List ADT has an interface and a linked list implementation whose source code is...
Java The List ADT has an interface and a linked list implementation whose source code is given at the bottom of this programming lab description. You are to modify the List ADT's source code by adding the method corresponding to the following UML: +hasRepeats() : boolean hasRepeats() returns true if the list has a value that occurs more than once in the list hasRepeats() returns false if no value in the list occurs more than once in the list For...
Java The List ADT has an interface and a linked list implementation whose source code is...
Java The List ADT has an interface and a linked list implementation whose source code is given at the bottom of this programming lab description. You are to modify the List ADT's source code by adding the method corresponding to the following UML: +hasRepeats() : boolean hasRepeats() returns true if the list has a value that occurs more than once in the list hasRepeats() returns false if no value in the list occurs more than once in the list For...
Java program Statement: Provide a user interface to the invoice program in Section 12.3 that allows...
Java program Statement: Provide a user interface to the invoice program in Section 12.3 that allows a user to enter and print an arbitrary invoice. Do not modify any of the existing classes. ..... ..... ..... /** Describes an invoice for a set of purchased products. */ public class Invoice { /** Adds a charge for a product to this invoice. @param aProduct the product that the customer ordered @param quantity the quantity of the product */ public void add(Product...
Write a Java program that takes an ArrayList<Integer>,  adds k copies of it at the end, and...
Write a Java program that takes an ArrayList<Integer>,  adds k copies of it at the end, and returns the expanded ArrayList.  The total size will be (k+1) * n.   public ArrayList<Integer> makeCopies(ArrayList<Integer>, int k) { } Example: ArrayList<Integer> has (3,7,4) and k = 2, then the returned, expanded ArrayList will have (3,7,4,3,7,4,3,7,4).  The total size is (k+1)*n = (2+1)*3= 9.
Find a method of ArrayList that is not in the List interface, specifically a method that...
Find a method of ArrayList that is not in the List interface, specifically a method that trims the internal array down to fit exactly. A Google search for this did work, but the JDK API of course is the definitive source. Give the method header for the method. Add a call to this method to TestArrayList.java (which is available online in TestArrayList.zip), and see that it compiles and runs fine. Now change the line creating the ArrayList to use type...
Focuses on the design, development, implementation, and testing of a Python program using Jupyter Notebook only...
Focuses on the design, development, implementation, and testing of a Python program using Jupyter Notebook only to solve the problem described below. You will write a program that simulates an Automatic Teller Machine (ATM). For this program, your code can have of user-defined functions only. However, the program must not call on any external functions or modules to handle any of the input, computational, and output requirements. Note, the program can be completed without the use of user-defined functions. Requirements:...
Use the below info to create a java program A GUI interface to ensure a user...
Use the below info to create a java program A GUI interface to ensure a user is old enough to play a game. Properly formatted prompts to input name, address, phone number, and age. Remember that name, address, phone number, etc. can be broken out in additional fields. Refer to the tutorial from this week’s Reading Assignment Multiple vs. Single Field Capture for Phone Number Form Input for help with this. Instructions to ensure that the information is displayed back...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT