Increment map value when meeting conditions - java

I have hit a brick wall and the revision book isn't much help as it provides flat examples, my revision assignment requires me to declare a local variable of a type to reference a list, Teams, then if should get the list of teams for the key value division, and assign it to the local variable.
It then ask me to increment the number of wins for teamA if it has a higher score than teamB and vice versa, if it is a draw then increment the number of draws.
I have managed to write the method to iterate over the list and an if-else statement to check he given arguments using a .get() method which works
The problem I am having is accessing in the incWon() method in the Team class to change the value of won for each map value. The material though gives quite flat examples of how map values are to be changed which don't really explain how I can change a value using a dynamic input.
any help would be greatly appreciated as if I can get won to work the rest will fall into place.
This is my class
{
private SortedMap<String, Set<Team>> teams;
/**
* Constructor for objects of class LeagueAdmin
*/
public LeagueAdmin()
{
// Create the HashMap
//Map<String, Team> teams = new HashMap<>();
super();
this.teams = new TreeMap<>();
}
public void addTeam(String division, Team team)
{
boolean changed;
if (!this.teams.containsKey(division)) // checks if the key division doesn't contain the value of divsioin
{
HashSet<Team> teamSet = new HashSet<>(); // instantiates a list of objects called Team and assigns them to local variable teamSet
teamSet.add(team); // adds a new team to the list
this.teams.put(division, teamSet);
changed = true;
}
else
{
Set<Team> teamSet = this.teams.get(division); // if list exists already adds new team to existing list
changed = teamSet.add(team);
}
}
public void recordResult(String division, String teamA, String teamB, int teamAScore, int teamBScore)
{
Set<String> teamKeys = teams.keySet();
for (String eachDivision: teamKeys)
{
if(teamAScore > teamBScore)
{
teams.put(); // updates wins for teamA
// System.out.println(teamA);
}
else if (teamAScore < teamBScore)
{
teams.get(teamB); // updates wins for teamB
// System.out.println(teamB);
}
else
{
// teams.put(); //updates draws for both teams
}
// System.out.println(eachDivision + " teams are " + teams.get(eachDivision));
}
}
}
and this the TEAM class I am have to access to increment values.
public class Team
{
private String name;
private String division;
private int won;
private int drew;
private int lost;
// no need to record points as = 3*won + drew
/**
* Constructor for objects of class Team
*/
public Team(String aName, String aDivision)
{
name = aName;
division = aDivision;
// no need to set won, drew and lost to 0
}
/**
* getter for attribute points
*/
public int getPoints()
{
return 3 * won + drew;
}
/**
* getter for name
*/
public String getName()
{
return name;
}
/**
* getter for division
*/
public String getDivision()
{
return division;
}
/**
* getter for won
*/
public int getWon()
{
return won;
}
/**
* getter for drew
*/
public int getDrew()
{
return drew;
}
/**
* getter for lost
*/
public int getLost()
{
return lost;
}
/**
* increments the number of games won
*/
public void incWon()
{
won = won + 1;
}
/**
* increments the number of games drawn
*/
public void incDrew()
{
drew = drew + 1;
}
/**
* increments the number of games lost
*/
public void incLost()
{
lost = lost + 1;
}
/**
* setter for division
*/
public void setDivision(String aDivision)
{
division = aDivision;
}
public String toString()
{
return ("Team " + name + ", division: " + division + " stats: Won: " + won
+ ", drew: " + drew + ", lost: " + lost + ", points: " + getPoints());
}
}

I think you misunderstood the data structure requirement. You're looping through a list of teams, and never updating the loop variable. I believe the data structure should be something more like this:
private Map<String, Map<String, Team>> teams;
Using the division for the outer map key, and the team name for the inner map key. This separates div1's teamA from div2's teamA
This simplifies your recordResult method to pulling the specific team and updating them accorrdingly
public void recordResult(String division, String teamA, String teamB, int teamAScore, int teamBScore)
{
Map<String, Team> teamKeys = teams.get(division);
if(teamAScore > teamBScore)
{
teams.get(teamA).incWon(); // updates wins for teamA
}
else if (teamAScore < teamBScore)
{
teams.get(teamB).incWon(); // updates wins for teamB
}
else
{
teams.get(teamA).incDrew();
teams.get(teamB).incDrew();
}
}

Related

Array Loop is printing a reference instead of a string [duplicate]

This question already has answers here:
How to override toString() properly in Java?
(15 answers)
Closed 4 years ago.
I have been provided with an object and several methods to work with it. I am having a tough time printing the string that I am assigning to the variables. At the moment, I am unsure if I assigning new values at all and I am unable to print any values. Previous iterations have only printed references.
Question: Am I assigning new string values? How do I print a string with the given methods?
Here is the code I was provided
public class Team implements Comparable<Team> {
public String toString(String team, int wins) {
return team + ": " + wins;
}
// Data fields
private String name;
private int winCount;
Team() {
name = "Sooners";
winCount = 1;
}
Team(String inputName) {
name = inputName;
winCount = 1;
}
Team(String inputName, int inputWinCount) {
name = inputName;
winCount = inputWinCount;
}
// ----------------------------------------------------
// Getters and Setters
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name
* the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the winCount
*/
public int getWinCount() {
return winCount;
}
/**
* #param winCount
* the winCount to set
*/
public void setWinCount(int winCount) {
this.winCount = winCount;
}
/**
* Increments the winCount variable by one for this Team
*/
public void incrementWinCount() {
winCount++;
}
/**
* This method allows you to check to see if this Team object has the same
* name as another Team object.
*
* This method allows you to use the contains method in ArrayList to see
* if any element in an array list has the same name as a specific Team.
*
* #param o
* the other Team being compared to.
*/
#Override
public boolean equals(Object o) {
return name.equals(((Team) o).name);
}
/**
* This method allows you to check to see if this Team object has the same
* name as another Team object
*
* #param otherTeam
* one team
*/
public boolean sameName(Team otherTeam) {
return name.equals(otherTeam.name);
}
/**
* This method allows you to check to see if this Team object has the same
* name as another Team object
*
* #param team1
* one team
* #param team2
* the other team
*/
public static boolean sameName(Team team1, Team team2) {
return team1.name.equals(team2.name);
}
/**
* This method allows you to sort an ArrayList of Team items using
* Collections.sort
*
* #param o
* the other Team being compared to.
* #return -1 if this Team item should come first, +1 if this Team item
* should come after the other, and 0 if this Team item is
* equivalent to the other.
*/
#Override
public int compareTo(Team o) {
if (this.winCount < o.winCount) {
return -1;
} else if (this.winCount > o.winCount) {
return 1;
}
return 0;
}
}
Here is my current code
Scanner scnr = new Scanner(System.in);
Random rando = new Random();
String name = "no";
int cycles = 0;
int value = 0;
int match = 0;
ArrayList<Team> teams = new ArrayList<Team>();
Team newTeam = new Team(name,1);
System.out.println("Welcome to the Advanced Sportsball Tracker!");
while (!name.equals("x")) // looping print statement
{ // x loop begins
System.out.println("Which team just won? (x to exit)");
match = 0;
cycles++;
name = scnr.next();
for (Team list : teams)
{
if (list.getName().equals(name)) // compares the name of the team to the input value
{
match++;
}
}
if (match == 0)
{
teams.add(newTeam);
}
}// x loop ends
System.out.print(newTeam.getName());
if (cycles == 1) // prints no data if user immediately exits
{
System.out.println("No data input");
}
if (cycles > 1)
{
System.out.println("Final Tally: "); // loop to print final Talley
for (Team list : teams) // FIXME
{
list.toString(list.getName(),list.getWinCount()); // makes a string out of the string and wincount of the team
}
What was the original code for the toString method they gave you? Did you add the parameters? A better way to do this would be to let the object use it's data fields inside of the method. Passing in the member variables in your for loop is unnecessary, and just bad code. Instead, you want to do something like this:
public String toString() {
return name + ": " + wins;
}
And in your loop, if you want to print the results, simply do this:
System.out.print(list.toString());

Car Search java

In one of my classes we created a program that randomly creates 10 cars with the price and star rating. Right now the program creates the 10 objects and then creates another object that it compare the 10 to. It searches by the star rating, sorts the 10 by star rating, then runs a binary search on the 10 objects. I have been trying to improve on it by adding in the car manufacturer name to each object but keep messing up the program. The program has two classes
import java.util.*;
import java.util.Scanner;
public class Sorter{
static Car [] ary; // declare
final static int NUM_CARS = 10;
public static void main() {
//Scanner rating = new Scanner(System.in);
//int r = rating.nextInt();
Car key = new Car();
ary = new Car[NUM_CARS]; // initialize
int i;
int position;
for (i=0; i<NUM_CARS; i++) {
ary [ i ] = new Car();
}
System.out.println("Unsorted:");
System.out.println(Arrays.toString(ary));
System.out.println("Sequential search for " + key);
ary[0].reset();
position = sequentialSearch(key)+1; //add one to the index position to display the position on screen that the user's desired search is first found
System.out.println("Total comparisons: "
+ ary[0].getAllCount());
System.out.println("Found a position: " +position);
System.out.println();
System.out.println("Sorted:");
ary[0].reset();
Arrays.sort(ary);
System.out.println("Total comparisons: "
+ ary[0].getAllCount());
System.out.println(Arrays.toString(ary));
System.out.println("Binary search for " + key);
ary[0].reset();
position = binarySearch(key)+1; //add one to the index position to display the position on screen that the user's desired search is first found
System.out.println("Found a position: " +position);
System.out.println("Total comparisons: "
+ ary[0].getAllCount());
}
public static int binarySearch (Car keyCar) {
return Arrays.binarySearch(ary,keyCar);
}
public static int sequentialSearch (Car keyCar) {
int pos = -1;
int i;
int answer;
for (i=0; i<ary.length; i++) {
answer = ary[i].compareTo(keyCar);
if (answer==0) {
pos = i;
break;
}
}
return pos;
}
}
Second class
import java.util.*;
/**
* in class work
*/
public class Car implements Comparable<Car> {
// instance variables - replace the example below with your own
int stars;
double price;
String name [] = {"Ford", "Dodge", "Chevrolet", "Honda", "Toyota", "VW", "Hyundai"};
int myCounter;
static int allCounter;
/**
* Constructor for objects of class Sorter
*/
public Car() {
Random generator = new Random ();
price = generator.nextDouble()*50000 + 50000;
stars = generator.nextInt(5)+1;
reset();
}
public String toString()
{
return String.format("$%,7.0f(%d stars)",price,stars);
//$ put dollar sign infront
//up to 7 digits
//, puts commas
}
/**
* Resets counter to zero
*/
public void reset(){
myCounter=0;
allCounter=0;
}
public int getMyCount() {
return myCounter;
}
public int getAllCount() {
return allCounter;
}
/**
* #param other A house to compare to.
* #return Returns 0 if they are equal
*/
public int compareTo(Car other)
{
myCounter++;
allCounter++;
if (this.stars < other.stars) {
return -1;
} else if (this.stars> other.stars) {
return +1;
}
return 0; // equals
}
}
How do I make it so that the objects will display the price, star rating, and the manufacturer?
Also, another thing I'd like to do but haven't tried yet is making it so the user can input what star rating they want and it'll display those cars only. This part is the next thing I'd like to try when time comes around to do so.
To associate data with an object, a variable to store that data needs to be in the object's constructor. So, to associate a manufacturer with each car object, you'll have to add String manufacturer or something similar as a variable in your Car class's constructor. It seems like you would then want to set that manufacturer variable to a random element of your String name [] array.
To make the car "display" the manufacturer variable you just created, you would have to modify the toString() method in your car class to print manufacturer as well as price and stars.

Java PhoneBook using ArrayList

Im trying to make a PhoneBook using array list but I'm not getting the right output here is my code, thank you for any help with this, the output I'm getting now is just a zero when i ask for the size, not seeming to add anyone, that is probably where the problem lies
import java.util.ArrayList;
public class Phonebook implements Directory
{
private ArrayList<Person> book;
public Phonebook ()
{
book = new ArrayList<Person>();
}
/**
* will return the number of entries currently entered in
* the <code>Directory</code>.
* #return - the number of valid entries in the <code>Directory</code>.
**/
public int size()
{
return book.size();
}
/**
* will display the entries currently entered in the <code>Directory</code>.
**/
public void listAll()
{
for(int i = 0; i < book.size(); i++)
{
System.out.println(book.get(i));
}
}
/**
* will add a new record to the <code>Directory</code> in alphabetical order
* if the name is not a duplicate entry. Otherwise no changes will be made.
* #param name - name of individual to be added to the <code>Directory</code>.
* #param number - phone number of the individual to be added.
* #return - true if the entry was added successfully, otherwise false.
**/
public boolean addPerson(String name, String number)
{
Person x = new Person (name, number);
if (checkPerson(name) == -1)
return false;
int index = 0;
while(index < book.size())
{
if((x.getName().compareTo((book.get(index)).getName())) < 0)
{
book.add(x);
return true;
}
index++;
}
return false;
}
public int checkPerson(String name)
{
int lo = 0;
int hi = book.size() - 1;
while(lo <= hi)
{
int half = (lo + hi) / 2;
if(name.equals(book.get(half).getName()))
return half;
if(name.compareTo(book.get(half).getName()) < 0){
hi = half - 1;}
else lo = half + 1;
}
return -1;
}
/**
* will remove an entry from the <code>Directory</code> if the name parameter
* is currently in the <code>Directory</code>. Otherwise no changes
* will be made.
* #param name - individual to be removed from the <code>Directory</code>.
* #return - true if the entry was successfully removed, otherwise false.
**/
public boolean removePerson(String name)
{
if (checkPerson(name) == -1)
return false;
book.remove(checkPerson(name));
return true;
}
/**
* will search the <code>Directory</code> to find out if the name passed in
* is currently in the <code>Directory</code>. If so, it will return the
* phone number associated with this person. Otherwise it will return null.
* #param name - name of individual to look up in the <code>Directory</code>.
* #return - the phone number if the name was found, otherwise null.
**/
public String lookUp(String name)
{
Person n = new Person (name, "999-9999");
int local = checkPerson(n.getName());
if(local == -1)
return null;
return book.get(local).getNumber();
}
/**
* will search the <code>Directory</code> to find out if the phone number
* is currently in the <code>Directory</code>. If so, it will return the
* name associated with this number. Otherwise it will return null.
* #param number - name of individual to look up in the <code>Directory</code>.
* #return - the name of the person if the number was found, otherwise null.
**/
public String lookUpNum(String number)
{
for(int i = 0; i <book.size(); i++)
{
if(number.equals(book.get(i).getNumber()))
return book.get(i).getName();
}
return null;
}
}
/**
* The Person class is a container class to hold the
* name and phone number of an individual. There are methods
* to access the name and number, and modify the name and number.
* Each name is stored in "Last, First" form to facilitate searching
* and sorting of persons. A private helper method is used to be
* sure that names entered in "First Last" form are converted to
* the proper format.
*/
public class Person implements Comparable<Person>
{
private String first;
private String last;
private String name; // Last, First
private String number;
/**
* explicit constructor, will store the first and last
* names, as well as the entire name in Last, First order
*
* #param na is the name of the individual
* #param nu is the phone number of the individual
*/
public Person(String na, String nu)
{
convert(na);
number = nu;
}
/**
* copy constructor, will make an exact copy of the parameter
*
* #param per is the <B>Person</B> to be duplicated
*/
public Person(Person per)
{
first = per.first;
last = per.last;
name = per.name;
number = per.number;
}
/**
* accessor method to return the name of <B>this Person</B>
*
* #return the name of the individual in Last, First order
*/
public String getName()
{
return name;
}
/**
* accessor method to return the phone number of <B>this Person</B>
*
* #return the phone number of the individual
*/
public String getNumber()
{
return number;
}
/**
* modifier method to set a new name for <B>this Person</B>
* The helper method convert() is called to handle the details
*
* #param the new name for the individual
*/
public void setName(String na)
{
convert(na);
}
/**
* modifier method to set a new phone number <B>this Person</B>
* just in case somebody needs to enter witness protection
*
* #param the new phone number for the individual
*/
public void setNumber(String num)
{
number = num;
}
/**
* accessor method that implements the <B>Comparable interface</B>
* based on the name field for <B>this Person</B>
* will return a positive number if <B>this</B> is greater than oth
* zero if <B>this</B> is equal to oth
* and a negative number if <B>this</B> is less than oth
*
* #return negative, zero, or positive int as per Comparable interface
*/
public int compareTo(Person oth)
{
return name.toUpperCase().compareTo(oth.name.toUpperCase());
}
/**
* accessor method to test if the instance data for <B>this Person</B>
* is equal to the instance data for oth
*
* #return true if names and numbers match, false otherwise
*/
public boolean equals(Person oth)
{
return name.toUpperCase().equals(oth.name.toUpperCase()) && number.equals(oth.number);
}
private void convert(String na)
{
if(na.indexOf(" ") == -1)
{
last = na;
first = null;
name = na;
}
else if(na.indexOf(",") != -1)
{
name = na;
first = na.substring(na.indexOf(",") + 2);
last = na.substring(na.indexOf(","));
}
else
{
first = na.substring(0, na.indexOf(" "));
last = na.substring(na.indexOf(" ") + 1);
name = last + ", " + first;
}
}
/**
* accessor method to return the instance data of <B>this Person</B>
* in a formatted String (24 character name field, followed by the number)
*
* #return name in Last, First order followed by the phone number
*/
public String toString()
{
String local = name;
if(name.length() < 8)
local += "\t";
if(name.length() < 16)
local += "\t";
local += "\t" + number;
return local;
}
}
public class client
{
public static void main(String[] args)
{
Phonebook nickBook = new Phonebook();
nickBook.addPerson("name lastname", "321-3256");
System.out.println();
nickBook.listAll();
System.out.println(nickBook.size());
}
}
Your addPerson method won't add the Person if the list is empty, since while (0 < 0) will be false, and the loop won't be entered :
int index = 0;
while(index < book.size())
{
if((x.getName().compareTo((book.get(index)).getName())) < 0)
{
book.add(x);
return true;
}
index++;
}
Beside that problem, book.add(x); will always add the new Person to the end of the List, which is not what you want. You should use book.add(index,x), assuming index is the location in which you wish to add the new Person.
Finally, if the new Person wasn't added inside the while loop, that means this Person should be the last Person on the List, so you have to add it to the end of the List after the loop.
A possible implementation :
public boolean addPerson(String name, String number)
{
Person x = new Person (name, number);
if (checkPerson(name) == -1)
return false;
int index = 0;
while(index < book.size())
{
if((x.getName().compareTo((book.get(index)).getName())) < 0)
{
book.add(index,x);
return true;
}
index++;
}
book.add(x); // this handles both the case of an empty List and the
// case in which the new Person should be the last Person
// on the list
return true;
}
Your function checkPerson is wrong. book.size() is 0 in the beginning and the hi results to -1 which means that it does not enter the loop. Besides that think about your half variable. It is possible that this results in another number than an integer which is not allowed if you are using this variable as an index for a query of the list.
public int checkPerson(String name)
{
int lo = 0;
int hi = book.size() -1;
while(lo <= hi)
{
int half = (lo + hi) / 2;
if(name.equals(book.get(half).getName()))
return half;
if(name.compareTo(book.get(half).getName()) < 0){
hi = half - 1;}
else lo = half + 1;
}
return -1;
}

Modify DataSet to accept Comparable objects

I need to modify DataSet to accept Comparable Objects. The tester will not compile and I do not know how to print out the compareTo method. Should I be using an ArrayList for the tester? Thanks ahead of time!
public interface Comparable
{
/**
Compares this object with another.
#param other the object to be compared
#return a negative integer, zero, or a positive integer if this object
is less than, equal to, or greater than, other
*/
int compareTo(Object other);
}
public class DataSetComparable
{
private double sum;
private Object maximum;
private Object minimum;
private int count;
private Comparable comparer;
/**
Constructs an empty data set with a given measurer.
#param aMeasurer the measurer that is used to measure data values
*/
public DataSetComparable(Comparable acomparer)
{
sum = 0;
count = 0;
maximum = null;
minimum = null;
comparer= acomparer;
}
/**
Adds a data value to the data set.
#param x a data value
*/
public void add(Object x)
{
sum = sum + comparer.compareTo(x);
if (count == 0 || comparer.compareTo(maximum) < comparer.compareTo(x))
maximum = x;
if (count == 0 || comparer.compareTo(minimum) > comparer.compareTo(x))
minimum=x;
count++;
}
/**
Gets the largest of the added data.
#return the maximum or 0 if no data has been added
*/
public Object getMaximum()
{
return maximum;
}
/**Gets the smallest of the added data.
*#return the minimum or 0 if no data has been added
**/
public Object getMinimum()
{
return minimum;
}
}
public class String implements Comparable {
private String input;
private int holder;
public String(String aninput){
input= aninput;
holder=0;
}
public String getComparer(){
return input;
}
public String getString(){
return input;
}
public int compareTo(Object other){
String temp= (String) other;
if(input.compareTo(temp)<0){
holder=-1;
}
else if (input.compareTo(temp)== 0) {
holder= 0;
}
else{
holder= 1;
}
return holder;
}
}
public class StringTester{
public static void main (String [] args){
Comparable c = new String();
DataSetComparable data = new DataSetComparable(c);
data.add(new String("Jimmy"));
data.add(new String("Amy"));
data.add(new String("Melissa"));
data.add(new String("Melissa"));
String max = (String) data.getMaximum();
String min = (String) data.getMinimum();
System.out.println("Maximum String = " + max);
System.out.println("Minimum String = " + min);
}
}
More specifically, the error says:
constructor String in class String cannot be applied to given types.
Your code includes this:
public class String implements Comparable {
...
}
Do you realize that there is a standard Java library class called String that gets imported by default into every class? If implement your own class called String you are going to get some very confusing compilation error messages.
I strongly recommend that you change the name of your class to something else; e.g. StringHolder.
Note, technically you could define a class called String. However the rules that Java uses to disambiguate the names of classes are not designed for this use-case ... and you will end up having to refer to java.lang.String by its fully qualified name wherever you use it. And other people reading / modifying your code would find that really awkward / annoying.
It is best to treat the names of classes in the java.lang package as "reserved", and don't define classes with the same (unqualified) name.

How to count occurence of the same number in an arraylist in java?

I have an arraylist in java where the content is added from input of the user. The user add name, number for the month and a number for the year. Like this: Name: Bob, month: 4, year: 11
My task is to find how many user have added the same month number to the arraylist. Count the occurence of the same month number and print it out.
I know I must iterate over the arraylist and to store the occurence somwhere until the iterator have finished to search trough the collection of the arraylist and then print out how many times the same month number has been added.
I am quiet stuck on this task. Even tough it is an easy task.
Thank for your help!
I have three classes
public class Person
{
// The name of this user.
private final String name;
/**
* Create a new user with the given name.
* #param name The user's name.
*/
public Person(String name)
{
this.name = name;
}
/**
* #return The user's name.
*/
public String getName()
{
return name;
}
}
/////////////////////////////////
/**
* Store details of a club membership.
*
*/
public class Membership
{
// The name of the member.
private String name;
// The month in which the membership was taken out.
private int month;
// The year in which the membership was taken out.
private int year;
/**
* Constructor for objects of class Membership.
* #param name The name of the member.
* #param month The month in which they joined. (1 ... 12)
* #param year The year in which they joined.
*/
public Membership(String name, int month, int year)
throws IllegalArgumentException
{
if(month < 1 || month > 12) {
throw new IllegalArgumentException(
"Month " + month + " out of range. Must be in the range 1 ... 12");
}
this.name = name;
this.month = month;
this.year = year;
}
/**
* #return The member's name.
*/
public String getName()
{
return name;
}
/**
* #return The month in which the member joined.
* A value in the range 1 ... 12
*/
public int getMonth()
{
return month;
}
/**
* #return The year in which the member joined.
*/
public int getYear()
{
return year;
}
/**
* #return A string representation of this membership.
*/
public String toString()
{
return "Name: " + name +
" joined in month " +
month + " of year " + year;
}
}
////////////////////////////////////////////
import java.util.ArrayList;
import java.util.Iterator;
/**
* Store details of club memberships.
*
*/
public class Club
{
// Define any necessary fields here ...
private ArrayList club;
// private String member = club;
private int joined;
/**
* Constructor for objects of class Club
*/
public Club()
{
// Initialise any fields here ...
club = new ArrayList();
}
/**
* Add a new member to the club's list of members.
* #param member The member object to be added.
*/
public void join(Membership member)
{
club.add(member);
//System.out.println(member);
}
//////////////////////////////////////////////////////////
// public int getJoined()
// {
// return joined;
// }
//////////////////////////////////////////////////////////
/**
* #return The number of members (Membership objects) in
* the club.
*/
public int numberOfMembers()
{
return club.size();
}
///////////////////////////////////////////////////////////////////////////////////
public int joinedInMonth(int month)
{
//int joined = month;
if(month < 1 || month > 12)
{
System.out.println("Not a valid month");
}
else{
// int countMonth(ArrayList<Person> person, int month)
{
int count = 0;
for (Club club : people)
if (person.getMonth() == month) count++;
return count;
}
}
// using traditional for loop
// int joined = month;
// for(int i = 0; i < club.size(); i++)
// {
// System.out.println(i+1 + ": " + club.get(i));
// }
//
// for(Iterator i = club.iterator();i.hasNext();)
// {
//
// System.out.println(i.next());
//
//
// }
return 0;
}
}
/////////////////////////////////////////
This is what I have so far with the method to count occurence of the same number in the arraylist:
public int joinedInMonth(int month)
{
int joined = month;
if(joined < 1 || joined > 12){
System.out.println("Not a valid month");
}
else{
int count = 0;
Iterator it = club.iterator();
while(it.hasNext()) {
Membership membership = (Membership) it.next();
if(joined == membership.getMonth());count++;
System.out.println("Month " + membership.getMonth());
return count;
but I cant understand how I can store the value from count into a new arraylist?
Any help?
Since you haven't posted for 2 hours, here's one way:
class Person {
String name;
int month;
int year;
// with getters()
}
int countMonth(List<Person> people, int month) {
int count = 0;
for (Person person : people)
if (person.getMonth() == month) count++;
return count;
}
For this kind of task a would use a Hashtable<Integer, List<Person>> where all person of a particular month would be index toghether in one List.
Hashtable<Integer, List<Person>> index = new Hashtable<Integer, List<Person>>();
for (Person person : persons) {
if (index.get(person.month) == null) {
index.put(person.month, new ArrayList<Person>());
}
index.get(person.month).add(person);
}
The you can retrive a list of person according to their month.
This code will only print the month and the number of persons contained in list.
for (int i = 1; i <= 12; i++) {
int count = 0;
if (index.get(i) != null) {
count = index.get(i).size();
}
System.out.println("%d: %d", i, count);
}
Hashtables are really nice for this kind of tasks were you have to regroup elements toghether or access an value using a key (here its the month as an Integer and the value is List<Person>).

Categories