My project involves 2 classes: Members & Society.
Currently I have written a method 'removeMembers()' in the Society Class that when given a particular month and year, it removes all the members who fit the description.
However, how would I create a separate collection class object which returns the deleted members?
Any help or advice on this will be appreciated, I will also post my code for both classes.
Society Class:
public class Society
{
private ArrayList<Member> myMembers;
private Member member;
private String societyName;
private boolean feesPaid;
public Society(String society)
{
myMembers = new ArrayList<Member>();
this.societyName = society;
}
public String getSocietyName()
{
return societyName;
}
public void join(Member member)
{
myMembers.add(member);
}
public void showMember(int listPosition)
{
Member member;
if( listPosition < myMembers.size() )
{
member = myMembers.get(listPosition);
System.out.println("Position " + listPosition + ": " + member);
}
}
public void joinedInMonth(int joined) {
if (joined > 12 || joined < 1) {
System.out.println("Invalid number. Please enter a number from 1 - 12.");
}
long joinedMonth = myMembers.stream().filter(m -> m.getMonth() == joined).count();
System.out.printf("%d members have joined this society on month %d%n", joinedMonth, joined);
}
public int numberOfMembers()
{
return myMembers.size();
}
public void printDetails()
{
for (Member m : myMembers) {
System.out.println("Society Name: " + societyName);
System.out.println(m.toString());
System.out.println("--------------------------");
}
}
public void removeMembers(int month, int year) {
myMembers.removeIf(m -> m.getYear() == year && m.getMonth() == month);
}
public void payFees(Member member)
{
if (member.isFeesPaid()) {
System.out.println("Fees has been paid");
return;
}
}
}
Member Class:
public class Member
{
private int month;
private int year;
private String name;
/*private Society society;*/
private List<Society> societies;
private boolean feesPaid;
public Member(String name, int month, int year /*Society society*/)
{
this.name = name;
this.month = month;
this.year = year;
this.societies = new ArrayList<>();
}
public void joinSociety(Society society)
{
societies.add(society);
}
public boolean isFeesPaid() {
return feesPaid;
}
public int getYear()
{
return year;
}
public int getMonth()
{
return month;
}
public String getName()
{
return name;
}
public String toString()
{
return "Name: " + name + ", Month Joined: " + month + ", Year Joined: " + year;
}
You can create a new List in removeMembers() method and add the removed objects to list and return it. remove(Object o) method in arraylist will return the removed object and remaining methods remove(int index), removeIf(Predicate<? super E> filter) and removeRange(int fromIndex, int toIndex) will not return removed object
public List<Members> removeMembers(int month, int year) {
List<Members> deletedMembers= new ArrayList<>();
Iterator<Members> members = myMembers.iterator();
while (members.hasNext()) {
Member member = members.next();
if (member.getYear()==year && member.getMonth()==month) {
deletedMembers.add(members.remove());
}
}
return deletedMembers;
}
Related
I'm trying to implement this enum into my program so that it will return the String equivalent of the enum value. So for example, if the value of dept = 3, then it will return Printed Books & eBooks.
This is what I have so far and it doesn't seem to work because when I go to my program tester class and I try to add a new OrderItem it says that the constructor is undefined once I enter an integer from 0-5 for the Department part of the constructor.
Does anyone have any ideas about what I am doing wrong?
The enum
public enum Department {
ELECTRICAL(0), PHOTOGRAPHIC(1), COMPUTING(2), BOOKS(3), MUSIC(4), FASHION(5);
private int dNum;
private static String dept[] = { "Electrical & Electronics", "Cameras & Photography", "Laptops, Desktops & Consoles",
"Printed Books & eBooks", "MP3 & CD Music", "Fashion & Accessories" };
private Department(int num) {
dNum = num;
}
public String toString() {
return dept[dNum];
}
}
The program
public class OrderItem {
private int itemCode;
private String itemName;
private String itemSupplier;
private double itemCost;
private Department dept;
private static int nextCode = 1;
public OrderItem(String itemName, String itemSupplier, double itemCost, Department dept) {
setItemName(itemName);
setItemSupplier(itemSupplier);
setItemCost(itemCost);
setDepartment(dept);
}
public void setItemName(String itemName) {
if (itemName != null) {
this.itemName = itemName;
} else {
if (this.itemName == null)
// a default value
this.itemName = "Unknown";
}
}
public void setItemSupplier(String itemSupplier) {
if (itemSupplier != null) {
this.itemSupplier = itemSupplier;
} else {
if (this.itemSupplier == null)
// a default value
this.itemSupplier = "Unknown";
}
}
public void setItemCost(double itemCost) {
this.itemCost = itemCost;
}
public void setDepartment(Department dept) {
this.dept = dept;
}
public void setDepartment(int dept) {
if (dept == 0)
setDepartment(Department.ELECTRICAL);
else if (dept == 1)
setDepartment(Department.PHOTOGRAPHIC);
else if (dept == 2)
setDepartment(Department.COMPUTING);
else if (dept == 3)
setDepartment(Department.BOOKS);
else if (dept == 4)
setDepartment(Department.MUSIC);
else if (dept == 5)
setDepartment(Department.FASHION);
}
public String getItemName() {
return this.itemName;
}
public String getItemSupplier() {
return this.itemSupplier;
}
public double getItemCost() {
return this.itemCost;
}
public String getDepartment() {
return dept.toString();
}
public int useNextCode() {
itemCode = nextCode;
nextCode++;
return itemCode;
}
public String getDetails() {
String result = "Item name: " + getItemName() + "\n Supplier: " + getItemSupplier() + "\n Department: "
+ getDepartment() + "\n Cost: " + getItemCost();
return result;
}
public String toString() {
System.out.println("Item Code: " + useNextCode());
return getDetails();
}
}
You cannot pass Integer (0-5) in your OrderItem Constructor. Instead you need to pass the desired enum. This should work fine.
OrderItem oi = new OrderItem("PenDrive","HP",300.0, Department.ELECTRICAL);
As the title question was how to return the String value for enum, the answer could be to refactor the enum to have description field instead of inner static array of strings, and add a method to retrieve Department by the ordinal value:
public enum Department {
ELECTRICAL("Electrical & Electronics"),
PHOTOGRAPHIC("Cameras & Photography"),
COMPUTING("Laptops, Desktops & Consoles"),
BOOKS("Printed Books & eBooks"),
MUSIC("MP3 & CD Music"),
FASHION("Fashion & Accessories");
private String description;
private Department(String description) {
this.description = description;
}
public String toString() {
return this.description;
}
public static Department byNum(int ordinal) {
if (ordinal < ELECTRICAL.ordinal() || ordinal > FASHION.ordinal()) {
return null; // or throw IllegalArgumentException
}
return Department.values()[ordinal];
}
}
Then method OrderItem::setDepartment(int dept) may be changed like this (instead of multiple if statements):
public static void setDepartment(int dept) {
Optional.ofNullable(Department.byNum(dept))
.ifPresent(OrderItem::setDepartment);
}
I have a Java project that requires me to have two classes called: Pokemon.java and Move.java so I can add new Pokemon and their moves. I’ve already written all of the methods that were required for the project but I’m having issues storing and modifying the moves, specifically the forgetMove method in the Pokemon class.
Here’s the code for Pokemon.java:
public class Pokemon
{
// Private constants
private static final int MAX_HEALTH = 100;
private static final int MAX_MOVES = 4;
private String name;
private int health;
private Move move;
// Write your Pokemon class here
public Pokemon(String theName, int theHealth)
{
name = theName;
if(theHealth <= MAX_HEALTH)
{
health = theHealth;
}
}
public String getName()
{
return name;
}
public int getHealth()
{
return health;
}
public boolean hasFainted()
{
if(health <= 0)
{
return true;
}
else
{
return false;
}
}
public boolean canLearnMoreMoves()
{
if(Move.getNumOfMoves() < 4)
{
return true;
}
else
{
return false;
}
}
public boolean learnMove(Move move)
{
if(canLearnMoreMoves())
{
this.move = move;
return true;
}
else
{
return false;
}
}
public void forgetMove(Move other)
{
if(Move.equals(other))
{
move -= other;
}
}
public String toString()
{
return name + " (Health: " + health + " / " + MAX_HEALTH + ")";
}
}
and here is the code for Move.java:
public class Move
{
// Copy over your Move class into here
private static final int MAX_DAMAGE = 25;
private static String name;
private static int damage;
public static int numMoves;
public Move(String theName, int theDamage)
{
name = theName;
if(theDamage <= MAX_DAMAGE)
{
damage = theDamage;
}
numMoves++;
}
public static String getName()
{
return name;
}
public static int getDamage()
{
return damage;
}
public static int getNumOfMoves()
{
return numMoves;
}
public String toString()
{
return name + " (" + damage + " damage)";
}
// Add an equals method so we can compare Moves against each other
public static boolean equals(Move other)
{
if(name.equals(other.getName()))
{
return true;
}
else
{
return false;
}
}
}
Here is the code for PokemonTester.java:
public class PokemonTester extends ConsoleProgram
{
public void run()
{
Pokemon p1 = new Pokemon("Charrizard", 100);
Move m1 = new Move("Flamethrower", 90);
System.out.println(p1);
System.out.println(m1);
}
}
This seems like it might be homework so I won't give you a full implementation.
If you are simply filling out the methods required for the Pokemon and Move class, I would start by reconsidering the way you are storing moves.
The getNumOfMoves provides a hint that your Pokemon class should store more than one move, a common way to do this is with arrays or lists.
If you have stored your moves in a list, the forgetMove function may look like this:
public void forgetMove(Move other){
moves.remove(other);
}
I have created a simple Queue of type which is also contains a print() function to it.
public class ArrayQueue implements Queue {
private T[] theArray;
private int currentSize;
private int front;
private int back;
private static final int DEFAULT_CAPACITY = 10;
public ArrayQueue() {
theArray = (T[]) new Object[DEFAULT_CAPACITY];
currentSize = 0;
front = 0;
back = -1;
}
public boolean isEmpty() {
return currentSize == 0;
}
public T dequeue() throws EmptyQueueException {
if (isEmpty())
throw new EmptyQueueException("ArrayQueue dequeue error");
T returnValue = theArray[front];
front = increment(front);
currentSize--;
return returnValue;
}
public void enqueue(T x) {
if (currentSize == theArray.length)
doubleQueue();
back = increment(back);
theArray[back] = x;
currentSize++;
}
private int increment(int x) {
if (++x == theArray.length)
x = 0;
return x;
}
public void print() {
if (isEmpty()) {
System.out.printf("Empty queue\n");
return;
}
System.out.printf("The queue is: ");
for (int i = front; i != back; i = increment(i)) {
System.out.print(theArray[i] + " ");
}
System.out.print(theArray[back] + "\n");
}
I have also created a Song object with 3 variables
public class Song {
private int id;
private String name;
private int likes;
public Song() {
this(1,"Test",10);
}
public Song(int id,String name, int likes) {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getLikes() {
return likes;
}
public void setLikes(int likes) {
this.likes = likes;
}
Is there a way modify this function in order to print a specific object's information or do i need to write a different print method during my implementation?
For example i would like my Print method to show all the objects variables , if i call just like this is will only get the object pointer
ArrayQueue<Song> arrayQueue = new ArrayQueue<Song>();
Queue<Song> queue = arrayQueue; //arrayQueue instance is also a Queue
Song s = new Song();
arrayQueue.enqueue(s);
arrayQueue.print();
Result is
The queue is: Song#15db9742
My modification would print :
The queue is : 1 Test 10
You need to override the toString() method of Song.
For example, add this to Song:
#Override
public String toString() {
return id + " " + name + " " + likes;
}
I am trying to search in a list but I sort as array so that I convert my linked list to array list but when I compile it without this part below. Command prompt gives "Person is not abstract and does not override abstract method compareTo(Person) in Comparable".
How can I fix this?
public int compareTo(Person other){
if (!this.name.equalsIgnoreCase(other.name))
return this.name.compareTo(other.name);
return this.name + " "+other.name;
}
Search list and sort methods:
public void searchList(String search)
{
if(phoneList.size() == 0){
System.out.println("There is no record phone book.");
}
Node<Person> tempNode = phoneList.head;
SLinkedList<Person> tempList = new SLinkedList();
for(int i=1; i<=phoneList.size; i++)
{
if (tempNode.getElement().getName().contains(search) || tempNode.getElement().getSurname().contains(search) || tempNode.getElement().getAddress().contains(search) || tempNode.getElement().getCell().contains(search) || tempNode.getElement().getHome().contains(search) || tempNode.getElement().getWork().contains(search))
{
tempList.addLast(tempNode.getElement());
personArray = new Person[tempList.size()];
Iterator<Person> it = tempList.iterator();
while(it.hasNext()){
int x = 0;
personArray[x] = it.next();
x++;
}
bubbleSort(personArray );
for(int x = 0; x < tempList.size(); x++)
System.out.println((x+1) + ""+ personArray[x]);
}
tempNode = tempNode.getNext();
}
}
public <AnyType extends Comparable<? super AnyType>> void bubbleSort(AnyType[] a) {
int outer, inner;
for (outer = a.length - 1; outer > 0; outer--) { // counting down
for (inner = 0; inner < outer; inner++) { // bubbling up
if (a[inner].compareTo(a[inner + 1]) > 0) { // if out of order...
//then swap
swapReferences(a,inner,inner+1);
}
}
}
}
public <AnyType> void swapReferences( AnyType [ ] a, int index1, int index2 )
{
AnyType tmp = a[ index1 ];
a[ index1 ] = a[ index2 ];
a[ index2 ] = tmp;
}
Person Class:
public class Person implements Comparable<Person>
{
private String name;
private String surname;
public String address;
public String cell;
public String home;
public String work;
public Person(String name, String surname, String address, String cell, String home, String work)
{
this.name = name;
this.surname = surname;
this.address = address;
this.cell = cell;
this.home = home;
this.work = work;
}
// Accessor methods:
public String getName(){
return name;
}
public String getSurname(){
return surname;
}
public String getAddress(){
return address;
}
public String getCell(){
return cell;
}
public String getHome(){
return home;
}
public String getWork(){
return work;
}
// Modifier methods:
public void setName(String name){
this.name = name;
}
public void setSurname(String surname){
this.surname = surname;
}
public void setAddress (String address){
this.address = address;
}
public void setCell (String cell){
this.cell = cell;
}
public void setHome (String home){
this.home = home;
}
public void setWork (String work){
this.work = work;
}
public String toString(){
return name + " " + surname + " " + address + " " + cell + " " + home + " " + work;
}
public int compareTo(Person other){
if (!this.name.equalsIgnoreCase(other.name))
return this.name.compareTo(other.name);
return this.name + " "+other.name;
}
}
Your existing compareTo method has a problem, but removing it violates the implements Comparable contract, since you must provide a compareTo method.
public int compareTo(Person other) {
if (!this.name.equalsIgnoreCase(other.name))
return this.name.compareTo(other.name);
// next line returns a String, but the method needs to return an int
return this.name + " " + other.name;
}
You can instead rely more directly on the standard String compareTo:
public int compareTo(Person other) {
if ( this.name.equalsIgnoreCase( other.name ) ) { return 0 };
return this.name.compareTo( other.name );
}
If you didn't have the ignore case constraint you've coded for, this would simply be
public int compareTo(Person other) {
return this.name.compareTo( other.name );
}
As an aside, there is no reason to make address, cell, home, and work public — and that's generally bad practice.
In order to implement an interface you need to implement all the methods in that interface. You either remove implements Comparable part or add public int compareTo method to your class.
The rule of compareTo method is that :
- if this Person is greater than other , return 1
- if this Person is smaller than other , return -1
- if they are equal, return 0
I have to order Appointments by date and time. I have an ArrayList of Appointments and have tried to create a comparator to compare their dates and times. I am trying to use the Collections.sort method, passing it the ArrayList of Appointments and the AppointmentComparator I have created. When compiling I get a "No suitable method for sort." Here's a link to the full error message generated by the compiler : http://prntscr.com/7y4qb
Comparator:
public class AppointmentComparator implements Comparator<Appointment>
{
public int compare(Appointment a, Appointment b)
{
if (a.getDay() < b.getDay())
return -1;
if (a.getDay() == b.getDay())
{
if (a.getStart() < b.getStart())
return -1;
if (a.getStart() > b.getStart())
return 1;
return 0;
}
return 1;
}
Line with syntax error:
Collections.sort(book, new AppointmentComparator());
variable book is an ArrayList of Appointments. ArrayList<Appointment>
AppointmentBook class:
import java.util.ArrayList;
import java.util.Collections;
public class AppointmentBook
{
private ArrayList<Appointment> book;
public AppointmentBook()
{
book = new ArrayList<Appointment>();
}
public void addAppointment(Appointment appt)
{
book.add(appt);
Collections.sort(book, new AppointmentComparator());
}
public String printAppointments(int day)
{
String list = "";
for (int i = 0; i < book.size(); i++)
{
if (book.get(i).getDay() == day)
{
list = list + "Appointment description: " + book.get(i).getDescription() + "\n" + "Date of Appointment: " +
book.get(i).getDay() + "\n" + "Time: " + book.get(i).getStart() + " - " + book.get(i).getEnd() + "\n" + "\n";
}
}
return list;
}
Appointment class:
public class Appointment
{
private String desc;
private int day; //in format mmddyyyy
private int start; //in format hhmm
private int end; //in format hhmm
public Appointment(String description, int aptDay, int startTime, int endTime)
{
desc = description;
day = aptDay;
start = startTime;
end = endTime;
}
public String getDescription()
{
return desc;
}
public int getDay()
{
return day;
}
public int getStart()
{
return start;
}
public int getEnd()
{
return end;
}
}
From the error message it looks like you forgot to declare your comparator as implementing the interface:
public class AppointmentComparator implements Comparator<Appointment> {}
It needs to have the implements part, not just contain the method.
You need to cast your new AppointmentComparator
Collections.sort(book, new (Comparator)AppointmentComparator());
Also we can use inner class for some cases:
public int indexOfLargest(ArrayList<QuakeEntry> Data) {
Comparator<QuakeEntry> cmtr = new Comparator<QuakeEntry>() {
#Override
public int compare(QuakeEntry t, QuakeEntry t1) {
if (t.getMagnitude() < t1.getMagnitude())
return -1;
if (t.getMagnitude() == t1.getMagnitude())
return 1;
if (t1.getMagnitude() > t1.getMagnitude())
return 0;
return 1;
}
};
QuakeEntry max = Collections.max(Data, cmtr);
int maxIndex = Data.indexOf(max);
//----------------------------------------------------------------------
System.out.println("//---------------------------------------------------");
System.out.println("ArrayList sorted by Magnitude using inner class with Comparator");
System.out.println("//---------------------------------------------------");
Collections.sort(Data, cmtr);
for (QuakeEntry qe : Data) {
System.out.println(qe);
}
return maxIndex;
}
code for all classes:
https://github.com/Evegen55/Java_DukeEdu_Coursera_2/blob/master/Earthquakes_Programming%20and%20Interfaces/src/earthquakes_programming_and_interfaces/QuakeEntry.java
Seems you have not implemented The comparator interface for your AppointmentComparator