SlideShare a Scribd company logo
1 of 13
Download to read offline
I have another assignment due for an advance java programming class that I do not understand
how to do. I don't know how to implement the comparable interface and sort the cards from
lowest to highest based on suit within rank. And I also dont understand how I am suppose to add
a static nested class that implements the comparator interface and then sort the cards lowest to
highest based on rank within a suit. Then I have to add the different buttons and I am not sure
which class that these buttons are to be placed in. The buttons I have to add are: Deal Button,
Fish Sort Button, Spades Sort Button, and a Reverse Toggle Button. The description for each
button is in the instructions below:
Program 4 – Sorting with nested classes and lambda expressions
This program is a bit different from our others. Just like the last program, you will start with the
project that is attached to this assignment. Remember to rename the project. You will lose points
if you do not. Also, remember that you need to submit an Eclipse project, not just Java files. You
will lose points there as well.
The main point of the exercise is to demonstrate your ability to use various types of nested
classes. Of course, sorting is important as well, but you don’t really need to do much more than
create the class that does the comparison. In general, I like giving you some latitude in how you
design and implement your projects. However, for this assignment, each piece is very specific as
to how I want you to implement things. There are a number of parts to this program. Make
certain you accomplish the two additions to the Card class early-on since much of the rest of
your program will depend on that work.
The requirements:
Properly named project, good code (avoid redundancy), nice UI, etc. (20 pts)
Implement the Comparable interface in the Card class. (15 pts)
Sort the cards lowest to highest based on suit within rank, e.g.
2 clubs
2 diamonds
2 hearts
2 spades
3 clubs
3 diamonds
etc.
Add a static nested class to the Card class that implements the Comparator interface. (15 pts)
Sort the cards lowest to highest based on rank within suit, e.g.
2 clubs
3 clubs
4 clubs
5 clubs
etc.
In the UI, add the following to your interface.
Deal Button (10 pts)
Implement the Deal action handler using an inner class (not local). You may want to pull some
of the code from the show method that is already there. Or better, put the common code into a
class and call it.
Fish Sort Button (15 pts)
Sort the code in a way that would be useful playing Go Fish. I.e. with all of the cards grouped
together. Implement the action handler using a lambda expression in the UI. The code in the
lambda expression should depend on the Card class for the actual sorting (i.e. the natural order).
It must not call any other method in the UI class.
Spades Sort Button (15 pts)
Order the cards in such a way that they would be useful playing Spades; i.e. with the cards sorted
by rank within suit and the suits in the order provided by the nested class in #2 above. You
actually want to reverse this sort before displaying. Implement the action handler using an
anonymous class in the UI. The code in the anonymous class should depend on the Card class for
the actual sorting; i.e. the Comparator that you added above.
Reverse Toggle Button (10 pts)
If this toggle is checked, the order of the sort is reversed, e.g.
AS, AH, 8H, 8D, 8C
becomes
8C, 8D, 8H, AH, AS
Clicking the toggle should have no effect. However, pushing the Spades Sort buttons should
result in a reversed ordering if the toggle button is selected. Unchecking the button and pushing
Spades Sort should result in the original sort. Note that this does not merely reverse the order; if
the button is checked pushing the SpadesSort button any number of times should always result in
the same ordering. You do not have to apply this to the Fish Sort, but see below. This action can
be accomplished in a number of ways. Some are simpler than others, some more efficient.
Extra Credit
Fish Sort and Reverse Toggle (3 pts)
Find a means to reverse sort that does not require reversing after sorting for the Fish Sort. That
is, the sort itself should do the reverse. Do not add code outside the lambda expression. It should
check whether the toggle button is checked and act appropriately. You must keep the Fish Sort
action in a lambda expression. This may take some research.
Bridge Sort Button (10 pts)
This sort is similar to the Spade sort where all of the cards are grouped by suit. However, the
groups of suits should then be sorted by how many are in each suit. E.g. if there are 2 spades, 5
hearts, 3 diamonds and 3 clubs, the hearts would be first, followed by the diamonds, clubs and
spades in that order. This will take some thinking on your part; it isn’t a simple problem. You
can do this in an inner class, anonymous class or even a static method in the Card class…or
something else you think of.
Turn your program in by zipping your project directory (or export it from Eclipse) and submit it
to D2L. Remember, the Eclipse project needs a new name that contains your last name. Do not
leave it the same as it is now. You may leave the package names just as they are.
Remember, I will be grading each of these on whether they work and whether you did each as
specified. Note that if you were really developing something like this you might opt for
everything in anonymous classes, or lambda expressions, or inner classes. However, I want to
see that you can do all of these, and do them where they are specified, so follow the instructions
carefully.
OK, you are all adding up the points, and yes, 113 would be possible if everything is exactly
correct.
We have some classes to start off that are done for us, now we have to do what the instructions
say above. The classes are as follows that are done for us:
IN THE CARDS.MODEL PACKAGE ARE THE FOLLOWING CLASSES:
Card.java class:
import java.util.Comparator;
public class Card implements Comparable
{
public final int SUIT_SIZE = 13;
public static final int CLUB = 0;
public static final int DIAMOND = 1;
public static final int HEART = 2;
public static final int SPADE = 3;
private int suit; // clubs = 0, diamonds = 1, hearts = 2, spades = 3
private int rank; // deuce = 0, three = 1, four = 2, ..., king = 11, ace = 12
private boolean isFaceUp = true; // not used for our program
// create a new card based on integer 0 = 2C, 1 = 3C, ..., 51 = AS
public Card(int card) {
rank = card % SUIT_SIZE;
suit = card / SUIT_SIZE;
}
public int getRank() {
return rank;
}
public int getSuit() {
return suit;
}
public boolean isFaceUp()
{
return isFaceUp;
}
public void flip()
{
isFaceUp = !isFaceUp;
}
// represent cards like "2H", "9C", "JS", "AD"
public String toString() {
String ranks = "23456789TJQKA";
String suits = "CDHS";
return ranks.charAt(rank) + "" + suits.charAt(suit);
}
@Override
public int compareTo(Card o) {
// TODO Auto-generated method stub
return 0;
}
}
Deck.java class:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;
public class Deck implements Iterator
{
// list of cards still in the deck
private ArrayList deck = new ArrayList<>();
// list of cards being used
private ArrayList used = new ArrayList<>();
// used to shuffle the deck
Random dealer = new Random();
private ArrayList myCardList;
private int myIndex;
public Deck()
{
// builds the deck
for (int i = 0; i < 52; i++) {
deck.add(new Card(i));
}
}
public ArrayList deal(int handSize)
{
ArrayList hand = new ArrayList<>();
// do we need more cards? If so, shuffle
if (deck.size() < handSize) {
shuffle();
}
for (int i=0; i < handSize; i++) {
Card next = deck.remove(deck.size() - 1);
hand.add(next);
used.add(next);
}
return hand;
}
public void shuffle()
{
deck.addAll(used);
for (int i=0; i < deck.size() - 1; i++) {
int swap = dealer.nextInt(deck.size() - i) + i;
if (swap != i) {
Card tmp1 = deck.get(i);
Card tmp2 = deck.get(swap);
deck.set(i, tmp2);
deck.set(swap, tmp1);
}
}
}
// just used for testing
public static void showHand(ArrayList hand)
{
for (Card c : hand) {
System.out.printf(" %s",c);
}
System.out.println();
}
// just used for testing
public static void main(String args[])
{
Deck deck = new Deck();
deck.shuffle();
ArrayList hand = deck.deal(5);
showHand(hand);
deck.shuffle();
hand = deck.deal(5);
showHand(hand);
}
@Override
public boolean hasNext() {
return myIndex < myCardList.size();
}
@Override
public Object next()
{
Card card = (Card)myCardList.get(myIndex);
return card;
}
}
IN THE CARDS.VIEW PACKAGE, THE TWO CLASSES ARE AS FOLLOWS:
HandDisplayWindow.java class:
import edu.trident.lanigan.cpt237.cards.model.Card;
import edu.trident.lanigan.cpt237.cards.model.Deck;
import javafx.geometry.Orientation;
import javafx.scene.Scene;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class HandDisplayWindow
{
private final int SUIT_SIZE = 13;
private Image[] cardImages = new Image[4*SUIT_SIZE];
private Stage myStage;
ListView listView = new ListView<>();
Deck deck;
int handSize;
public HandDisplayWindow(Stage stage, int size)
{
handSize = size;
myStage = stage;
myStage.setTitle("Card Hand");
BorderPane pane = new BorderPane();
Scene scene = new Scene(pane);
myStage.setScene(scene);
listView.setCellFactory(param -> new ListCell() {
private ImageView imageView = new ImageView();
@Override
public void updateItem(Card card, boolean empty)
{
super.updateItem(card, empty);
if (empty) {
setGraphic(null);
} else {
// determine the index of the card
int index = card.getSuit() * SUIT_SIZE + card.getRank();
imageView.setImage(cardImages[index]);
imageView.setPreserveRatio(true);
imageView.setFitWidth(50);
setGraphic(imageView);
}
}
});
listView.setOrientation(Orientation.HORIZONTAL);
pane.setCenter(listView);
myStage.setHeight(150);
myStage.setWidth(68 * handSize);
loadImages();
}
private void loadImages()
{
String resourceDir = "file:resources/cardspng/";
char[] suits = { 'c', 'd', 'h', 's' };
char[] rank = { '2', '3', '4', '5', '6', '7', '8', '9', '0', 'j', 'q', 'k', 'a' };
int slot = 0;
// load images
for (int s = 0; s < 4; s++) {
for (int r = 0; r < SUIT_SIZE; r++) {
String path = resourceDir + suits[s] + rank[r] + ".png";
cardImages[slot] = new Image(path);
slot++;
}
}
}
public void show(Deck deck)
{
this.deck = deck;
if (deck != null)
listView.getItems().setAll(deck.deal(handSize));
myStage.show();
}
}
MainApplication.java class:
import edu.trident.lanigan.cpt237.cards.model.Deck;
import javafx.application.Application;
import javafx.stage.Stage;
public class MainApplication extends Application
{
@Override
public void start(Stage primaryStage) throws Exception
{
HandDisplayWindow ui = new HandDisplayWindow(primaryStage, 13);
Deck deck = new Deck();
deck.shuffle();
ui.show(deck);
}
public static void main(String[] args)
{
Application.launch(args);
}
}
Solution
import java.util.Comparator;
public class Card implements Comparable
{
public final int SUIT_SIZE = 13;
public static final int CLUB = 0;
public static final int DIAMOND = 1;
public static final int HEART = 2;
public static final int SPADE = 3;
private int suit; // clubs = 0, diamonds = 1, hearts = 2, spades = 3
private int rank; // deuce = 0, three = 1, four = 2, ..., king = 11, ace = 12
private boolean isFaceUp = true; // not used for our program
// create a new card based on integer 0 = 2C, 1 = 3C, ..., 51 = AS
public Card(int card) {
rank = card % SUIT_SIZE;
suit = card / SUIT_SIZE;
}
public int getRank() {
return rank;
}
public int getSuit() {
return suit;
}
public boolean isFaceUp()
{
return isFaceUp;
}
public void flip()
{
isFaceUp = !isFaceUp;
}
// represent cards like "2H", "9C", "JS", "AD"
public String toString() {
String ranks = "23456789TJQKA";
String suits = "CDHS";
return ranks.charAt(rank) + "" + suits.charAt(suit);
}
@Override
public int compareTo(Card o) {
// TODO Auto-generated method stub
return 0;
}
}
Deck.java class:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;
public class Deck implements Iterator
{
// list of cards still in the deck
private ArrayList deck = new ArrayList<>();
// list of cards being used
private ArrayList used = new ArrayList<>();
// used to shuffle the deck
Random dealer = new Random();
private ArrayList myCardList;
private int myIndex;
public Deck()
{
// builds the deck
for (int i = 0; i < 52; i++) {
deck.add(new Card(i));
}
}
public ArrayList deal(int handSize)
{
ArrayList hand = new ArrayList<>();
// do we need more cards? If so, shuffle
if (deck.size() < handSize) {
shuffle();
}
for (int i=0; i < handSize; i++) {
Card next = deck.remove(deck.size() - 1);
hand.add(next);
used.add(next);
}
return hand;
}
public void shuffle()
{
deck.addAll(used);
for (int i=0; i < deck.size() - 1; i++) {
int swap = dealer.nextInt(deck.size() - i) + i;
if (swap != i) {
Card tmp1 = deck.get(i);
Card tmp2 = deck.get(swap);
deck.set(i, tmp2);
deck.set(swap, tmp1);
}
}
}
// just used for testing
public static void showHand(ArrayList hand)
{
for (Card c : hand) {
System.out.printf(" %s",c);
}
System.out.println();
}
// just used for testing
public static void main(String args[])
{
Deck deck = new Deck();
deck.shuffle();
ArrayList hand = deck.deal(5);
showHand(hand);
deck.shuffle();
hand = deck.deal(5);
showHand(hand);
}
@Override
public boolean hasNext() {
return myIndex < myCardList.size();
}
@Override
public Object next()
{
Card card = (Card)myCardList.get(myIndex);
return card;
}
}
import edu.trident.lanigan.cpt237.cards.model.Deck;
import javafx.application.Application;
import javafx.stage.Stage;
public class MainApplication extends Application
{
@Override
public void start(Stage primaryStage) throws Exception
{
HandDisplayWindow ui = new HandDisplayWindow(primaryStage, 13);
Deck deck = new Deck();
deck.shuffle();
ui.show(deck);
}
public static void main(String[] args)
{
Application.launch(args);
}
}

More Related Content

Similar to I have another assignment due for an advance java programming class .pdf

I really need help with this Assignment Please in C programming not .pdf
I really need help with this Assignment Please in C programming not .pdfI really need help with this Assignment Please in C programming not .pdf
I really need help with this Assignment Please in C programming not .pdfpasqualealvarez467
 
Android tutorials7 calculator
Android tutorials7 calculatorAndroid tutorials7 calculator
Android tutorials7 calculatorVlad Kolesnyk
 
05 neo4j gds graph catalog
05   neo4j gds graph catalog05   neo4j gds graph catalog
05 neo4j gds graph catalogNeo4j
 
Raspberry Pi and Physical Computing Workshop
Raspberry Pi and Physical Computing WorkshopRaspberry Pi and Physical Computing Workshop
Raspberry Pi and Physical Computing WorkshopRachel Wang
 
Please write this in java using a GUIImplement a class cal.pdf
Please write this in java using a GUIImplement a class cal.pdfPlease write this in java using a GUIImplement a class cal.pdf
Please write this in java using a GUIImplement a class cal.pdfaniarihant
 
Basics of Programming - A Review Guide
Basics of Programming - A Review GuideBasics of Programming - A Review Guide
Basics of Programming - A Review GuideBenjamin Kissinger
 
You will write a multi-interface version of the well-known concentra.pdf
You will write a multi-interface version of the well-known concentra.pdfYou will write a multi-interface version of the well-known concentra.pdf
You will write a multi-interface version of the well-known concentra.pdfFashionColZone
 
Arduino experimenters guide hq
Arduino experimenters guide hqArduino experimenters guide hq
Arduino experimenters guide hqAndreis Santos
 
Most asked JAVA Interview Questions & Answers.
Most asked JAVA Interview Questions & Answers.Most asked JAVA Interview Questions & Answers.
Most asked JAVA Interview Questions & Answers.Questpond
 
Hierarchies of LifeExperiment 1 Classification of Common Objects.docx
Hierarchies of LifeExperiment 1 Classification of Common Objects.docxHierarchies of LifeExperiment 1 Classification of Common Objects.docx
Hierarchies of LifeExperiment 1 Classification of Common Objects.docxpooleavelina
 
project 6cards.pyimport randomclass Card( object ).docx
project 6cards.pyimport randomclass Card( object ).docxproject 6cards.pyimport randomclass Card( object ).docx
project 6cards.pyimport randomclass Card( object ).docxbriancrawford30935
 

Similar to I have another assignment due for an advance java programming class .pdf (18)

Dart - en ny platform til webudvikling af Rico Wind, Google
Dart - en ny platform til webudvikling af Rico Wind, GoogleDart - en ny platform til webudvikling af Rico Wind, Google
Dart - en ny platform til webudvikling af Rico Wind, Google
 
Modul 1 Scratch
Modul 1 ScratchModul 1 Scratch
Modul 1 Scratch
 
I really need help with this Assignment Please in C programming not .pdf
I really need help with this Assignment Please in C programming not .pdfI really need help with this Assignment Please in C programming not .pdf
I really need help with this Assignment Please in C programming not .pdf
 
User rpl tut
User rpl tutUser rpl tut
User rpl tut
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
 
Android tutorials7 calculator
Android tutorials7 calculatorAndroid tutorials7 calculator
Android tutorials7 calculator
 
05 neo4j gds graph catalog
05   neo4j gds graph catalog05   neo4j gds graph catalog
05 neo4j gds graph catalog
 
Raspberry Pi and Physical Computing Workshop
Raspberry Pi and Physical Computing WorkshopRaspberry Pi and Physical Computing Workshop
Raspberry Pi and Physical Computing Workshop
 
Logo tutorial
Logo tutorialLogo tutorial
Logo tutorial
 
Please write this in java using a GUIImplement a class cal.pdf
Please write this in java using a GUIImplement a class cal.pdfPlease write this in java using a GUIImplement a class cal.pdf
Please write this in java using a GUIImplement a class cal.pdf
 
Basics of Programming - A Review Guide
Basics of Programming - A Review GuideBasics of Programming - A Review Guide
Basics of Programming - A Review Guide
 
Jeop game-final-review
Jeop game-final-reviewJeop game-final-review
Jeop game-final-review
 
You will write a multi-interface version of the well-known concentra.pdf
You will write a multi-interface version of the well-known concentra.pdfYou will write a multi-interface version of the well-known concentra.pdf
You will write a multi-interface version of the well-known concentra.pdf
 
Arduino experimenters guide hq
Arduino experimenters guide hqArduino experimenters guide hq
Arduino experimenters guide hq
 
Most asked JAVA Interview Questions & Answers.
Most asked JAVA Interview Questions & Answers.Most asked JAVA Interview Questions & Answers.
Most asked JAVA Interview Questions & Answers.
 
Ardx experimenters-guide-web
Ardx experimenters-guide-webArdx experimenters-guide-web
Ardx experimenters-guide-web
 
Hierarchies of LifeExperiment 1 Classification of Common Objects.docx
Hierarchies of LifeExperiment 1 Classification of Common Objects.docxHierarchies of LifeExperiment 1 Classification of Common Objects.docx
Hierarchies of LifeExperiment 1 Classification of Common Objects.docx
 
project 6cards.pyimport randomclass Card( object ).docx
project 6cards.pyimport randomclass Card( object ).docxproject 6cards.pyimport randomclass Card( object ).docx
project 6cards.pyimport randomclass Card( object ).docx
 

More from FORTUNE2505

Why would a manager be concerned with bandwidth How is bandwidth me.pdf
Why would a manager be concerned with bandwidth How is bandwidth me.pdfWhy would a manager be concerned with bandwidth How is bandwidth me.pdf
Why would a manager be concerned with bandwidth How is bandwidth me.pdfFORTUNE2505
 
Where would the Internet be today if the UNIX operating system did n.pdf
Where would the Internet be today if the UNIX operating system did n.pdfWhere would the Internet be today if the UNIX operating system did n.pdf
Where would the Internet be today if the UNIX operating system did n.pdfFORTUNE2505
 
What do you understand by degrees of Data AbstractionSolution.pdf
What do you understand by degrees of Data AbstractionSolution.pdfWhat do you understand by degrees of Data AbstractionSolution.pdf
What do you understand by degrees of Data AbstractionSolution.pdfFORTUNE2505
 
validity. (The Case lulTTtuT 2. Discuss the Economics of Effective Ma.pdf
validity. (The Case lulTTtuT 2. Discuss the Economics of Effective Ma.pdfvalidity. (The Case lulTTtuT 2. Discuss the Economics of Effective Ma.pdf
validity. (The Case lulTTtuT 2. Discuss the Economics of Effective Ma.pdfFORTUNE2505
 
Twitter had their IPO in 2013. Which of the following is not accurate.pdf
Twitter had their IPO in 2013. Which of the following is not accurate.pdfTwitter had their IPO in 2013. Which of the following is not accurate.pdf
Twitter had their IPO in 2013. Which of the following is not accurate.pdfFORTUNE2505
 
Use C programmingMake sure everything works only upload.pdf
Use C programmingMake sure everything works only upload.pdfUse C programmingMake sure everything works only upload.pdf
Use C programmingMake sure everything works only upload.pdfFORTUNE2505
 
The Adventures of Huckleberry Finn was published twenty years after .pdf
The Adventures of Huckleberry Finn was published twenty years after .pdfThe Adventures of Huckleberry Finn was published twenty years after .pdf
The Adventures of Huckleberry Finn was published twenty years after .pdfFORTUNE2505
 
Step 1 You work for Thunderduck Custom Tables Inc. This is the first.pdf
Step 1 You work for Thunderduck Custom Tables Inc. This is the first.pdfStep 1 You work for Thunderduck Custom Tables Inc. This is the first.pdf
Step 1 You work for Thunderduck Custom Tables Inc. This is the first.pdfFORTUNE2505
 
Researchers argue about whether Oldowan toolmakers were hunters or s.pdf
Researchers argue about whether Oldowan toolmakers were hunters or s.pdfResearchers argue about whether Oldowan toolmakers were hunters or s.pdf
Researchers argue about whether Oldowan toolmakers were hunters or s.pdfFORTUNE2505
 
In Aristotles Poetics he speaks of epics and tragedies. How do.pdf
In Aristotles Poetics he speaks of epics and tragedies. How do.pdfIn Aristotles Poetics he speaks of epics and tragedies. How do.pdf
In Aristotles Poetics he speaks of epics and tragedies. How do.pdfFORTUNE2505
 
Name the type of chemical messenger is released from the axon termina.pdf
Name the type of chemical messenger is released from the axon termina.pdfName the type of chemical messenger is released from the axon termina.pdf
Name the type of chemical messenger is released from the axon termina.pdfFORTUNE2505
 
Marilee Jones, the former dean of admissions of the Massachusetts In.pdf
Marilee Jones, the former dean of admissions of the Massachusetts In.pdfMarilee Jones, the former dean of admissions of the Massachusetts In.pdf
Marilee Jones, the former dean of admissions of the Massachusetts In.pdfFORTUNE2505
 
Know how the complement of mRNAs in a cell can be assayed (in plants.pdf
Know how the complement of mRNAs in a cell can be assayed (in plants.pdfKnow how the complement of mRNAs in a cell can be assayed (in plants.pdf
Know how the complement of mRNAs in a cell can be assayed (in plants.pdfFORTUNE2505
 
In Module 5 the you are here slide indicates we are currently in.pdf
In Module 5 the you are here slide indicates we are currently in.pdfIn Module 5 the you are here slide indicates we are currently in.pdf
In Module 5 the you are here slide indicates we are currently in.pdfFORTUNE2505
 
Identify the role you believe mobile devices have on email investiga.pdf
Identify the role you believe mobile devices have on email investiga.pdfIdentify the role you believe mobile devices have on email investiga.pdf
Identify the role you believe mobile devices have on email investiga.pdfFORTUNE2505
 
I need to implement in c++ this non-List member function void print.pdf
I need to implement in c++ this non-List member function void print.pdfI need to implement in c++ this non-List member function void print.pdf
I need to implement in c++ this non-List member function void print.pdfFORTUNE2505
 
4. Real gross domestic prodact A. measures the value of fimal goods a.pdf
4. Real gross domestic prodact A. measures the value of fimal goods a.pdf4. Real gross domestic prodact A. measures the value of fimal goods a.pdf
4. Real gross domestic prodact A. measures the value of fimal goods a.pdfFORTUNE2505
 
Hypothesis What is your hypothesis for the genetic characteristi.pdf
Hypothesis  What is your hypothesis for the genetic characteristi.pdfHypothesis  What is your hypothesis for the genetic characteristi.pdf
Hypothesis What is your hypothesis for the genetic characteristi.pdfFORTUNE2505
 
How is a process shown in a DFD(data flow diagramSolution Data.pdf
How is a process shown in a DFD(data flow diagramSolution  Data.pdfHow is a process shown in a DFD(data flow diagramSolution  Data.pdf
How is a process shown in a DFD(data flow diagramSolution Data.pdfFORTUNE2505
 
Hey,Why is it not possible in Java to write a swap routine that sw.pdf
Hey,Why is it not possible in Java to write a swap routine that sw.pdfHey,Why is it not possible in Java to write a swap routine that sw.pdf
Hey,Why is it not possible in Java to write a swap routine that sw.pdfFORTUNE2505
 

More from FORTUNE2505 (20)

Why would a manager be concerned with bandwidth How is bandwidth me.pdf
Why would a manager be concerned with bandwidth How is bandwidth me.pdfWhy would a manager be concerned with bandwidth How is bandwidth me.pdf
Why would a manager be concerned with bandwidth How is bandwidth me.pdf
 
Where would the Internet be today if the UNIX operating system did n.pdf
Where would the Internet be today if the UNIX operating system did n.pdfWhere would the Internet be today if the UNIX operating system did n.pdf
Where would the Internet be today if the UNIX operating system did n.pdf
 
What do you understand by degrees of Data AbstractionSolution.pdf
What do you understand by degrees of Data AbstractionSolution.pdfWhat do you understand by degrees of Data AbstractionSolution.pdf
What do you understand by degrees of Data AbstractionSolution.pdf
 
validity. (The Case lulTTtuT 2. Discuss the Economics of Effective Ma.pdf
validity. (The Case lulTTtuT 2. Discuss the Economics of Effective Ma.pdfvalidity. (The Case lulTTtuT 2. Discuss the Economics of Effective Ma.pdf
validity. (The Case lulTTtuT 2. Discuss the Economics of Effective Ma.pdf
 
Twitter had their IPO in 2013. Which of the following is not accurate.pdf
Twitter had their IPO in 2013. Which of the following is not accurate.pdfTwitter had their IPO in 2013. Which of the following is not accurate.pdf
Twitter had their IPO in 2013. Which of the following is not accurate.pdf
 
Use C programmingMake sure everything works only upload.pdf
Use C programmingMake sure everything works only upload.pdfUse C programmingMake sure everything works only upload.pdf
Use C programmingMake sure everything works only upload.pdf
 
The Adventures of Huckleberry Finn was published twenty years after .pdf
The Adventures of Huckleberry Finn was published twenty years after .pdfThe Adventures of Huckleberry Finn was published twenty years after .pdf
The Adventures of Huckleberry Finn was published twenty years after .pdf
 
Step 1 You work for Thunderduck Custom Tables Inc. This is the first.pdf
Step 1 You work for Thunderduck Custom Tables Inc. This is the first.pdfStep 1 You work for Thunderduck Custom Tables Inc. This is the first.pdf
Step 1 You work for Thunderduck Custom Tables Inc. This is the first.pdf
 
Researchers argue about whether Oldowan toolmakers were hunters or s.pdf
Researchers argue about whether Oldowan toolmakers were hunters or s.pdfResearchers argue about whether Oldowan toolmakers were hunters or s.pdf
Researchers argue about whether Oldowan toolmakers were hunters or s.pdf
 
In Aristotles Poetics he speaks of epics and tragedies. How do.pdf
In Aristotles Poetics he speaks of epics and tragedies. How do.pdfIn Aristotles Poetics he speaks of epics and tragedies. How do.pdf
In Aristotles Poetics he speaks of epics and tragedies. How do.pdf
 
Name the type of chemical messenger is released from the axon termina.pdf
Name the type of chemical messenger is released from the axon termina.pdfName the type of chemical messenger is released from the axon termina.pdf
Name the type of chemical messenger is released from the axon termina.pdf
 
Marilee Jones, the former dean of admissions of the Massachusetts In.pdf
Marilee Jones, the former dean of admissions of the Massachusetts In.pdfMarilee Jones, the former dean of admissions of the Massachusetts In.pdf
Marilee Jones, the former dean of admissions of the Massachusetts In.pdf
 
Know how the complement of mRNAs in a cell can be assayed (in plants.pdf
Know how the complement of mRNAs in a cell can be assayed (in plants.pdfKnow how the complement of mRNAs in a cell can be assayed (in plants.pdf
Know how the complement of mRNAs in a cell can be assayed (in plants.pdf
 
In Module 5 the you are here slide indicates we are currently in.pdf
In Module 5 the you are here slide indicates we are currently in.pdfIn Module 5 the you are here slide indicates we are currently in.pdf
In Module 5 the you are here slide indicates we are currently in.pdf
 
Identify the role you believe mobile devices have on email investiga.pdf
Identify the role you believe mobile devices have on email investiga.pdfIdentify the role you believe mobile devices have on email investiga.pdf
Identify the role you believe mobile devices have on email investiga.pdf
 
I need to implement in c++ this non-List member function void print.pdf
I need to implement in c++ this non-List member function void print.pdfI need to implement in c++ this non-List member function void print.pdf
I need to implement in c++ this non-List member function void print.pdf
 
4. Real gross domestic prodact A. measures the value of fimal goods a.pdf
4. Real gross domestic prodact A. measures the value of fimal goods a.pdf4. Real gross domestic prodact A. measures the value of fimal goods a.pdf
4. Real gross domestic prodact A. measures the value of fimal goods a.pdf
 
Hypothesis What is your hypothesis for the genetic characteristi.pdf
Hypothesis  What is your hypothesis for the genetic characteristi.pdfHypothesis  What is your hypothesis for the genetic characteristi.pdf
Hypothesis What is your hypothesis for the genetic characteristi.pdf
 
How is a process shown in a DFD(data flow diagramSolution Data.pdf
How is a process shown in a DFD(data flow diagramSolution  Data.pdfHow is a process shown in a DFD(data flow diagramSolution  Data.pdf
How is a process shown in a DFD(data flow diagramSolution Data.pdf
 
Hey,Why is it not possible in Java to write a swap routine that sw.pdf
Hey,Why is it not possible in Java to write a swap routine that sw.pdfHey,Why is it not possible in Java to write a swap routine that sw.pdf
Hey,Why is it not possible in Java to write a swap routine that sw.pdf
 

Recently uploaded

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesEnergy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesShubhangi Sonawane
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfChris Hunter
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxNikitaBankoti2
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 

Recently uploaded (20)

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesEnergy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 

I have another assignment due for an advance java programming class .pdf

  • 1. I have another assignment due for an advance java programming class that I do not understand how to do. I don't know how to implement the comparable interface and sort the cards from lowest to highest based on suit within rank. And I also dont understand how I am suppose to add a static nested class that implements the comparator interface and then sort the cards lowest to highest based on rank within a suit. Then I have to add the different buttons and I am not sure which class that these buttons are to be placed in. The buttons I have to add are: Deal Button, Fish Sort Button, Spades Sort Button, and a Reverse Toggle Button. The description for each button is in the instructions below: Program 4 – Sorting with nested classes and lambda expressions This program is a bit different from our others. Just like the last program, you will start with the project that is attached to this assignment. Remember to rename the project. You will lose points if you do not. Also, remember that you need to submit an Eclipse project, not just Java files. You will lose points there as well. The main point of the exercise is to demonstrate your ability to use various types of nested classes. Of course, sorting is important as well, but you don’t really need to do much more than create the class that does the comparison. In general, I like giving you some latitude in how you design and implement your projects. However, for this assignment, each piece is very specific as to how I want you to implement things. There are a number of parts to this program. Make certain you accomplish the two additions to the Card class early-on since much of the rest of your program will depend on that work. The requirements: Properly named project, good code (avoid redundancy), nice UI, etc. (20 pts) Implement the Comparable interface in the Card class. (15 pts) Sort the cards lowest to highest based on suit within rank, e.g. 2 clubs 2 diamonds 2 hearts 2 spades 3 clubs 3 diamonds etc. Add a static nested class to the Card class that implements the Comparator interface. (15 pts) Sort the cards lowest to highest based on rank within suit, e.g. 2 clubs 3 clubs
  • 2. 4 clubs 5 clubs etc. In the UI, add the following to your interface. Deal Button (10 pts) Implement the Deal action handler using an inner class (not local). You may want to pull some of the code from the show method that is already there. Or better, put the common code into a class and call it. Fish Sort Button (15 pts) Sort the code in a way that would be useful playing Go Fish. I.e. with all of the cards grouped together. Implement the action handler using a lambda expression in the UI. The code in the lambda expression should depend on the Card class for the actual sorting (i.e. the natural order). It must not call any other method in the UI class. Spades Sort Button (15 pts) Order the cards in such a way that they would be useful playing Spades; i.e. with the cards sorted by rank within suit and the suits in the order provided by the nested class in #2 above. You actually want to reverse this sort before displaying. Implement the action handler using an anonymous class in the UI. The code in the anonymous class should depend on the Card class for the actual sorting; i.e. the Comparator that you added above. Reverse Toggle Button (10 pts) If this toggle is checked, the order of the sort is reversed, e.g. AS, AH, 8H, 8D, 8C becomes 8C, 8D, 8H, AH, AS Clicking the toggle should have no effect. However, pushing the Spades Sort buttons should result in a reversed ordering if the toggle button is selected. Unchecking the button and pushing Spades Sort should result in the original sort. Note that this does not merely reverse the order; if the button is checked pushing the SpadesSort button any number of times should always result in the same ordering. You do not have to apply this to the Fish Sort, but see below. This action can be accomplished in a number of ways. Some are simpler than others, some more efficient. Extra Credit Fish Sort and Reverse Toggle (3 pts) Find a means to reverse sort that does not require reversing after sorting for the Fish Sort. That is, the sort itself should do the reverse. Do not add code outside the lambda expression. It should check whether the toggle button is checked and act appropriately. You must keep the Fish Sort action in a lambda expression. This may take some research.
  • 3. Bridge Sort Button (10 pts) This sort is similar to the Spade sort where all of the cards are grouped by suit. However, the groups of suits should then be sorted by how many are in each suit. E.g. if there are 2 spades, 5 hearts, 3 diamonds and 3 clubs, the hearts would be first, followed by the diamonds, clubs and spades in that order. This will take some thinking on your part; it isn’t a simple problem. You can do this in an inner class, anonymous class or even a static method in the Card class…or something else you think of. Turn your program in by zipping your project directory (or export it from Eclipse) and submit it to D2L. Remember, the Eclipse project needs a new name that contains your last name. Do not leave it the same as it is now. You may leave the package names just as they are. Remember, I will be grading each of these on whether they work and whether you did each as specified. Note that if you were really developing something like this you might opt for everything in anonymous classes, or lambda expressions, or inner classes. However, I want to see that you can do all of these, and do them where they are specified, so follow the instructions carefully. OK, you are all adding up the points, and yes, 113 would be possible if everything is exactly correct. We have some classes to start off that are done for us, now we have to do what the instructions say above. The classes are as follows that are done for us: IN THE CARDS.MODEL PACKAGE ARE THE FOLLOWING CLASSES: Card.java class: import java.util.Comparator; public class Card implements Comparable { public final int SUIT_SIZE = 13; public static final int CLUB = 0; public static final int DIAMOND = 1; public static final int HEART = 2; public static final int SPADE = 3; private int suit; // clubs = 0, diamonds = 1, hearts = 2, spades = 3 private int rank; // deuce = 0, three = 1, four = 2, ..., king = 11, ace = 12 private boolean isFaceUp = true; // not used for our program // create a new card based on integer 0 = 2C, 1 = 3C, ..., 51 = AS public Card(int card) { rank = card % SUIT_SIZE;
  • 4. suit = card / SUIT_SIZE; } public int getRank() { return rank; } public int getSuit() { return suit; } public boolean isFaceUp() { return isFaceUp; } public void flip() { isFaceUp = !isFaceUp; } // represent cards like "2H", "9C", "JS", "AD" public String toString() { String ranks = "23456789TJQKA"; String suits = "CDHS"; return ranks.charAt(rank) + "" + suits.charAt(suit); } @Override public int compareTo(Card o) { // TODO Auto-generated method stub return 0; } } Deck.java class: import java.util.ArrayList; import java.util.Iterator; import java.util.Random; public class Deck implements Iterator { // list of cards still in the deck
  • 5. private ArrayList deck = new ArrayList<>(); // list of cards being used private ArrayList used = new ArrayList<>(); // used to shuffle the deck Random dealer = new Random(); private ArrayList myCardList; private int myIndex; public Deck() { // builds the deck for (int i = 0; i < 52; i++) { deck.add(new Card(i)); } } public ArrayList deal(int handSize) { ArrayList hand = new ArrayList<>(); // do we need more cards? If so, shuffle if (deck.size() < handSize) { shuffle(); } for (int i=0; i < handSize; i++) { Card next = deck.remove(deck.size() - 1); hand.add(next); used.add(next); } return hand; } public void shuffle() { deck.addAll(used);
  • 6. for (int i=0; i < deck.size() - 1; i++) { int swap = dealer.nextInt(deck.size() - i) + i; if (swap != i) { Card tmp1 = deck.get(i); Card tmp2 = deck.get(swap); deck.set(i, tmp2); deck.set(swap, tmp1); } } } // just used for testing public static void showHand(ArrayList hand) { for (Card c : hand) { System.out.printf(" %s",c); } System.out.println(); } // just used for testing public static void main(String args[]) { Deck deck = new Deck(); deck.shuffle(); ArrayList hand = deck.deal(5); showHand(hand); deck.shuffle(); hand = deck.deal(5); showHand(hand); } @Override public boolean hasNext() { return myIndex < myCardList.size(); } @Override
  • 7. public Object next() { Card card = (Card)myCardList.get(myIndex); return card; } } IN THE CARDS.VIEW PACKAGE, THE TWO CLASSES ARE AS FOLLOWS: HandDisplayWindow.java class: import edu.trident.lanigan.cpt237.cards.model.Card; import edu.trident.lanigan.cpt237.cards.model.Deck; import javafx.geometry.Orientation; import javafx.scene.Scene; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; public class HandDisplayWindow { private final int SUIT_SIZE = 13; private Image[] cardImages = new Image[4*SUIT_SIZE]; private Stage myStage; ListView listView = new ListView<>(); Deck deck; int handSize; public HandDisplayWindow(Stage stage, int size) { handSize = size; myStage = stage; myStage.setTitle("Card Hand"); BorderPane pane = new BorderPane(); Scene scene = new Scene(pane); myStage.setScene(scene); listView.setCellFactory(param -> new ListCell() {
  • 8. private ImageView imageView = new ImageView(); @Override public void updateItem(Card card, boolean empty) { super.updateItem(card, empty); if (empty) { setGraphic(null); } else { // determine the index of the card int index = card.getSuit() * SUIT_SIZE + card.getRank(); imageView.setImage(cardImages[index]); imageView.setPreserveRatio(true); imageView.setFitWidth(50); setGraphic(imageView); } } }); listView.setOrientation(Orientation.HORIZONTAL); pane.setCenter(listView); myStage.setHeight(150); myStage.setWidth(68 * handSize); loadImages(); } private void loadImages() { String resourceDir = "file:resources/cardspng/"; char[] suits = { 'c', 'd', 'h', 's' }; char[] rank = { '2', '3', '4', '5', '6', '7', '8', '9', '0', 'j', 'q', 'k', 'a' }; int slot = 0; // load images for (int s = 0; s < 4; s++) { for (int r = 0; r < SUIT_SIZE; r++) { String path = resourceDir + suits[s] + rank[r] + ".png"; cardImages[slot] = new Image(path); slot++; }
  • 9. } } public void show(Deck deck) { this.deck = deck; if (deck != null) listView.getItems().setAll(deck.deal(handSize)); myStage.show(); } } MainApplication.java class: import edu.trident.lanigan.cpt237.cards.model.Deck; import javafx.application.Application; import javafx.stage.Stage; public class MainApplication extends Application { @Override public void start(Stage primaryStage) throws Exception { HandDisplayWindow ui = new HandDisplayWindow(primaryStage, 13); Deck deck = new Deck(); deck.shuffle(); ui.show(deck); } public static void main(String[] args) { Application.launch(args); } } Solution import java.util.Comparator; public class Card implements Comparable { public final int SUIT_SIZE = 13;
  • 10. public static final int CLUB = 0; public static final int DIAMOND = 1; public static final int HEART = 2; public static final int SPADE = 3; private int suit; // clubs = 0, diamonds = 1, hearts = 2, spades = 3 private int rank; // deuce = 0, three = 1, four = 2, ..., king = 11, ace = 12 private boolean isFaceUp = true; // not used for our program // create a new card based on integer 0 = 2C, 1 = 3C, ..., 51 = AS public Card(int card) { rank = card % SUIT_SIZE; suit = card / SUIT_SIZE; } public int getRank() { return rank; } public int getSuit() { return suit; } public boolean isFaceUp() { return isFaceUp; } public void flip() { isFaceUp = !isFaceUp; } // represent cards like "2H", "9C", "JS", "AD" public String toString() { String ranks = "23456789TJQKA"; String suits = "CDHS"; return ranks.charAt(rank) + "" + suits.charAt(suit); } @Override public int compareTo(Card o) {
  • 11. // TODO Auto-generated method stub return 0; } } Deck.java class: import java.util.ArrayList; import java.util.Iterator; import java.util.Random; public class Deck implements Iterator { // list of cards still in the deck private ArrayList deck = new ArrayList<>(); // list of cards being used private ArrayList used = new ArrayList<>(); // used to shuffle the deck Random dealer = new Random(); private ArrayList myCardList; private int myIndex; public Deck() { // builds the deck for (int i = 0; i < 52; i++) { deck.add(new Card(i)); } } public ArrayList deal(int handSize) { ArrayList hand = new ArrayList<>(); // do we need more cards? If so, shuffle if (deck.size() < handSize) { shuffle(); } for (int i=0; i < handSize; i++) {
  • 12. Card next = deck.remove(deck.size() - 1); hand.add(next); used.add(next); } return hand; } public void shuffle() { deck.addAll(used); for (int i=0; i < deck.size() - 1; i++) { int swap = dealer.nextInt(deck.size() - i) + i; if (swap != i) { Card tmp1 = deck.get(i); Card tmp2 = deck.get(swap); deck.set(i, tmp2); deck.set(swap, tmp1); } } } // just used for testing public static void showHand(ArrayList hand) { for (Card c : hand) { System.out.printf(" %s",c); } System.out.println(); } // just used for testing public static void main(String args[]) { Deck deck = new Deck(); deck.shuffle();
  • 13. ArrayList hand = deck.deal(5); showHand(hand); deck.shuffle(); hand = deck.deal(5); showHand(hand); } @Override public boolean hasNext() { return myIndex < myCardList.size(); } @Override public Object next() { Card card = (Card)myCardList.get(myIndex); return card; } } import edu.trident.lanigan.cpt237.cards.model.Deck; import javafx.application.Application; import javafx.stage.Stage; public class MainApplication extends Application { @Override public void start(Stage primaryStage) throws Exception { HandDisplayWindow ui = new HandDisplayWindow(primaryStage, 13); Deck deck = new Deck(); deck.shuffle(); ui.show(deck); } public static void main(String[] args) { Application.launch(args); } }