Binary Search Same items & Store and Display them - java

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.

Related

How do I fill an array with user-defined objects?

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, getNodes(), is created that should return an array containing all the nodes.
My problem lies within the method getNodes(), as I am struggling to populate the array. My code is below.
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;
}
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 boolean contains(Line line) {
for (int i = 0; i < numLines; i++) {
if (line == lines[i])
return true;
}
return false;
}
public Line getLine(String name) {
for (int i = 0; i < numLines; i++) {
if (lines[i].getName().equals(name))
return lines[i];
}
System.out.println("Line " + name + " not found");
return null;
}
public void printModel() {
System.out.println('\n' + "Line model: " + name);
for (int i = 0; i < numLines; i++) {
System.out.println(lines[i]);
}
}
public Node getNode(String name) {
// Loop through lines
for (int i = 0; i <= numLines; i++) {
// Check if node 1 is contained in the line and returns if true
if (lines[i].getN1().getName().equals(name)) {
return lines[i].getN1();
}
// Check if node 2 is contained in the line and returns if true
else if (lines[i].getN2().getName().equals(name)) {
return lines[i].getN2();
}
}
return null;
}
public Node[] getNodes() {
Node[] nodes = new Node[2 * numLines];
for (int i = 0; i < numLines; i++) {
Node start = lines[i].getN1();
Node end = lines[i].getN2();
for (int j = 0; j < nodes.length - 1; j++) {
nodes[j] = start;
for (int k = 1; k <= nodes.length - 1; k++) {
nodes[k] = end;
}
}
}
return nodes;
}
}
Classes Node and Line are below
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);
}
}
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();
}
My current output is this:
[L_22751459.Node;#7530d0a
You just need to replace your getNodes() method with below code.
Need to introduce extra variable count and for every added node simply increment it. So automatically for two lines it will add four nodes like node[0],node[1],node[2],node[3]
public Node[] getNodes() {
int count=0;
Node[] nodes = new Node[2 * numLines];
for (int i = 0; i < numLines; i++) {
nodes[count]=lines[i].getN1();
nodes[count+1]=lines[i].getN2();
count=count+2;
}
return nodes;
}
public static void main(String[] args) {
LineModel obj2=new LineModel("l2",2);
obj2.addLine(new Line("name1",new Node("x",1.0),new Node("y",2.0)));
obj2.addLine(new Line("name2",new Node("x",2.0),new Node("y",3.0)));
Node[] arr=obj2.getNodes();
Arrays.stream(arr).forEach(node -> System.out.println(node.toString()));
}
Above code printing below Output which is perfectly fine.
Node x [1.0]
Node y [2.0]
Node x [2.0]
Node y [3.0]

Sort Single Linked List in descending order

How would I display this linked list in desending order by Score? I need it when it when I display it in my GUI to sort by the highest score at the top, and then desending to the lowest score in the bottom? Also, I was wondering if there is a way to limit the entries to only 10. Any help would be appreciated! Thanks.
public class ScoreList {
private Player head; //reference to the head of the list
private Player tail; //reference to the tail of the list
int count;
public ScoreList() {
count = 0;
head = null;
tail = null;
}
public int getCount() {
return count;
}
public int size() {
int count = 0;
Player p = head;
while(p != null) {
count++;
p = p.next;
}
return count;
}
//method to add an item to the list - append to the tail of the list
public void add(String name, String score) {
// Create Player object
Player newPlayer = new Player(name, score);
if (head == null) {
head = newPlayer;
tail = head;
count++;
}
else {
//append to the end of the list
tail.setNext(newPlayer);
tail = newPlayer;
count++;
}
if(size() > 10) {
Player currentPlayer = head;
for (int i = 0; i < 9; i++) {
currentPlayer = currentPlayer.next;
}
currentPlayer.next = null;
}
}
// end add method
//method to let the user get the data from a node in the list
public String getItem(int index) {
String result = "";
String name = "";
String score = "";
Player curName;
if (count > 0 && index == 0) {
//return the Player info at the head of the list
name = head.getName();
score = head.getScore();
}
else if (index > 0 && index < count) {
curName = head;
for (int i = 1; i <= index; i++) {
curName = curName.getNext();
}
name = curName.getName();
score = curName.getScore();
}
result = "Player: " + name + " Score: " + score;
return result;
}
//nested inner class
public class Player {
private String player;
private String score;
private Player next;
public Player() {
player = "";
score = "";
next = null;
}
public Player(String artist, String title) {
this.player = artist;
this.score = title;
next = null;
}
public String getName() {
return player;
}
public String getScore() {
return score;
}
public Player getNext() {
return next;
}
public void setArtist(String player) {
this.player = player;
}
public void setTitle(String score) {
this.score = score;
}
public void setNext(Player next) {
this.next = next;
}
}
}
Why are you taking Score as a String?
I am assuming score as Integer
below is the sort method that you can include in ScoreList class, which will sort your LinkList in descending order of player score.
Time Complexity : O(nlogn)
Space COmplexity: O(n)
Hope this helps
public void sort() {
Player runner = head;
Player[] arr = new Player[size()];
int i = 0;
while (runner != null) {
arr[i++] = runner;
runner = runner.next;
}
Arrays.sort(arr, new Comparator<Player>() {
public int compare(Player o1, Player o2) {
if (Integer.parseInt(o1.getScore()) > Integer.parseInt(o2.getScore())) {
return -1;
} else if (Integer.parseInt(o1.getScore()) < Integer.parseInt(o2.getScore())) {
return 1;
} else {
return 0;
}
}
});
for (int j = 0; j < arr.length - 1; j++) {
arr[j].setNext(arr[j + 1]);
}
if (arr.length > 0) {
arr[arr.length - 1].setNext(null);
head = arr[0];
tail = arr[arr.length - 1];
}
}

Displaying search results from a hash table

I can't figure out how to display the results from my search method. I put strings in where it needs to display the results.
Here is the client class
public class Client
{
private String name;
private String city;
public Client(String name, String city)
{
this.name = name;
this.city = city;
}
public String toString()
{
return name + " " + city;
}
public String getName()
{
return name;
}
public String getCity()
{
return city;
}
}
Here is my Hashtable class
public class Hashtable {
private int n;
private Client[] table;
public Hashtable(int n) {
this.n = n;
table = new Client[n];
}
public int hashFunction(String key) {
int sum = 0;
for (int i = 0; i < key.length(); i++) {
sum += (int) key.charAt(i);
}
sum = sum%n;
return sum;
}
public String search(String key) {
int sum = 0;
for (int i = 0; i < key.length(); i++) {
sum += (int) key.charAt(i);
}
sum = sum%n;
if (key.equals(table[sum])) {
return ("Returns the toString from the client class here");
} else if (table[sum] == null) {
return null;
} else {
while (table[sum] != null) {
sum++;
}
return ("Returns the toString from the client class here");
}
}
public boolean insert(Client myClient) {
int counter = 0;
String temp = myClient.getName();
boolean ret = false;
int tempSum = 0;
for (int i = 0; i < temp.length(); i++) {
tempSum += (int) temp.charAt(i);
}
tempSum = tempSum%n;
if (table[tempSum] == null) {
table[tempSum] = myClient;
ret = true;
} else {
while (table[tempSum] != null) {
if(tempSum == table.length){
tempSum = -1;
}
tempSum++;
counter++;
}
if(counter != n){
ret = true;
table[tempSum] = myClient;
}
}
return ret;
}
}
When you are comparing the key in search method, Make sure you compare against name.
Change table[sum] to table[sum].getName() ???? I modified the code and added comments for the change.
public class Hashtable {
private int n;
private Client[] table;
public Hashtable(int n) {
this.n = n;
table = new Client[n];
}
public int hashFunction(String key) {
int sum = 0;
for (int i = 0; i < key.length(); i++) {
sum += (int) key.charAt(i);
}
sum = sum%n;
return sum;
}
public String search(String key) {
int sum = 0;
for (int i = 0; i < key.length(); i++) {
sum += (int) key.charAt(i);
}
sum = sum%n;
if (key.equals(table[sum].getName())) { //This Should be table[sum].getName()
return ("Returns the toString from the client class here");
} else if (table[sum] == null) {
return null;
} else {
while (table[sum] != null) {
sum++;
}
return ("Returns the toString from the client class here");
}
}
public boolean insert(Client myClient) {
int counter = 0;
String temp = myClient.getName();
boolean ret = false;
int tempSum = 0;
for (int i = 0; i < temp.length(); i++) {
tempSum += (int) temp.charAt(i);
}
tempSum = tempSum%n;
if (table[tempSum] == null) {
table[tempSum] = myClient;
ret = true;
} else {
while (table[tempSum] != null) {
if(tempSum == table.length){
tempSum = -1;
}
tempSum++;
counter++;
}
if(counter != n){
ret = true;
table[tempSum] = myClient;
}
}
return ret;
}
}
Let me know if that helped

Odd return on PEMDAS calculator

It seems that this calculator works for all other cases, except cases like this:
(2*3^4)
It does not return 162, instead, it returns 0.0.
I identified that the error must be from the method public static double operation, since the default return statement is 0.0
Here is the code:
import java.util.Iterator;
import java.util.NoSuchElementException;
public class StackC<Item> implements Stack<Item> {
private Item[] a; // array of items
private int N; // number of elements on stack
public StackC() {
a = (Item[]) new Object[2];
}
public boolean isEmpty() {
return N == 0;
}
public int size() {
return N;
}
private void resize(int capacity) {
assert capacity >= N;
Item[] temp = (Item[]) new Object[capacity];
for (int i = 0; i < N; i++) {
temp[i] = a[i];
}
a = temp;
}
public void push(Item item) {
if (N == a.length) resize(2*a.length); // double size of array if necessary
a[N++] = item; // add item
}
public Item pop() {
if (isEmpty())
throw new NoSuchElementException("Stack underflow");
Item item = a[N-1];
a[N-1] = null; // to avoid loitering
N--;
// shrink size of array if necessary
if (N > 0 && N == a.length/4)
resize(a.length/2);
return item;
}
public Item peek() {
if (isEmpty())
throw new NoSuchElementException("Stack underflow");
return a[N-1];
}
public Iterator<Item> iterator() {
return new ReverseArrayIterator();
}
private class ReverseArrayIterator implements Iterator<Item> {
private int i;
public ReverseArrayIterator() {
i = N;
}
public boolean hasNext() {
return i > 0;
}
public void remove() {
throw new UnsupportedOperationException();
}
public Item next() {
if (!hasNext()) throw new NoSuchElementException();
return a[--i];
}
}
//---------------------------------------------------------------------
public static void main(String[] args) {
StackC<String> Operator = new StackC<String>();
StackC<Double> Values = new StackC<Double>();
while (!StdIn.isEmpty()) {
String token = StdIn.readString();
try {
Double x = Double.parseDouble(token);
Values.push(x);
}
catch(NumberFormatException nFE) {
}
if (token.equals("("))
Operator.push(token);
if (token.equals(")"))
{
if (Operator.peek() != "(")
{
String type = Operator.pop();
double b = Values.pop();
double a = Values.pop();
Values.push(operation(type,a,b));
}
Operator.pop();
}
if(token.equals("*") || token.equals("+") || token.equals("/") || token.equals("-") || token.equals("^") )
{
if(!Operator.isEmpty())
{
String prev = Operator.peek();
int x = comparePrecedence(token, Operator.peek()); // You need to compare precedence first
if(x == -1 || x == 0)
{
String type = Operator.pop();
double b = Values.pop();
double a = Values.pop();
Values.push(operation(type,a,b));
}
}
Operator.push(token);
}
}
while(!Operator.isEmpty())
{
String prev = Operator.peek();
String type = Operator.pop();
double b = Values.pop();
double a = Values.pop();
Values.push(operation(type,a,b));
}
System.out.println(Values.pop());
}
public static double operation(String operator, double a, double b) {
if (operator.equals("+"))
return a + b;
else if (operator.equals("-"))
return a - b;
else if (operator.equals("*"))
return a * b;
else if (operator.equals("/"))
return a / b;
else if (operator.equals("^"))
return Math.pow(a,b);
return 0.0;
}
public static int comparePrecedence(String x, String y)
{
int val1 = 0;
int val2 = 0;
if(x.equals("-"))
val1 = 0;
if(y.equals("-"))
val2 = 0;
if(x.equals("+"))
val1 = 1;
if(y.equals("+"))
val2 = 1;
if(x.equals("/"))
val1 = 2;
if(y.equals("/"))
val2 = 2;
if(x.equals("*"))
val1 = 3;
if(y.equals("*"))
val2 = 3;
if(x.equals("^"))
val1 = 4;
if(y.equals("^"))
val2 = 4;
if(val1 > val2)
return 1;
else if(val2 > val1)
return -1;
else
return 0;
}
}
Everything above the dotted line was given via the professor, and is not the problem for the code.
StdIn is simply a method that reads inputs.

forming equals methods java hw

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.

Categories