I am wondering if I am writing this equals method correctly. My program keeps printing out "equal" even though the two objects Item and otherObject are not equal. I have three equals methods, and none seem to work right when run one at a time. The three equals methods are located right after each other for reference. My main is at the end.
import static java.lang.System.*;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Scanner;
import java.math.*;
public class Item {
DecimalFormat df = new DecimalFormat("#.00");
//the properties of an Item
static double cash=59.00;
static double sum=0.00;
private int priority;
private String name;
private double price;
static boolean value= false;
//default constructer
public Item() {
priority = -1; //fill with default values
price = 0.00;
name = "No name yet";
}
public Item(int priority, String name, double price) {//constructor with all 3 arguments
this.priority = priority;
this.name = name;
this.price = price;
}
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
//priority must be between 1 and 7
if (priority > 0 && priority <= 7) {
this.priority = priority;
} else {
System.err.println("Error, enter 1 through 7");
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
//price between 0 and 100 inclusive
if (price >= 0.00) {
if (price <= 100.00) {
this.price = price;
cash = cash-=price;
sum=sum+=price;
} else {
System.err.println("Error: price to high");
}
} else {
System.err.println("Error: price to low");
}
}
public boolean equals(Item otherObject) {
return this.name.equals(otherObject.name);
}
/*public boolean equals(Item otherObject) {
if(this.getPriority()==(otherObject.getPriority()));
return true;
} */
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + priority;
return result;
}
/*#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Item))
return false;
Item other = (Item) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (priority != other.priority)
return false;
return true;
}*/
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Item [Price= ").append(getPrice()).append(", ");
if (getName() != null) {
builder.append("Name= ").append(getName()).append(", ");
}
builder.append("Priority= ").append(getPriority()).append("]");
return builder.toString();
}
public static void main (String[] args) {
Item[] list = new Item[2];
Scanner keyboard = new Scanner(System.in);
for (int i = 1; i <= list.length; i++) {
if(cash==59)
{
System.out.println("You have 59 dollars");
}
Item otherObject=new Item();
Item anItem = new Item(); // new item object created 7 times
System.out.println("Enter an item you want to add to your list " + i);
anItem.setName(keyboard.next());
System.out.println("Enter a price " + i);
anItem.setPrice(keyboard.nextDouble());
System.out.println("Enter the priority of the item " + i);
anItem.setPriority(keyboard.nextInt());
list[i-1] = anItem;
System.out.println("Cash left "+cash);
System.out.println("Sum of Items "+sum);
System.out.println(Arrays.toString(list));
if (anItem.equals(otherObject)); //--------------- This is printing out each time. Is it comparing default constructors?
{System.out.println("\nequal");}
}
if(sum>59)
{System.err.println("Error, you ran out of money\t\t");
}
// int a;
//int b;
//a=list[0].getPriority();
// b=list[1].getPriority();
//System.out.println(a +" here");
// System.out.println(b +" here");
//final int[] arraySort = { a, b,};
Item temp;
for (int i = 0; i < list.length; i++) {
//min = i;
for (int j = 1; j < (list.length - i); j++) {
if (list[j-1].getPriority() > list[j].getPriority()) {
temp = list[j - 1];
list[j - 1] = list[j];
list[j] = temp;
}
} //min = j;
System.out.println(list[i]);
}
} //main
}// class Item
if("foo".equals("bar"));
{System.out.println("\nequal");}
this prints equal too!
You end the if statement too early, so the next statement is always executed!
You need to remove the ; after the the if
if (anItem.equals(otherObject))
{System.out.println("\nequal");}
If you are looking to override Object#equals(Object), your method signature needs to be
public boolean equals(Object [some identifer])
otherwise you are overloading the method.
Simple trick is to annotate methods that are meant to be overriden with #Override. Any decent IDE will tell you if that method isn't overriding anything.
Otherwise, it doesn't seem like you've set the name of otherObject to that of anItem.name and therefore
this.name.equals(otherObject.name)
will return false.
I think your equals method should be:
public boolean equals(Item otherObject) {
return this.name.equals(otherObject.getName());
}
Simple because name field is private.
Related
I am writing a program that creates an object (Line) that contains a name and two nodes (x,y,z coordinates) which are then stored in a separate object (class LineModel). Within the class LineModel a method, getNode(), is created that should return the node. The nodes are constructed in a separate object (class Node).
My problem lies within the method getNode(), as I can't seem to return the node that I'm looking for.
public class LineModel {
// Object attributes
private String name;
private Line[] lines;
private int numLines;
// Constructor
public LineModel(String name, int maxLines) {
this.name = name;
lines = new Line[maxLines];
numLines = 0;
}
// Add lines
public void addLine(Line line) {
if (contains(line)) {
System.out.println("Line " + line.getName() + " already in model");
return;
}
if (numLines < lines.length) {
lines[numLines] = line;
numLines++;
} else {
System.out.println("Increase lines array size.");
System.exit(1);
}
}
public Node getNode(String name) {
for (int i = 0; i < numLines; i++) {
if (lines[i].getN1().getName().equals(name) || lines[i].getN2().getName().equals(name)) {
return lines[i].getN1();
} else {
return null;
}
}
}
Below are the classes Line and Node
public class Line {
// Object attributes
private String name;
private Node n1, n2;
// Constructor(s)
public Line(String name, Node n1, Node n2){
this.name = name;
this.n1 = n1;
this.n2 = n2;
}
public String getName(){ return name; }
// Object methods
public double length(){
double[] n1C = n1.getCoordinates();
double[] n2C = n2.getCoordinates();
if(n1C.length == n2C.length){
double pythagoras = 0;
for (int i = 0; i < n1C.length; i++) {
double dv = n2C[i] - n1C[i];
pythagoras += dv*dv;
}
return Math.sqrt(pythagoras);
}
return Double.NaN;
}
#Override
public String toString(){
return "Line "+name+" "+n1.getName()+"-->"+n2.getName()+" Length = "+length();
}
public Node getN1() { return n1;}
public Node getN2() { return n2;}
public class Node {
// Object attributes
private String name;
private double[] coordinates;
// Constructor(s)
public Node(String name, double x) {
this.name = name;
coordinates = new double[1];
coordinates[0] = x;
}
public Node(String name, double x, double y) {
this.name = name;
coordinates = new double[2];
coordinates[0] = x; coordinates[1] = y;
}
public Node(String name, double x, double y, double z) {
this.name = name;
coordinates = new double[3];
coordinates[0] = x; coordinates[1] = y; coordinates[2] = z;
}
// Object methods
public String getName(){
return name;
}
public double[] getCoordinates(){
return coordinates;
}
public double getX() {
if (coordinates.length > 0){
return coordinates[0];
} else {
return Double.NaN;
}
}
public double getY() {
if (coordinates.length > 1){
return coordinates[1];
} else {
return Double.NaN;
}
}
public double getZ() {
if (coordinates.length > 2){
return coordinates[2];
} else {
return Double.NaN;
}
}
public String toString() {
return "Node "+name+" "+Arrays.toString(coordinates);
}
}
The current error is that it has to return type Node, but I can't seem to figure out why it says that. Sorry for the large amount of code. I'm quite new to coding so I don't know if everthing is relevant.
The for-loop inside "getNode" always gets terminated after one iteration.
If the first node has the matching name it returns the node, otherwise it returns null which always terminates the for-loop after the first iteration without checking any further nodes inside the array.
IMHO you should change the code to something like this:
public Node getNode(String name) {
for (int i = 0; i <= numLines; i++) {
if (lines[i].getN1().getName().equals(name) || lines[i].getN2().getName().equals(name)) {
return lines[i].getN1();
}
}
return null;
}
In this case the for-loop iterates over each element of the array until it finds the correct node or until there are no more elements left. If the requested node gets found it returns the node, otherwise it returns null.
You should also do
for (int i = 0; i <= numLines; i++)
instead of
for (int i = 0; i < numLines; i++)
because, in your implementation the last element of the array will always be ignored as if the array has one element "numLines" will be "1" and "1 < 1 == false". This means, that the loop even doesn't do any iteration and if "numLines" is "2" it will only perform one iteration as "2 < 2 == false".
This is my main search algorithm for multiple items using binary and separate function. I need someone to refactor my approach.
private int Multisearch(TYPE key){
int ind = binarySearchComparator(key);
// If element is not present
if (ind == -1)
return -1;
// Count elements on left side.
int count = 1;
int left = ind - 1;
int i = 1;
while (left >= 0 && (comparator.compare(list[left], key)) == 0)
{
lol[i] = list[left]; // store left found elements in array here
i++;
count++;
left--;
}
// Count elements
// on right side.
int right = ind + 1;
try{
while (right < list.length && (comparator.compare(list[right], key)) == 0)
{
lol[i] = list[right]; // store right found elements in array here
i++;
count++;
right++;
}
}catch(Exception e){
}
return count;
}
private int binarySearchComparator(TYPE key) {
int low = 0;
int high = count - 1;
while (low <= high) {
int mid = (low + high) / 2 ;
TYPE midVal = list[mid];
int cmp = comparator.compare(midVal, key);
if (cmp < 0)
low = mid + 1;
else if (cmp > 0)
high = mid - 1;
else
return mid; // key found
}
return -1; // key not found.
}
Above code is my approach and my backup. I want you guys to use a binary search to look for multiple items and store them somewhere for it to display to the user as the user is filtering items by gender and the binarysearch function will search items that is " Male " and display them all for the user.
I need it to search multiple items and display/store them somewhere else to display it to the user.
This is like a filtering function by the way if any kind soul is able to help me out. I will greatly appreciate it!
Well if you can actually count the occurrence of same item/object as well as store them to display later. I will even greatly appreciate that approach! Please show me how! Thanks!
Sorted List Interface
public interface SortedListInterface <TYPE extends Comparable<TYPE>> {
public boolean add(TYPE element);
public TYPE get(int index);
public int search(TYPE element);
public TYPE remove(int index);
public void clear();
public int getLength();
public boolean isEmpty();
public boolean isFull();
}
SearchComparator Class
public class MobileSearch implements Comparator<Student>{
private String type;
public void setType(String type) {
this.type = type;
}
public String getType() {
return type;
}
#Override
public int compare(Student student1, Student student2) {
int result = 0;
if(this.type.equals("mobile")){
result = student1.getMobileNo().compareTo(student2.getMobileNo());
System.out.print(result+"mobile");
}
else if(this.type.equals("name")){
result = student1.getName().getFullName().compareTo(student2.getName().getFullName());
System.out.println(result+"name");
}
else if(this.type.equals("group")){
result = student1.getGroup().compareTo(student2.getGroup());
System.out.print(result+"group");
}
return result;
}
}
SortedArrayList Implementation
public class SortedArrayList<TYPE extends Comparable<TYPE>> implements SortedListInterface<TYPE>{
//Data Types
private TYPE[] list;
private int length;
private static final int SIZE = 10;
private Comparator<? super TYPE> comparator;
private int count;
#SuppressWarnings("unchecked")
public SortedArrayList(Comparator<? super TYPE> c) {
comparator = c;
list = (TYPE[]) new Comparable[SIZE]; // No way to verify that 'list' only contains instances of 'T'.
/* NOTE: Following is not allowed.
list = new T[SIZE]; // Cannot create a generic array of T
*/
}
// Constructors
public SortedArrayList() {
this(SIZE);
}
public SortedArrayList(int size) {
length = 0;
list = (TYPE[]) new Comparable[SIZE]; // an array of instances of a class implementing Comparable interface and able to use compareto method but its overidden instead
}
// Setter & Getters
#Override
public int getLength() {
return length;
}
#Override
public boolean isEmpty() {
return length == 0;
}
#Override
public boolean isFull() {
return false;
}
#Override
public void clear() {
length = 0;
}
// Array Expansion
private boolean isArrayFull() {
return length == list.length;
}
private void expandArray() {
TYPE[] oldList = list;
int oldSize = oldList.length;
list = (TYPE[]) new Object[2 * oldSize];
for (int i = 0; i < oldSize; i++) // copy old array elements into new array elements
list[i] = oldList[i];
}
// ADT METHODs
// Add New Elements Function
#Override
// public boolean add(TYPE element) {
// int i = 0;
//
// while (i < length && element.compareTo(list[i]) > 0) // return 0 with equal , return more than 1 if element larger than list[i] , return -1 if less
// {
// i++;
// }
//
// makeRoom(i + 1);
// list[i] = element;
// length++;
// return true;
// }
public boolean add(TYPE element) {
boolean result = false;
if (count == 0) {
list[0] = element;
count = 1;
result = true;
}
else {
if (!isFull()) {
int i = 0;
while (list[i] != null) {
if (element.compareTo(list[i]) < 0) {
break;
}
i++;
}
if (list[i] != null) {
for (int j = count - 1; j >= i; j--) {
list[j + 1] = list[j];
}
}
list[i] = element;
count++;
result = true;
}
}
return result;
}
private void makeRoom(int index) { // accepts given index
int newIndex = index - 1;
int lastIndex = length - 1;
for (int i = lastIndex; i >= newIndex; i--)
list[i + 1] = list[i];
}
//Remove Elements Function
#Override
public TYPE remove(int index) { // accepts given index
TYPE result = null;
if ( index >= 1 && index <= length ) {
result = list[index - 1];
if (index < length)
removeGap(index);
length--;
}
return result;
}
private void removeGap(int index) { // accepts given index and remove the gap where the element its removed
int removedIndex = index - 1;
int lastIndex = length - 1;
for (int i = removedIndex; i < lastIndex; i++)
list[i] = list[i + 1]; // shifts elements back to remove the gap
}
// Get Element
#Override
public TYPE get(int index) { // accepts given index and return the object
TYPE object = null;
if ( index >= 1 && index <= length)
object = list[index - 1];
return object;
}
// Search Algorithms
#Override
// public boolean search(TYPE element) {
// boolean found = false;
//
// int lo = 0;
// int hi = count - 1;
//
// while (lo <= hi) {
// int mid = (lo + hi) / 2;
// if (list[mid].compareTo(element) < 0) {
// lo = mid + 1;
// }
// else if (list[mid].compareTo(element) > 0) {
// hi = mid - 1;
// }
// else if (list[mid].compareTo(element) == 0) {
// found = true;
// break;
// }
// return found
// }
public int search(TYPE element) {
return exponentialSearch(element);
}
private boolean binarySearchComparable(TYPE element) {
boolean found = false;
int lo = 0;
int hi = count - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (list[mid].compareTo(element) < 0) {
lo = mid + 1;
}
else if (list[mid].compareTo(element) > 0) {
hi = mid - 1;
}
else if (list[mid].compareTo(element) == 0) {
found = true;
break;
}
}
System.out.print("Single");
return found;
}
private int exponentialSearch(TYPE key){
int ind = binarySearchComparator(key);
// If element is not present
if (ind == -1)
return -1;
// Count elements on left side.
int count = 1;
int left = ind - 1;
int i = 1;
while (left >= 0 && (comparator.compare(list[left], key)) == 0)
{
// lol[i] = list[left];
System.out.println(left+"lefttest");
i++;
count++;
left--;
}
// Count elements
// on right side.
int right = ind + 1;
try{
while (right < list.length && (comparator.compare(list[right], key)) == 0)
{
System.out.println(right+"righttest");
// lol[i] = arr[right];
i++;
count++;
right++;
}
}catch(Exception e){
}
return count;
}
private int binarySearchComparator(TYPE key) {
int low = 0;
int high = count - 1;
while (low <= high) {
int mid = (low + high) / 2 ;
TYPE midVal = list[mid];
int cmp = comparator.compare(midVal, key);
if (cmp < 0)
low = mid + 1;
else if (cmp > 0)
high = mid - 1;
else
return mid; // key found
}
return -1; // key not found.
}
//To String Method
#Override
public String toString() {
String result = "";
for (int i = 0; i < count; i++)
result += list[i] + "\n";
return result;
}
}
Name Class
public class Name {
// Data Types
private String firstName;
private String lastName;
// Constructors
public Name() {
}
public Name(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
// setter
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
// getter
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getFullName(){
return firstName + " " + lastName;
}
#Override
public String toString() {
return "Name{" + "firstName=" + firstName + ", lastName=" + lastName + '}';
}
}
Student Class
public class Student implements Comparable<Student>{
// Data Types
private String studID;
private Name name;
private String gender;
private String icNo;
private String mobileNo;
private Course course;
private String group;
private String dOB;
// Constructors
public Student() {
}
public Student(String studID, Name name, String gender, String icNo, String mobileNo, Course course, String group, String dOB) {
this.studID = studID;
this.name = name;
this.gender = gender;
this.icNo = icNo;
this.mobileNo = mobileNo;
this.course = course;
this.group = group;
this.dOB = dOB;
}
public Student(Name name) {
this.name = name;
}
// setter
public void setStudID(String studID) {
this.studID = studID;
}
public void setName(Name name) {
this.name = name;
}
public void setGender(String gender) {
this.gender = gender;
}
public void setIcNo(String icNo) {
this.icNo = icNo;
}
public void setMobileNo(String mobileNo) {
this.mobileNo = mobileNo;
}
public void setCourse(Course course) {
this.course = course;
}
public void setGroup(String group) {
this.group = group;
}
public void setdOB(String dOB) {
this.dOB = dOB;
}
// getter
public String getStudID() {
return studID;
}
public Name getName() {
return name;
}
public String getGender() {
return gender;
}
public String getIcNo() {
return icNo;
}
public String getMobileNo() {
return mobileNo;
}
public Course getCourse() {
return course;
}
public String getGroup() {
return group;
}
public String getdOB() {
return dOB;
}
#Override
public String toString() {
return "Student{" + "name=" + name + ", gender=" + gender + ", icNo=" + icNo + ", mobileNo=" + mobileNo + ", course=" + course + ", group=" + group + ", dOB=" + dOB + '}';
}
#Override
public int compareTo(Student object) { // Sort according to name if name same then sort according to gender and so on.
int c = this.name.getFullName().compareTo(object.getName().getFullName());
if(c == 0)
c = this.gender.compareTo(object.getGender());
if(c == 0)
c = this.icNo.compareTo(object.getIcNo());
if(c == 0)
c = this.mobileNo.compareTo(object.getMobileNo());
if(c == 0)
c = this.group.compareTo(object.getGroup());
if(c == 0)
c = this.dOB.compareTo(object.getdOB());
return c;
}
public static Student[] sort(Student[] object,String category){
Student[] array;
if(category.equals("ID")){
for (int i=1; i < object.length; i++) {
for(int j = 0 ; j < object.length - i ; j++)
if( (object[j].getGender().compareTo(object[j+1].getGender())) > 0 ){
Student lol = object[j];
object[j] = object[j+1];
object[j+1] = lol;
}
}
}
array = object;
return array;
}
}
Course Class
public class Course {
// Data Types
private String courseCode;
private String courseName;
private double courseFee;
// Constructors
public Course() {
}
public Course(String courseCode, String courseName, double courseFee) {
this.courseCode = courseCode;
this.courseName = courseName;
this.courseFee = courseFee;
}
// setter
public void setCourseCode(String courseCode) {
this.courseCode = courseCode;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public void setCourseFee(double courseFee) {
this.courseFee = courseFee;
}
// getter
public String getCourseCode() {
return courseCode;
}
public String getCourseName() {
return courseName;
}
public double getCourseFee() {
return courseFee;
}
#Override
public String toString() {
return "CourseCode = " + courseCode + "Course Name = " + courseName + "Course Fee = " + courseFee;
}
}
If your data are already sorted, you won't get faster than binary search O(log n). If there are more than one match, find one match and than iterate forward (until no more matches found) and backward (until no more matches found) from it to get all matches.(or if you only need the index of first and last match, you can replace the iterating part by again binary search for the first / last matching one. That would reduce complexity to O(n) no matter how many matches there are)
This takes O(log n) + O(#matches)
If that is not fast enough for you, try profiling your implementation to find the bottleneck where further optimization attempts make most sense.
I'm currently designing a program to simulate an airport. I ran into a problem and I've already tried my best to figure out the problem and posting to this site was my final resort.
It keeps giving me a "Exception in thread "main" java.lang.NullPointerException at AirportApp.main(AirportApp.java:119)" which is under the //Landings section with the code
System.out.println(plane1.getCapacity());
The reason I did the print is to make sure plane1.getCapacity isn't a null. This is because when I tried the code below it
if(plane1.getCapacity() < 300);
it gave me the NullPointerException error. I did the print and it didn't return a null.
What I'm trying to do here is whenever a plane lands, it will be assigned to an empty gate. If the plane has a capacity of 300 or more, it will be assigned to the 4th or 5th gate only. The other planes can be assigned to any gate.
What I noticed was that the error happens only when the capacity is over 300.
I've already looked at my code over and over again making sure all variables were initialized and I still could not find anything wrong. Any help or hints will be greatly appreciated. Apologies for the messy code.
Main class.
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class AirportApp {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
Random rn = new Random();
String [] flightNames = {"SQ", "MI", "TZ", "TR", "EK", "MO", "FC"};
int [] flightNum = {8421, 5361, 6342, 6135, 8424, 7424, 5435};
Queue landingRunway = new Queue(10);
Queue takeoffRunway = new Queue(10);
Queue planesQueue = new Queue(100);
Queue gatesQueue = new Queue(100);
ArrayList<Gate> allGates = new ArrayList();
for(int i = 1 ; i < 6 ; i++)
{
allGates.add(new Gate(i, 0, 0, true));
}
int minutes = 0;
int planesMissedTime = 0;
Boolean highWinds = null;
int tookOffPlanes = 0;
int smallCapPlanes = 0;
int largeCapPlanes = 0;
int landedPlanes = 0;
System.out.println("Please key in the number of minutes you want "
+ "the program to run: ");
int desiredMinutes = sc.nextInt();
while(minutes < desiredMinutes)
{
//Randomise wind warnings
int windRandom = rn.nextInt(2) + 1;
if(windRandom == 1)
{
highWinds = true;
}
if(windRandom == 2)
{
highWinds = false;
}
//Empty the gates
for(Gate c : allGates)
{
if(c.getAvailability() == false)
{
c.addMinInQueue(1);
if(c.getMinInQueue() == 15)
{
c.isAvailable();
}
}
}
//Every 2 minutes
if(minutes % 2 == 0)
{
//Randomise flight names and number
int index = rn.nextInt(flightNames.length);
int index1 = rn.nextInt(flightNum.length);
String name = flightNames[index];
int num = flightNum[index1];
//Randomise plane assignment
int planeDirection = rn.nextInt(2) + 1;
int planeCap = rn.nextInt(401) + 100;
//Arrival Planes
if(planeDirection == 1)
{
planesQueue.enqueue(new Plane(num, name, planeCap, 5 , 0 ));
System.out.println("A plane has been generated.");
}
//Departure Planes
if(planeDirection == 2)
{
planesQueue.enqueue(new Plane(num, name, planeCap, 0 , 5 ));
System.out.println("A plane has been generated.");
}
//Take-Offs
if(!takeoffRunway.isEmpty())
{
System.out.println("A plane has departed.");
Plane departPlane = (Plane) takeoffRunway.dequeue();
if (departPlane.getCapacity() < 300)
{
smallCapPlanes++;
}
tookOffPlanes++;
}
}
//Landings
if(minutes % 3 == 0 && !landingRunway.isEmpty())
{
System.out.println("A plane has landed.");
gatesQueue.enqueue(landingRunway.dequeue());
landedPlanes++;
loop1:
for(Gate e : allGates)
{
if(e.getAvailability() == true)
{
Plane plane1 = (Plane) gatesQueue.dequeue();
System.out.println(plane1.getCapacity());
if(plane1.getCapacity() < 300)
{
e.addNumOfPlanes(1);
e.setAvailability(false);
break loop1;
}
if(plane1.getCapacity() > 300)
{
largeCapPlanes++;
if(e.getGateId() == 4 || e.getGateId() == 5)
{
e.addNumOfPlanes(1);
e.setAvailability(false);
break loop1;
}
}
}
}
}
//Plane assigned to takeoff or landing queue
if(minutes % 5 == 0)
{
Plane item = (Plane) planesQueue.peek();
if(item.getArrivalTime() == 5 && landingRunway.isEmpty()
&& highWinds == false)
{
landingRunway.enqueue(planesQueue.dequeue());
System.out.println("A plane has been assigned to "
+ "the landing queue.");
}
else if(item.getDepartureTime() == 5 &&
takeoffRunway.isEmpty() && highWinds == false)
{
takeoffRunway.enqueue(planesQueue.dequeue());
System.out.println("A plane has been assigned to "
+ "the takeoff queue.");
}
else
{
planesMissedTime++;
}
}
minutes++;
}
Class 1
public class Plane
{
private int flightNo;
private String flightName;
private int capacity;
private int timeOfArrival;
private int timeOfDeparture;
private int delayTime;
public Plane(int flightNo, String flightName, int capacity,
int timeOfArrival, int timeOfDeparture)
{
this.flightNo = flightNo;
this.flightName = flightName;
this.capacity = capacity;
this.timeOfArrival = timeOfArrival;
this.timeOfDeparture = timeOfDeparture;
}
public void setFlightNum(int flightNo)
{
this.flightNo = flightNo;
}
public int getFlightNum()
{
return this.flightNo;
}
public void setFlightName(String flightName)
{
this.flightName = flightName;
}
public String getflightName()
{
return this.flightName;
}
public void addCapacity(int capacity)
{
this.capacity = capacity;
}
public int getCapacity()
{
return this.capacity;
}
public void setArrivalTime(int newArrivalTime)
{
this.timeOfArrival = newArrivalTime;
}
public int getArrivalTime()
{
return this.timeOfArrival;
}
public void setDepartureTime(int newDepartureTime)
{
this.timeOfDeparture = newDepartureTime;
}
public int getDepartureTime()
{
return this.timeOfDeparture;
}
}
Class 2
public class Gate
{
private int gateID;
private int numOfPlanes;
private int minInQueue;
private boolean availability;
public Gate(int id, int numPlanes, int minQueue, boolean available)
{
this.gateID = id;
this.numOfPlanes = numPlanes;
this.minInQueue = minQueue;
this.availability = available;
}
public int getGateId()
{
return this.gateID;
}
public void setGateId(int newID)
{
this.gateID = newID;
}
public int getNumOfPlanes()
{
return this.numOfPlanes;
}
public void addNumOfPlanes(int addNum)
{
this.numOfPlanes += addNum;
}
public int getMinInQueue()
{
return this.minInQueue;
}
public void setMinInQueue(int setMin)
{
this.minInQueue = 0;
}
public void addMinInQueue(int addMin)
{
this.minInQueue += addMin;
}
public boolean getAvailability()
{
return this.availability;
}
public void setAvailability(Boolean setAvailability)
{
this.availability = setAvailability;
}
public void isAvailable()
{
this.availability = true;
this.minInQueue = 0;
}
}
Queue class
class Queue
{
private int count;
private int front = 0;
private int rear = 0;
private Object [] items;
public Queue(int maxSize)
{
count = 0;
front = -1;
rear = -1;
items = new Object [maxSize];
}
public boolean enqueue (Object x)
{
if (count == items.length)
{
return false;
}
else
{
rear = (rear + 1) % items.length;
items[rear] = x;
if (count == 0)
{
front = 0;
}
count++;
return true;
}
}
public Object dequeue()
{
if (count == 0)
{
return null;
}
else
{
Object result = items[front];
front = (front + 1) % items.length;
count--;
if (count == 0)
{
front = -1;
rear = -1;
}
return result;
}
}
public int size()
{
return count;
}
public boolean isEmpty()
{
if (count == 0)
{
return true;
}
else
{
return false;
}
}
public Object peek()
{
if (count == 0)
{
return null;
}
else
{
return items[front];
}
}
}
The problem lies in the second if statement
if (plane1.getCapacity() > 300) {
largeCapPlanes++;
if (e.getGateId() == 4 || e.getGateId() == 5) {
e.addNumOfPlanes(1);
e.setAvailability(false);
break loop1;
}
}
You only break your loop if the gate is 4, or 5. So, if it is not gate 4 or 5, then you code will loop back to the next gate, grab another plane from the queue (which is empty and your plane1 is now null) and then try to get the capacity. And there you get your null pointer.
Note: Be careful nesting loops and if statements. This is where bugs enjoy living.
Happy Coding!
I ran the code and didn't get an error until I tried a large number for the time (1000). I'm assuming the error is with the Plane plane1 = (Plane) gatesQueue.dequeue(); section. I would throw some debug statements in there to see if for large n that the Queue is generated properly. if dequeue() returns null then plane1 will also be null
EDIT:
So I debugged it and confirmed that the issue is with your plane object in that loop. You enqueue your gates: gatesQueue.enqueue(landingRunway.dequeue()); then you run a loop: for(Gate e : allGates) and then you dequeue: Plane plane1 = (Plane) gatesQueue.dequeue();
If you dequeue more than what you enqueue you will return null. So you'll either have to change how you do your queue or put a check in that for-loop to check the size of your queue.
The reason you are seeing a number when you do your System.out.println() is because it is displaying that, returning to the top of the loop, and then trying to get the plane object again before you run the print again.
Greeting to everyone. I currently work on a program that sorting the emergency number of patients(the number that assigned by nurse when they enter the emergency room and this number determines the seriousness of their sickness too). However, if there are more than 1 patient who hold the same emergency numbers(eg: 2 patients hold emergency number 1), the one who came earlier should receive the treatment first. For this reason, I have 2 sortings, one is to sort the emergency number in ascending order and the other is to sort the time in ascending order too. But unfortunately the second sorting cannot work correctly.The following are the explanations for the type of emergency numbers:
Emergency number : 1 – Immediately life threatening
Emergency number : 2 – Urgent, but not immediately life threatening
Emergency number : 3 – Less urgent
So,now comes the coding part(Please note that this is a linkedlist)
Interface:
public interface ListInterface<T> {
public boolean add(T newEntry);
public boolean add(int newPosition, T newEntry);
public T remove(int givenPosition);
public void clear();
public boolean replace(int givenPosition, T newEntry);
public T getEntry(int givenPosition);
public boolean contains(T anEntry);
public int getLength();
public boolean isEmpty();
public boolean isFull();
}
LList class:
/**
* LList.java
* A class that implements the ADT list by using a chain of nodes,
* with the node implemented as an inner class.
*/
public class LList<T> implements ListInterface<T> {
private Node firstNode; // reference to first node
private int length; // number of entries in list
public LList() {
clear();
}
public final void clear() {
firstNode = null;
length = 0;
}
public boolean add(T newEntry) {
Node newNode = new Node(newEntry); // create the new node
if (isEmpty()) // if empty list
firstNode = newNode;
else { // add to end of nonempty list
Node currentNode = firstNode; // traverse linked list with p pointing to the current node
while (currentNode.next != null) { // while have not reached the last node
currentNode = currentNode.next;
}
currentNode.next = newNode; // make last node reference new node
}
length++;
return true;
}
public boolean add(int newPosition, T newEntry) { // OutOfMemoryError possible
boolean isSuccessful = true;
if ((newPosition >= 1) && (newPosition <= length+1)) {
Node newNode = new Node(newEntry);
if (isEmpty() || (newPosition == 1)) { // case 1: add to beginning of list
newNode.next = firstNode;
firstNode = newNode;
}
else { // case 2: list is not empty and newPosition > 1
Node nodeBefore = firstNode;
for (int i = 1; i < newPosition - 1; ++i) {
nodeBefore = nodeBefore.next; // advance nodeBefore to its next node
}
newNode.next = nodeBefore.next; // make new node point to current node at newPosition
nodeBefore.next = newNode; // make the node before point to the new node
}
length++;
}
else
isSuccessful = false;
return isSuccessful;
}
public T remove(int givenPosition) {
T result = null; // return value
if ((givenPosition >= 1) && (givenPosition <= length)) {
if (givenPosition == 1) { // case 1: remove first entry
result = firstNode.data; // save entry to be removed
firstNode = firstNode.next;
}
else { // case 2: givenPosition > 1
Node nodeBefore = firstNode;
for (int i = 1; i < givenPosition - 1; ++i) {
nodeBefore = nodeBefore.next; // advance nodeBefore to its next node
}
result = nodeBefore.next.data; // save entry to be removed
nodeBefore.next = nodeBefore.next.next; // make node before point to node after the
} // one to be deleted (to disconnect node from chain)
length--;
}
return result; // return removed entry, or
// null if operation fails
}
public boolean replace(int givenPosition, T newEntry) {
boolean isSuccessful = true;
if ((givenPosition >= 1) && (givenPosition <= length)) {
Node currentNode = firstNode;
for (int i = 0; i < givenPosition - 1; ++i) {
// System.out.println("Trace| currentNode.data = " + currentNode.data + "\t, i = " + i);
currentNode = currentNode.next; // advance currentNode to next node
}
currentNode.data = newEntry; // currentNode is pointing to the node at givenPosition
}
else
isSuccessful = false;
return isSuccessful;
}
public T getEntry(int givenPosition) {
T result = null;
if ((givenPosition >= 1) && (givenPosition <= length)) {
Node currentNode = firstNode;
for (int i = 0; i < givenPosition - 1; ++i) {
currentNode = currentNode.next; // advance currentNode to next node
}
result = currentNode.data; // currentNode is pointing to the node at givenPosition
}
return result;
}
public boolean contains(T anEntry) {
boolean found = false;
Node currentNode = firstNode;
while (!found && (currentNode != null)) {
if (anEntry.equals(currentNode.data))
found = true;
else
currentNode = currentNode.next;
}
return found;
}
public int getLength() {
return length;
}
public boolean isEmpty() {
boolean result;
if (length == 0)
result = true;
else
result = false;
return result;
}
public boolean isFull() {
return false;
}
public String toString() {
String outputStr = "";
Node currentNode = firstNode;
while (currentNode != null) {
outputStr += currentNode.data + "\n";
currentNode = currentNode.next;
}
return outputStr;
}
private class Node {
private T data;
private Node next;
private Node(T data) {
this.data = data;
this.next = null;
}
private Node(T data, Node next) {
this.data = data;
this.next = next;
}
} // end Node
} // end LList
Patient class:
public class Patient {
private int emergencyNo;
private int queueTime;
private String patientName;
private String patientIC;
private String patientGender;
private String patientTelNo;
private String patientAdd;
private String visitDate;
public Patient() {
}
public Patient(int emergencyNo, int queueTime, String patientName, String patientIC, String patientGender, String patientTelNo, String patientAdd, String visitDate)
{
this.emergencyNo = emergencyNo;
this.queueTime = queueTime;
this.patientName = patientName;
this.patientIC = patientIC;
this.patientGender = patientGender;
this.patientTelNo = patientTelNo;
this.patientAdd = patientAdd;
this.visitDate = visitDate;
}
//set methods
public void setQueueTime(int queueTime)
{
this.queueTime = queueTime;
}
public boolean setEmergencyNo(int emergencyNo)
{
boolean varEmergencyNo = true;
if (emergencyNo != 1 && emergencyNo != 2 && emergencyNo != 3)
{
varEmergencyNo = false;
System.out.println("Emergency number is in invalid format!");
System.out.println("Emergency number is either 1, 2 or 3 only!");
System.out.println("\n");
}
else
{
this.emergencyNo = emergencyNo;
}
return varEmergencyNo;
}
public boolean setPatientName(String patientName)
{
boolean varPatientName = true;
if (patientName.equals("") || patientName.equals(null))
{
varPatientName = false;
System.out.println("The patient name cannot be empty!\n");
}
else
{
this.patientName = patientName;
}
return varPatientName;
}
public boolean setPatientIC(String patientIC)
{
boolean varPatientIC = true;
if(!patientIC.matches("^[0-9]{12}$"))
{
varPatientIC = false;
System.out.println("IC is in invalid format!");
System.out.println("It must consist of 12 numbers only!\n");
}
else
{
this.patientIC = patientIC;
}
return varPatientIC;
}
public boolean setPatientGender(String patientGender)
{
boolean varPatientGender = true;
if(!patientGender.equals("F") && !patientGender.equals("f") && !patientGender.equals("M") && !patientGender.equals("m"))
{
varPatientGender = false;
System.out.println("Gender is in invalid format!");
System.out.println("It must be either 'M' or 'F' only!\n");
}
else
{
this.patientGender = patientGender;
}
return varPatientGender;
}
public boolean setPatientTelNo(String patientTelNo)
{
boolean varPatientTelNo = true;
if((!patientTelNo.matches("^01[02346789]\\d{7}$")) && (!patientTelNo.matches("^03\\d{8}$")))
{
varPatientTelNo = false;
System.out.println("Invalid phone number!");
System.out.println("It must be in the following format : 0167890990 / 0342346789!\n");
System.out.print("\n");
}
else
{
this.patientTelNo = patientTelNo;
}
return varPatientTelNo;
}
public boolean setPatientAdd(String patientAdd)
{
boolean varPatientAdd = true;
if (patientAdd.equals("") || patientAdd.equals(null))
{
varPatientAdd = false;
System.out.println("The patient address cannot be empty!\n");
}
else
{
this.patientAdd = patientAdd;
}
return varPatientAdd;
}
public void setVisitDate(String visitDate)
{
this.visitDate = visitDate;
}
//get methods
public int getQueueTime()
{
return this.queueTime;
}
public int getEmergencyNo()
{
return this.emergencyNo;
}
public String getPatientName()
{
return this.patientName;
}
public String getPatientIC()
{
return this.patientIC;
}
public String getPatientGender()
{
return this.patientGender;
}
public String getPatientTelNo()
{
return this.patientTelNo;
}
public String getPatientAdd()
{
return this.patientAdd;
}
public String getVisitDate()
{
return this.visitDate;
}
#Override
public String toString()
{
return (this.emergencyNo + "\t\t" + this.patientName + "\t\t" + this.patientIC +
"\t\t" + this.patientGender + "\t\t" + this.patientTelNo + "\t\t" + this.patientAdd + "\t\t" + this.visitDate);
}
public String anotherToString()
{
return (this.emergencyNo + "\t\t\t\t\t\t" + this.patientName + "\t\t\t " + this.visitDate);
}
}
EmergencyCmp(Comparator)--->use for sorting the emergency numbers of the patients
import java.util.Comparator;
public class EmergencyCmp implements Comparator<Patient>
{
#Override
public int compare(Patient p1, Patient p2)
{
if(p1.getEmergencyNo() > p2.getEmergencyNo())
{
return 1;
}
else
{
return -1;
}
}
}
QueueCmp(Comparator)--->use for sorting the arrival time of the patients
import java.util.Comparator;
public class QueueCmp implements Comparator<Patient>
{
#Override
public int compare(Patient p1, Patient p2)
{
if(p1.getQueueTime() > p2.getQueueTime())
{
return 1;
}
else
{
return -1;
}
}
}
Main function:
import java.util.Calendar;
import java.util.Scanner;
import java.util.Arrays;
import java.util.*;
public class DSA {
public DSA() {
}
public static void main(String[] args) {
//patient's attributes
int emergencyNo;
int queueTime;
String patientName;
String patientIC;
String patientGender;
String patientTelNo;
String patientAdd;
String visitDate;
//counter
int j = 0;
int x = 0;
int y = 0;
int z = 0;
int count1 = 0;
int count2 = 0;
int count3 = 0;
int countEnteredPatient = 1;
int totalCount = 0;
//calendar
int nowYr, nowMn, nowDy, nowHr, nowMt, nowSc;
//others
boolean enterNewPatient = true;
String continueInput;
boolean enterNewPatient1 = true;
String continueInput1;
boolean continueEmergencyNo;
Scanner scan = new Scanner(System.in);
ListInterface<Patient> patientList = new LList<Patient>();
ListInterface<Patient> newPatientList = new LList<Patient>();
Patient[] patientArr1 = new Patient[10000];
Patient[] patientArr2 = new Patient[10000];
Patient[] patientArr3 = new Patient[10000];
Patient tempoPatient;
do{
//do-while loop for entering new patient details after viewing patient list
System.out.println("Welcome to Hospital Ten Stars!\n");
do{
//do-while loop for entering new patient details
System.out.println("Entering details of patient " + countEnteredPatient);
System.out.println("===================================\n");
Calendar calendar = Calendar.getInstance();
nowYr = calendar.get(Calendar.YEAR);
nowMn = calendar.get(Calendar.MONTH);
nowDy = calendar.get(Calendar.DAY_OF_MONTH);
nowHr = calendar.get(Calendar.HOUR);
nowMt = calendar.get(Calendar.MINUTE);
nowSc = calendar.get(Calendar.SECOND);
queueTime = calendar.get(Calendar.MILLISECOND);
visitDate = nowDy + "/" + nowMn + "/" + nowYr + ", " + nowHr + ":" + nowMt + ":" + nowSc;
//input emergency number
do{
tempoPatient = new Patient();
continueEmergencyNo = false;
int EmergencyNoOption;
try
{
do{
System.out.print("Please select 1 – Immediately life threatening, 2 – Urgent, but not immediately life threatening or 3 – Less urgent(Eg: 1) : ");
EmergencyNoOption = scan.nextInt();
scan.nextLine();
System.out.print("\n");
}while(tempoPatient.setEmergencyNo(EmergencyNoOption) == false);
}
catch(InputMismatchException ex)
{
System.out.print("\n");
System.out.println("Invalid input detected.");
scan.nextLine();
System.out.print("\n");
continueEmergencyNo = true;
}
}while(continueEmergencyNo);
//input patient name
do{
System.out.print("Patient name(Eg: Christine Redfield) : ");
patientName = scan.nextLine();
System.out.print("\n");
}while(tempoPatient.setPatientName(patientName) == false);
//input patient ic no
do{
System.out.print("Patient IC number(Eg: 931231124567) : ");
patientIC = scan.nextLine();
System.out.print("\n");
}while(tempoPatient.setPatientIC(patientIC) == false);
//input patient gender
do{
System.out.print("Patient gender(Eg: M) : ");
patientGender = scan.nextLine();
System.out.print("\n");
}while(tempoPatient.setPatientGender(patientGender) == false);
//input patient tel. no
do{
System.out.print("Patient tel.No(without'-')(Eg: 0162345678/0342980123) : ");
patientTelNo = scan.nextLine();
System.out.print("\n");
}while(tempoPatient.setPatientTelNo(patientTelNo) == false);
//input patient address
do{
System.out.print("Patient address(Eg: 4-C9 Jln Besar 123, Taman Besar, 56000 Kuala Lumpur) : ");
patientAdd = scan.nextLine();
System.out.print("\n");
}while(tempoPatient.setPatientAdd(patientAdd) == false);
tempoPatient.setQueueTime(queueTime);
tempoPatient.setVisitDate(visitDate);
patientList.add(tempoPatient);
//decide whether want to enter a new patient or not
do{
System.out.print("Do you want to enter another new patient?(Eg: Y/N) : ");
continueInput = scan.nextLine();
if(continueInput.equals("Y") || continueInput.equals("y"))
{
enterNewPatient = true;
System.out.print("\n");
}
else if(continueInput.equals("N") || continueInput.equals("n"))
{
enterNewPatient = false;
}
else
{
System.out.println("\n");
System.out.println("Please enter Y/N only.\n");
}
}while(!continueInput.equals("Y") && !continueInput.equals("y") && !continueInput.equals("N") && !continueInput.equals("n"));
countEnteredPatient++;
}while(enterNewPatient); //end do-while loop for entering new patient details
System.out.println("\nWaiting list of patient will be displayed soon.\n");
try{
Thread.sleep(1000);
}
catch (Exception e)
{
}
System.out.println("Waiting list of patients");
System.out.println("========================\n");
System.out.println("Number\t\tEmergency number\t\tPatient name\t\t ArrivalTime");
System.out.println("============================================================================");
for(int i = 1; i <= patientList.getLength(); i++)
{
System.out.println(i + "\t\t\t" + patientList.getEntry(i).anotherToString());
}
do{
System.out.print("\nSo, now do you want to enter another new patient?(Eg: Y/N) : ");
continueInput1 = scan.nextLine();
if(continueInput1.equals("Y") || continueInput1.equals("y"))
{
enterNewPatient1 = true;
System.out.print("\n");
}
else if(continueInput1.equals("N") || continueInput1.equals("n"))
{
enterNewPatient1 = false;
}
else
{
System.out.println("\n");
System.out.println("Please enter Y/N only.\n");
}
}while(!continueInput1.equals("Y") && !continueInput1.equals("y") && !continueInput1.equals("N") && !continueInput1.equals("n"));
}while(enterNewPatient1);//end do-while loop for entering new patient details after viewing patient list
System.out.println("\nNow rearranging the list based on the seriouness and their arrival time.");
try{
Thread.sleep(1000);
}
catch (Exception e)
{
}
//create an unsorted array
Patient[] tempoPatientArr = new Patient[patientList.getLength()];
//copy the contents of patientList into tempoPatientArr
for(int i = 1; i <= patientList.getLength(); i++ )
{
tempoPatientArr[i-1] = patientList.getEntry(i);
}
//sort tempoPatientArr
Arrays.sort(tempoPatientArr, new EmergencyCmp());
//the above part until this comment line does not have problem
//check the emergency no and then categorise accordingly
for(int i = 0; i < tempoPatientArr.length; i++)
{
if(tempoPatientArr[i].getEmergencyNo() == 1)
{
patientArr1[x] = tempoPatientArr[i];
x++;
}
else if(tempoPatientArr[i].getEmergencyNo() == 2)
{
patientArr2[y] = tempoPatientArr[i];
y++;
}
else if(tempoPatientArr[i].getEmergencyNo() == 3)
{
patientArr3[z] = tempoPatientArr[i];
z++;
}
}
//to check how many !null elements by using count for 3 sub-arrays
for(int i = 0; i < patientArr1.length; i++)
{
if(patientArr1[i] != null)
{
count1++;
}
else
{
break;
}
}
for(int i = 0; i < patientArr2.length; i++)
{
if(patientArr2[i] != null)
{
count2++;
}
else
{
break;
}
}
for(int i = 0; i < patientArr3.length; i++)
{
if(patientArr3[i] != null)
{
count3++;
}
else
{
break;
}
}
//new array with elimination of null values
Patient[] newPatientArr1 = new Patient[count1];
Patient[] newPatientArr2 = new Patient[count2];
Patient[] newPatientArr3 = new Patient[count3];
//copy the contents of old sub arrays(the arrays with null values) into the new sub arrays(without null values)
for(int i = 0; i < newPatientArr1.length; i++)
{
newPatientArr1[i] = patientArr1[i];
}
for(int i = 0; i < newPatientArr2.length; i++)
{
newPatientArr2[i] = patientArr2[i];
}
for(int i = 0; i < newPatientArr3.length; i++)
{
newPatientArr3[i] = patientArr3[i];
}
totalCount = count1 + count2 + count3;
//array that used to combine all the sub-arrays
Patient[] newPatientArr = new Patient[totalCount];
//sort all sub new arrays
Arrays.sort(newPatientArr1, new QueueCmp());
Arrays.sort(newPatientArr2, new QueueCmp());
Arrays.sort(newPatientArr3, new QueueCmp());
//combine the contents of sub new arrays into the newPatientArr array
do{
for (int i = 0; i < count1; i++)
{
newPatientArr[j] = newPatientArr1[i];
j++;
}
for (int b = 0; b < count2; b++)
{
newPatientArr[j] = newPatientArr2[b];
j++;
}
for (int c = 0; c < count3; c++)
{
newPatientArr[j] = newPatientArr3[c];
j++;
}
}while(j < totalCount);
//relink the nodes
for(int i = 0; i < newPatientArr.length; i++)
{
newPatientList.add(newPatientArr[i]);
}
System.out.println("\nSorted waiting list of patients");
System.out.println("===============================\n");
System.out.println("Number\t\tEmergency number\t\tPatient name\t\t ArrivalTime");
System.out.println("============================================================================");
for(int i = 1; i <= newPatientList.getLength(); i++)
{
System.out.println(i + "\t\t\t" + newPatientList.getEntry(i).anotherToString());
}
}
}
Interface and LList class definitely do not have problems. So everyone can skip the 2 parts.
For the main function, I have a comment like this:
//the above part until this comment line does not have problem
When you all see the comment, that means the previous code does not have problem and you all may skip it and below is an attachment of the result that I got earlier:
So, from the picture you all can see that the sorting of arrival time is not correct. I hope that I can know why does this problem occurs since I cannot figure it out by myself. Thanks to all of you first.
So, after taking the advice of #Scott Hunter, I have made the following modification to the EmergencyCmp:
#Override
public int compare(Patient p1, Patient p2)
{
int value = 0;
if(p1.getEmergencyNo() > p2.getEmergencyNo())
{
value = 1;
}
else if(p1.getEmergencyNo() < p2.getEmergencyNo())
{
value = -1;
}
else if(p1.getEmergencyNo() == p2.getEmergencyNo())
{
if(p1.getQueueTime() > p2.getQueueTime())
{
return 1;
}
else
{
return -1;
}
}
return value;
}
However, the time sorting still produce a wrong result.
As I understand it (which I may not; you provided a LOT of extraneous stuff), it looks like you are trying to perform 2 distinct sorts, one after the other, such that the second is undoing the work of the first. Instead, you should define a single Comparator which compares emergency numbers and, only if they are the same, compares arrival times.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have created an array of Song objects. A song contains the variables title, author, interpreter, (int)yearReleased, album, and fileName. I am using a main method to test my array of songs and my equals method. The test is supposed to fill an array with five song objects and use my equals method to ensure the new entry is not a duplicate of a previous entry. My test class compiles, but when I enter duplicate song information I keep getting an error. If anyone could give me a tip or point me in the correct direction I would greatly appreciate it. Any other tips would also be great. As a student, it is great to hear good real world advice from professionals.
import java.util.Scanner;
public class Test{
public static void main(String[] args)
{
Scanner kybd = new Scanner(System.in);
Song[] songTest = new Song[5];
boolean match;
int count = 0;
System.out.println("Enter 5 songs\n");
for(Song x:songTest)
{
do{
match = false;
x = new Song();
System.out.print("Title: ");
x.setTitle(kybd.nextLine());
System.out.print("Author: ");
x.setAuthor(kybd.nextLine());
System.out.print("Interpreter: ");
x.setInterpreter(kybd.nextLine());
System.out.print("Year released: ");
x.setYearReleased(kybd.nextInt());
kybd.nextLine();
System.out.print("Album: ");
x.setAlbum(kybd.nextLine());
System.out.print("File name: ");
x.setFileName(kybd.nextLine());
System.out.print(x);
System.out.println();
for(int i = 0; i<count; i++)
if(songTest[i].equals(x)){
match = true;
System.out.print("Duplicate");
}
}while(match);
count++;
}
}
}
public class Song
{
public String title;
public String author;
public String interpreter;
public int yearReleased;
public String album;
public String fileName;
//private vars
private int reviewScore = 0;
private int reviews = 0;
private double average;
//Mutator methods
public void setTitle(String t)
{
this.title = t;
}
public void setAuthor(String a)
{
this.author = a;
}
public void setInterpreter(String i)
{
this.interpreter = i;
}
public void setYearReleased(int y)
{
if (y>0)
this.yearReleased = y;
else
{
System.out.print ("This song is not that old");
this.yearReleased = -5;
}
}
public void setAlbum(String a)
{
this.album = a;
}
public void setFileName(String f)
{
this.fileName = f;
}
public void addReviewScore(int s)
{
if (s>0 && s<6)
{
this.reviewScore += s;
this.reviews++;
}
else
System.out.print("This is not a valid review score!");
}
//Accessor methods
public String getTitle()
{
return this.title;
}
public String getAuthor()
{
return this.author;
}
public String getInterpreter()
{
return this.interpreter;
}
public int getYearReleased()
{
return this.yearReleased;
}
public String getAlbum()
{
return this.album;
}
public String getFileName()
{
return this.fileName;
}
public double getAverage()
{
this.average = this.calculateAverage();
return this.average;
}
//Methods
public boolean equals(Song otherSong)
{
boolean isEqual = false;
//compare this song to the otherSong
isEqual =
this.title == otherSong.title &&
this.author == otherSong.author &&
this.interpreter == otherSong.interpreter &&
this.yearReleased == otherSong.yearReleased &&
this.album == otherSong.album &&
this.fileName == otherSong.fileName;
return isEqual;
}
public String toString()
{
String songInfo;
songInfo =
"***Song information***\n" +
"Title: " + this.title +
"\nAuthor: " + this.author +
"\nInterpreter: " + this.interpreter +
"\nYear Released: " + this.yearReleased +
"\nAlbum: " + this.album +
"\nFile name: " + this.fileName +
"\nYears old: " + this.yearsOld();
return songInfo;
}
public int yearsOld()
{
int yearsOld = (2012 - this.yearReleased);
return yearsOld;
}
//Private methods
private double calculateAverage()
{
this.average = ((double)this.reviewScore/(double)this.reviews);
return this.average;
}
}
I tried your code and reproduced the error which occurs at this line:
if(songTest[i].equals(x)){
rewriting your equals method (or getting eclipse to do it for me) and adding the hashCode() solved the problem:
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((album == null) ? 0 : album.hashCode());
result = prime * result + ((author == null) ? 0 : author.hashCode());
long temp;
temp = Double.doubleToLongBits(average);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result
+ ((fileName == null) ? 0 : fileName.hashCode());
result = prime * result
+ ((interpreter == null) ? 0 : interpreter.hashCode());
result = prime * result + reviewScore;
result = prime * result + reviews;
result = prime * result + ((title == null) ? 0 : title.hashCode());
result = prime * result + yearReleased;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Song other = (Song) obj;
if (album == null) {
if (other.album != null)
return false;
} else if (!album.equals(other.album))
return false;
if (author == null) {
if (other.author != null)
return false;
} else if (!author.equals(other.author))
return false;
if (Double.doubleToLongBits(average) != Double
.doubleToLongBits(other.average))
return false;
if (fileName == null) {
if (other.fileName != null)
return false;
} else if (!fileName.equals(other.fileName))
return false;
if (interpreter == null) {
if (other.interpreter != null)
return false;
} else if (!interpreter.equals(other.interpreter))
return false;
if (reviewScore != other.reviewScore)
return false;
if (reviews != other.reviews)
return false;
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
if (yearReleased != other.yearReleased)
return false;
return true;
}
you also seem to have a problem with the counter not incrementing properly, but I'm not going to do all of you homework for you! ;)
edit:
Woah!
You're also missing something like
songTest[i] = song;
to add the checked song to your array.
also, to make sure your first song gets put in I added:
if(i==0){
songTest[i] = x;
}
before your check.
The i is and int I added by changing your first for loop back to the old fashioned version, and I renamed your inner for loop to j.
Now it works.
try putting in something like:
System.out.println("i: " + i + " j: " + j + " count: " + count);
to see what's going on with your counters
You also exit after finding a duplicate. Is this the behavior you want? Or would it be better to notify the user, and continue inputting song data.
When I run this, I get a null pointer exception on this line
if(songTest[i].equals(x)){
It looks like you're not actually putting the song object (x) into the array.