I have a 3 dimensional ArrayList and I want to determine if it is empty or not. There is an exception called EmptyCollectionException which is not part of java standard library and hence I'm not allowed to use it.
Is there a way to accomplish that using a native java exception or function?
The 3D List is constructed as follow:
public void makeRandomCardListForLearning (Course courseToBeMadeRandom) {
List<List<List<Card>>> course = new ArrayList<List<List<Card>>>();
for(Chapter chptr: courseToBeMadeRandom.getChapterList()) {
List<List<Card>> chapter = new ArrayList<List<Card>>();
course.add(chapter);
for(Deck dck: chptr.getDeckList()) {
List<Card> deck = new LinkedList<Card>();
chapter.add(deck);
for(Card crd: dck.getCardList()) {
if(dck.isTheCardDueToday(crd.getLastDate())) {
deck.add(crd);
}
}
Collections.shuffle(deck);
}
}
}
As I go through course, chapter and deck I create a List for each one. There is only one course, many chapters, many decks and of course many cards which are saved under deck doublyLinkedList if they pass the pre-condition. If no card passes the condition, I have a 3D list which exists but has no cards. And I want to determine that If no card exists in the list, then the user receives an error message.
In fact I only need the cards. But I also need to know in which deck each card resides at the moment. If I just make a list and go through all chapters and decks and put cards in that list based on the condition then I have no clue in which chapter and deck each card resides. That can be solved by maybe adding two attributes to the card class. But that was a mistake as we designed the system and adding them now costs a lot of change in other parts of the program. Each index in course List represents the chapter number and each index in chapter list represents the deck number. I solved the problem that way.
This should do it:
public static boolean isEmpty(List<List<List<Card>>> list3d) {
return list3d.stream().flatMap(llc -> llc.stream()).flatMap(lc -> lc.stream()).count() == 0;
}
It takes into account that the outer lists may contain empty inner lists. It deems the entire 3D list empty if there are no cards in it.
you can do something like this
List<List<List<Card>>> course = new ArrayList<List<List<Card>>>();
// some possible codes
boolean check = course.isEmpty()
// other possible codes
if (check) {
// do something
}
or any arraylist you want to check or any way you want to reach your goal
Related
I've been tasked with implementing an ADT for a deck of 52 cards. I have four files:
Stack.java (an interface)
Deck.java (which implements Stack)
Card.java (a simple object class with constructors, a toString method and get & set methods)
CardForce.java (the client application, where Deck is instantiated and iteratively populated with Card object references)
I need the program to display all the cards in the deck, which I've done in the Deck class like so:
public void show() {
Node current = topNode;
while (current != null) {
System.out.println(current.getData());
current = current.getNext();
}
}
This method is called in the CardForce client app simply as deck.show() - deck being the name of the variable of type Deck as such:
public static void testCardForceOperations() {
Stack<Card> deck = new Deck<Card>();
System.out.println("Adding 3♤, 4♡, 5♢, 6♧, 7♤, 8♡, 9♢, 10♧ to deck:");
Card card;
card = new Card(Card.Suit.SPADES, Card.Value.THREE);
deck.push(card);
card = new Card(Card.Suit.HEARTS, Card.Value.FOUR);
deck.push(card);
card = new Card(Card.Suit.DIAMONDS, Card.Value.FIVE);
deck.push(card);
card = new Card(Card.Suit.CLUBS, Card.Value.SIX);
deck.push(card);
card = new Card(Card.Suit.SPADES, Card.Value.SEVEN);
deck.push(card);
card = new Card(Card.Suit.HEARTS, Card.Value.EIGHT);
deck.push(card);
card = new Card(Card.Suit.DIAMONDS, Card.Value.NINE);
deck.push(card);
card = new Card(Card.Suit.CLUBS, Card.Value.TEN);
deck.push(card);
deck.show();
}
The code above is simply for testing purposes - to populate the ADT linked list with all 52 cards I use a for loop to create the Card objects.
The output I get is all of the Card objects references - rather than the cards themselves (e.g. Card#677327b6 Card#14ae5a5 Card#7f31245a etc).
I understand why this is happening - the Deck linked list isn't storing human readable information - it's storing references to Card type objects - but have hit a wall as to how to go about using the output to print human-readable data.
I was wondering if perhaps it was possible to iterate through the items stored in the ADT Deck linked list, returning them 1 by 1 to the client app then calling .toString() on them?
I've also got the suspicion that my implementation of the Card class is incorrect - that I should possibly be populating the ADT linked list in the Deck class, rather than doing so in the client app.
I am not sure how to do much with arrays yet and can't figure this out. Here is the full assignment.
Write a JAVA program that maintains a list of computer games using an array. Your main program should display the following menu repeatedly.
i. insert game
s. search game
p. print list
q. Quit
Select:
The array stores a list of computer games and each game in the list consists of title(string, key), developer(string), genre(string), year of production(int), and price(float). The list should be maintained in the increasing order of the key(title).
Option i should read a game(title, developer, genre, year, price) and insert the game into the array. Note that the new game should be inserted into the right spot so that the entire array may remain sorted. Sorting entire array again after adding the new game at the end of the array is costly and hence not acceptable. Option s asks for a game title and lists all the games matching with the title entered. Note that two or more games may have the same title. Option p simply lists all the games stored in the array.
We will assume a maximum of 100 games.
And here is what I have so far
package lab12;
import java.util.Scanner;
// create second class to hold methods
class next {
// create "insert game" method
public void insert( ) {
System.out.println("Insert");
}
// create "search game" method
public void search( ) {
System.out.println("Search");
}
// create "print list" method
public void print( ) {
System.out.println("Print");
}
// create method to
}
public class Lab12 {
public static void main(String[] args) {
Scanner in = new Scanner( System.in );
// create string to see what user wishes to do
String choose;
// create instance of other class
next choice = new next();
do {
// see which method user wants to use
System.out.print("Do you want to insert game (i) or search game (s) "
+ "or print list (p) or quit (q)? ");
// create string to see which method to go to
choose = in.nextLine();
// send user to correct method
if ( choose.equals("i") || choose.equals("I"))
choice.insert();
else if ( choose.equals("s") || choose.equals("S") )
choice.search();
else if ( choose.equals("p") || choose.equals("P") )
choice.print();
} while ( choose.equals("i") || choose.equals("s") || choose.equals("p")
|| choose.equals("I") || choose.equals("S") || choose.equals("P"));
}
}
I'm not sure how to sort the games in the array, it says to sort it by key but I don't know how to put in the key with the string. I'm not good with arrays either so I don't know how you can have all of the information linked together.
Thank you for all of your help!
Sincerely,
A stressed out college student.
Like Nimble Fungus stated, the first step is to create a Game class that will be your object representing games in your array.
If you're not concerned about efficiency, the Collections library had a built-in sorting method you can use. If you do need to worry about efficiency (for example, a massive data set) you should look into implementing a more advanced sorting algorithm. Although, I'm fairly certain Collections.sort implements Merge Sort, which should suffice in most situations.
To use Collections.sort on a datastructure containing objects, you must provide a Comparator in the method call:
Collections.sort(array, comparator);
For information on creating and using a comparator object, check out the documentation .
Also, if you plan on only using this comparator once, I might recommend creating an anonymous class, rather than creating a whole new class in your project. Here is the documentation for creating and using anonymous classes.
One last point to mention is that rather than creating a new comparator, you could actually have your Game class implement Comparable which would allow you to define the natural ordering of your Game objects at their creation.
John, create a POJO with all four parameters.
Sort the array or list on each insert using comparator. Use below link to know more .
http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator
Or u can even use sorted map with key as game name .
I have an ArrayList of x number of objects and wish to have a method that takes that ArrayList and produces new ArrayLists of size x-2 that represent all combinations of the objects in the original ArrayList.
For example, if I have an ArrayList of size 7 I would call this method and it would create ArrayLists that contain all possible combinations of the methods in the original ArrayList given the new size constraint.
I know a loop is needed but I'm having trouble with the logic. thanks
Here is what I have so far:
for (Card playerCard: playerHand) {
ArrayList<Card> FiveCHand = new ArrayList<Card>();
FiveCHand.add(playerCard);
for (Card communityCard: communityHand) {
FiveCHand.add(communityCard);
}
Collections.sort(FiveCHand, CardDomainModel.CardRank);
Hand hand = new Hand(FiveCHand);
FiveCardHands.add(hand);
}
Thanks for the code; it makes for a much better question.
If you permit me, I'd like to offer some feedback in order to get you to post the solution yourself. For that, we'll need all relevant code.
If you could add enough of the code we need to make a complete verifiable example then we know exactly what to change. Knowing what part of the code to post can be hard if you don't know how to solve the problem.
Your code could use some refactoring; this is pointed out by the fact that you never use the iteration variable playerHand. So, here are some questions and suggestions, inlined as comments:
// This is enough to make into a separate function. What would it's signature be?
// Also, what Class is this in?
for (Card playerCard: playerHand) { // playerhand not used!
ArrayList<Card> FiveCHand = new ArrayList<Card>(); // better: fiveCHand
FiveCHand.add(playerCard); // playerCard? where from?
for (Card communityCard: communityHand) { // there is Collections.addAll()
FiveCHand.add(communityCard);
}
Collections.sort(FiveCHand, CardDomainModel.CardRank);
Hand hand = new Hand(FiveCHand); // Why doesn't Hand take care of card list?
FiveCardHands.add(hand);
}
I am creating a video game were the player can enter and exit rooms. They may also enter rooms within room or sub-rooms. After all of the collision for this I come up with five Rectangle variables/arrays.
static Rectangle exitDoor[] = new Rectangle[1];
static Rectangle subExitDoor[] = new Rectangle[1];
static Rectangle roomDoor[] = new Rectangle[1];
static Rectangle roomLadder[] = new Rectangle[1];
static Rectangle roomInnerLadder[] = new Rectangle[1];
Each room can have multiple of each within. I would like to put all of these arrays within an array that creates two versions of them. What I mean is that if the final two dimesional array is named "room" than room[0][0] and room[1][0] (The second zero being the exitDoor array) would be two different values.
I have tried doing the below, but all it does is do the same thing as the first set of code.
Rectangle[][] roomCat = new Rectangle[][] { exitDoor, subExitDoor, roomDoor, roomLadder, roomInnerLadder };
I am not looking for someone to tell me how to make two dimensional arrays, I can al ready do that. I need someone to tell me how to take them to the next step.
Thanks,
Oak
Well, I didn't understand what you are trying to do with two dimensional arrays. Actually there is nothing special about two dimensional arrays, they are just array of arrays, if you know what I mean.
However if we look back what are you trying to do in the first place. It's not actually very complicated task.
Actually what you're trying to do is a very interesting concept in many areas such as mathematics and art, which is called self-referencing. You can see self-referencing in the paintings of Escher and in the conans of Bach. Take a look at the class below.
class Room {
Room outerRoom;
Room innerRoom;
Room(Room outerRoom, Room innerRoom) {
this.outerRoom = outerRoom;
this.innerRoom = innerRoom;
}
// goes to outerRoom
Room exit() {
return outerRoom;
}
// goes to innerRoom
Room enter() {
return innerRoom;
}
}
It's an implementation of a room in your game. As you mentioned there might be another room inside the room, therefore there might be another room outside the room. So if we want exit the room we go to outerRoom. What handy about this implementation is the outerRoom is a Room too. Therefore it contains inner and outer rooms as well.
You may think this class as a matryoshka doll however what we actually implemented is a basic linked list. You can look it up on the internet, and you can use it while you're making your game however it seems like you're looking for something more.
You want to have many rooms inside a room. What you're looking for is a tree, my friend. Look at the class below:
class Room {
Room outerRoom;
Room[] innerRooms;
// creates a room with n inner rooms
Room (Room outerRoom, int n) {
this.outerRoom = outerRoom;
this.innerRooms = new Room[0];
}
// sets nth room to innerRoom
void addRoom(int n, Room innerRoom) {
innerRooms[n] = innerRoom;
}
// goes to nth room
Room getRoom(int n) {
return innerRooms[n];
}
}
It's another implementation of a room in your game. Instead of having an inner room, we have an array of inner rooms this time. So you can have as many rooms as you want in the room however you can only have one room outside, just like a node of a tree.
So, I recommend you to look up linked lists and trees on the internet to understand the concept of this kind of self-referencing structures.
Also notice that if there isn't any room outside you can make it null, and if you don't want to have any inner rooms you can set the number of inner rooms to 0.
I hope it helps :).
I'm new to Java and I'm currently writing a program for an assignment that represents a 'sports league' (classes to represent player/club/match/league)
My main problems are occurring in the league class. Here are the relevant variables to give you an idea how I'm storing things:
public class League
{
private String leagueName;
private ArrayList<Club> clubs;
private ArrayList<Match> fixtures;
private ArrayList<String> results2;
private TreeMap<Match, String> results;
private String topTeam;
private String goldenBoot;
}
Currently trying to write a method in the League class which will print a 'league table' - i.e. a list of Clubs sorted by their points tally (held as variable in Club class) and I'm drawing a blank on it.
Further to this, I need to write two methods to find the top scorer (golden boot) and find the top team in the league; again I am drawing a blank. Perhaps I am overcomplicating things?
Would be very grateful for suggestions/sample methods
EDIT:
Ok, so that method I'm trying to write is something beginning with:
public void getLeagueTable() {
for(Club c : clubs) {
c.getTally();
}
}
which would give the tally value for each Club object - but how to sort these results, and how to associate the highest with one Club is what's really troubling.
To print the league table, you are going to need to sort the club array and then loop through each item and print the club name.
To sort the club array try using Collections.sort http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Collections.html
.. that is assuming you havent been told to implement your own algorithm
Again, more sorting required to get the top team and top scorer, then you will need to pick the top item from the sorted list.
Hope that helps...
You better use Set rather than ArrayList. And here is a good start for your question :
void printLeagueTable(){
i = 0 ;
while( i != clubs.size() ){
Club club = clubs.get(i);
System.out.println("club: "+i+ "points: " club.points() );
}
}