Keeping track of scores in Java - java

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() );
}
}

Related

java how to add variables to an object from a string

I have two objects that are being stored in arrays:
Game(String creator, String title, int releaseYear, int NumberSold)
Creator(String name, String gamesWorkedOn)
Game(creator) has multiple creators, so is stored as a string like this: "creator1, creator2, creator3" using commas to separate their values.
Not all games have multiple creators and there are not many different creators in total.
What I am trying to do is loop through an array of Game(games) and extract a creator variable from it and assign it to the Creator(name) and then match any games that creator is mentioned in and assign those title variables to Creator(gamesWorkedOn).
So far I have this:
public static void PopulateCreators(ArrayList<Game> games) {
//populating an array of Creators with games they have worked on
boolean match = false;
String thisCreator;
String gamesWorkedOn;
ArrayList<Creator> creatorArray = new ArrayList<Creator>();
for (int i = 0; i < games.size(); i++) {
thisCreator = games.get(i).getGameCreator();
thisCreator = thisCreator.replaceAll(", ", "\n");
Which gives me this output using a sysout:
Shigeru Miyamoto
Satoshi Tajiri
Yoshiaki Koizumi
Koichi Hayashida
Shigeru Miyamoto
My desired output would be to have something like this:
name = "Shigeru Miyamoto"
gamesWorkedOn = "game1, game2, game3"
I am looking at using a for loop but am unsure on how to implement it here.
Edit:
I forgot to mention a couple of details that I didn't think were important but I will be a bit clearer now. This is a Swing based project I am working on that takes user inputs and stores these arrays which are then saved into a JSON file that is read upon loading of the application and when a user clicks a 'save' button.
What you seem to want to do is map the creators to all the games that they have created or helped create. I'm going to start by creating a simplified version of the problem.
You have a list of:
class Game {
Set<Creator> creators;
}
which you want to convert to:
Map<Creator, Set<Game>> createdGames; // Map of creator name to games created
The first thing to do here is to find all of the unique creators to start adding to the map. This can be done with the stream API.
createdGames = gameList.stream().flatMap(game -> game.creators.stream()).distinct().collect(Collectors.toMap(Function.identity(), v -> new HashSet<>()));
Now you can just loop through all the games again and add the game to a creator's set if they took part in the creation of that game.
for(Game game : gameList) {
for(Creator creator : createdGames.keySet()) {
if(game.creators.contains(creator)) {
createdGames.get(creator).add(game);
}
}
}

How to Determine If a Collection Is Empty

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

I need to sort games in an array using title, developer, genre, etc

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 .

Java - Fancy Two Dimesional Arrays

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 :).

Making an add method for an ArrayList

So I am supposed to make an add method for an array list which adds a new movie object to the list if it doesnt exist, or if it finds a movie object with a similar title within the list, it just increases the quantity property of that object. Here is what I've got so far.
public void add(String title, double rating, int releaseYear){
if(this.myMovies.size() < 1)
{
Movie mymovie = new Movie(title, rating, releaseYear);
this.myMovies.add(mymovie);
}
else
{
for(int i = 0; i < this.myMovies.size(); i++)
{
Movie temp = this.myMovies.get(i);
if(temp.Title.equals(title)){
this.myMovies.get(i).quantity++;
break;
}
else
{
Movie mymovie = new Movie(title, rating, releaseYear);
this.myMovies.add(mymovie);
break;
}
}
}
}
My problem is that this ends up not taking account of similar names and doesn't increase the quantity but just adds another object to the list. I have a strong feeling that the problem lies within my For loop but I just can't identify it. Can anyone see anything that I may be doing wrong? Thank you!
You're testing only for equality, not similarity here:
if(temp.Title.equals(title)){
Instead, you should write a helper method to test for similarity based on whatever criteria are appropriate. For example:
if (isSimilar(temp.Title, title)){
and the isSimilar method might look something like this (assuming you don't need any input validation):
private void isSimilar(String title1, String title2) {
return title1.equalsIgnoreCase(title2)
|| title1.toLowerCase().contains(title2.toLowerCase())
|| title2.toLowerCase().contains(title1.toLowerCase());
}
or, perhaps more appropriately, like this (if you implement it in the Movie class):
private void isSimilar(otherMovie) {
return title.equalsIgnoreCase(otherMovie.title)
|| title.toLowerCase().contains(otherMovie.title.toLowerCase())
|| otherMovie.title.toLowerCase().contains(title.toLowerCase());
}
...in which case your if statement would also change slightly.
Keep in mind that I don't know what you consider 'similar'; only that the movies are considered similar if the names are similar.
A couple more comments:
Fields and method names generally start with a lowercase letter (so the field Movie.Title should instead be Movie.title).
It's usually preferable to loop over a Collection using an Iterator instead of using the raw index--partly because the Iterator should always know how to loop over the Collection efficiently.
Learn to use your IDE's debugger (it's probably very easy). Then you can step through each line of code to see exactly where your program is doing something unexpected.
I would do something like this:
public void add(String title, double rating, int releaseYear){
for(Movie m: myMovies.size())
{
if(m.Title.equals(title)){
m.quantity++;
return;
}
}
// movie with same title not found in the list -> insert
this.myMovies.add(new Movie(title, rating, releaseYear));
}
By the way: variable names should start with a lowercase character (Title -> title).
I'm addressing your "similarity" requirement. If you really want to do this properly it could be a lot of work. Essentially you have two strings and want to get a measure of the similarity. I am doing the same thing for figure captions and I plan to tackle it by:
splitting the title into words
lowercasing them
using them as features for classifier4J (http://classifier4j.sourceforge.net/)
That will go a long way based on simple word counts. But then you have the problem of stemming
(words that differ by endings - "Alien" and "Aliens"). If you go down this road you'll need to read up about Classification and Natural Language Processing

Categories