I'm making a phone book and filling it with entries. The entries consist of two Strings for surname and initial, and a telephone number. I'm using an array to store the entries. I'm trying to get the array to print out and I've put toString methods in each class. But when I print out i'm still getting "[LEntry;#8dc8569". I'm not sure what I'm doing wrong. Here's the code.
public class Entry {
String surname;
String initial;
int number;
public Entry(String surname, String initial, int number) {
this.surname = surname;
this.initial = initial;
this.number = number;
}
public String getSurname(){
return surname;
}
public String getInitial(){
return initial;
}
public int getNumber() {
return number;
}
void setNumber(int number){
this.number = number;
}
public String toString(){
return surname+ "\t" +initial+ "\t" +number;
}
}
public class ArrayDirectory {
int DIRECTORY_SIZE = 6;
Entry [] directory = new Entry[DIRECTORY_SIZE];
public void addEntry(String surname, String initial, int num) {
int i = findFreeLocation();
directory[i] = new Entry(surname, initial, num);
}
public void deleteEntry(String surname, String initial) {
int i = findEntryIndex(surname, initial);
directory[i] = null;
}
public void deleteEntry(int number) {
int i = findEntryIndex(number);
directory[i] = null;
}
public int findEntry(String surname, String initial) {
int i;
i = findEntryIndex(surname, initial);
return directory[i].getNumber();
}
public void editNum(String surname, String initial, int number) {
int i;
i = findEntryIndex(surname, initial);
directory[i].setNumber(number);
}
public void print() {
// TODO print array
System.out.println(directory);
}
private int findEntryIndex(String surname, String initial) {
int i;
for (i = 0; i <= DIRECTORY_SIZE; i++)
{
if(directory[i] != null && directory[i].getSurname().equals(surname) && directory[i].getInitial().equals(initial))
{
break;
}
}
return i;
}
private int findEntryIndex(int number) {
int i;
for (i = 0; i <= DIRECTORY_SIZE; i++)
{
if(directory[i] != null && directory[i].getNumber() == number)
{
break;
}
}
return i;
}
private int findFreeLocation() {
int i;
for (i = 0; i < DIRECTORY_SIZE; i++)
{
if(directory[i] == null)
{
break;
}
}
return i;
}
public String toString() {
for(int i = 0 ; i< DIRECTORY_SIZE ; i++){
System.out.println( directory[i] );
}
return null;
}
}
public class Test {
public static void main(String[] args) {
ArrayDirectory phoneBook = new ArrayDirectory();
phoneBook.addEntry("Bigger", "R", 2486);
phoneBook.addEntry("Smaller", "E", 0423);
phoneBook.addEntry("Ringer", "J", 6589);
phoneBook.addEntry("Looper", "T", 6723);
phoneBook.addEntry("Lennon", "B", 4893);
phoneBook.addEntry("Martin", "M", 2121);
phoneBook.print();
}
}
Use Arrays.toString();
Arrays.toString(directory);
when you just print directory, which is an instance of array of type Entry, it doesn't override the toString() method the way you are expecting
Also See
Why isn't there a java.lang.Array class? If a java array is an Object, shouldn't it extend Object?
Related
I have been working on an assignment and i am stuck at here. Basically i have 1 class which defines all functions and members.
And another class to initialize and manipulate objects.
Here is my first class code.
public class cyryxStudent_association {
String studentID, studentName, studentCourse_level, studentTitle;
int course_completed_year;
static double registration_fee;
double activity_fee;
double total_amt;
//Default constructor
cyryxStudent_association ()
{
studentID = "Null";
studentName = "Null";
studentCourse_level = "Null";
studentTitle = "Null";
course_completed_year = 0;
}
//Parameterized Constructor
cyryxStudent_association (String id, String name, String course_level, String title, int ccy)
{
this.studentID = id;
this.studentName = name;
this.studentCourse_level = course_level;
this.studentTitle = title;
this.course_completed_year = ccy;
}
//Getters
public String getStudentID ()
{
return studentID;
}
public String getStudentName ()
{
return studentName;
}
public String getStudentCourse_level ()
{
return studentCourse_level;
}
public String getStudentTitle ()
{
return studentTitle;
}
public int getCourse_completed_year ()
{
return course_completed_year;
}
public double getRegistration_fee ()
{
return registration_fee;
}
public double getActivity_fee ()
{
return findActivity_fee(registration_fee);
}
public double getTotal_amt ()
{
return total_amt(registration_fee, activity_fee);
}
//Setters
public void setStudentID (String id)
{
studentID = id;
}
public void setStudentName (String name)
{
studentName = name;
}
public void setStudentCourse_level (String course_level)
{
studentCourse_level = course_level;
}
public void setStudentTitle (String title)
{
studentTitle = title;
}
public void setCourse_completed_year (int ccy)
{
course_completed_year = ccy;
}
//Find registration fee method
public static double findRegistration_fee (String course_level)
{
if (course_level.equalsIgnoreCase("Certificate"))
{
registration_fee = 75;
}
else if (course_level.equalsIgnoreCase("Diploma"))
{
registration_fee = 100;
}
else if (course_level.equalsIgnoreCase("Degree"))
{
registration_fee = 150;
}
else if (course_level.equalsIgnoreCase("Master"))
{
registration_fee = 200;
}
return registration_fee;
}
//Find activity method
public static double findActivity_fee (double registration_fee)
{
return registration_fee * 0.25;
}
//Find total amount
public static double total_amt (double registration_fee, double activity_fee)
{
return registration_fee + activity_fee;
}
//To string method
public String toString ()
{
return "ID: "+getStudentID()+"\nName: "+getStudentName()+"\nCourse Level:
"+getStudentCourse_level()+"\nTitle: "+getStudentTitle()+"\nCourse Completed Year:
"+getCourse_completed_year()+"\nRegistration Fee: "+getRegistration_fee()+"\nActivity Fee:
"+getActivity_fee()+"\nTotal Amount: "+getTotal_amt ();
}
}
And here is my second class code.
import java.util.Scanner;
public class test_cyryxStudent_association {
public static void main (String[] args)
{
Scanner sc = new Scanner (System.in);
int num, i;
System.out.println("Welcome!");
System.out.println("\nEnter the number of students: ");
num = sc.nextInt();
sc.nextLine();
cyryxStudent_association Std[] = new cyryxStudent_association[num];
for (i = 0; i < Std.length; i++)
{
System.out.println("\nEnter ID: ");
Std[i].setStudentID(sc.nextLine());
System.out.println("Enter Name: ");
Std[i].setStudentName(sc.nextLine());
System.out.println("Enter Course Level [Certificate, Diploma, Degree, Master]: ");
Std[i].setStudentCourse_level(sc.nextLine());
System.out.println("Enter Title: ");
Std[i].setStudentTitle(sc.nextLine());
Std[i].getRegistration_fee();
Std[i].getActivity_fee();
Std[i].getTotal_amt();
}
for (i = 0; i < Std.length; i++)
{
System.out.println("\nStudent " + i + 1 + " Information");
System.out.println("===================================");
Std[i].toString();
}
sc.close();
}
}
I get an error when values in the for loop. Can someone help me? I'm pretty new to programming and studying java for 2 months now. What am i doing wrong?
Here is my objectives.
Create an array of objects and get user input for number of objects to be manipulated.
Read and display array of object values.
Thank you!
You have to initialize the objects of your array.
After the line:
cyryxStudent_association Std[] = new cyryxStudent_association[num];
do a for loop like:
for(i = 0; i<std.length; i++){
std[i] = new cyryxStudent_association();
}
I am getting an error as follows:
/AccountDemo.java:53: error: missing return statement } ^ 1 error
I have tried everything. How can I fix this problem?
class Account
{
private int number;
public int getNumber()
{
return this.number;
}
public void setNumber(int number1)
{
number=number1;
}
}
public class AccountDemo {
public static void main(String[] args) {
Account[] objArray= new Account[5];
objArray[0].setNumber(7);
objArray[1].setNumber(3);
objArray[2].setNumber(5);
objArray[3].setNumber(4);
objArray[4].setNumber(9);
int accountres= searchAccountByNumber(objArray, 63);
System.out.println("Output after first search: "+accountres);
int accountres1= searchAccountByNumber(objArray, 4);
System.out.println("Output after second search: "+accountres1);
}
public static int searchAccountByNumber(Account[] objArray,int s)
{
int i=0;
for(i=0;i<5;i++)
{
if(objArray[i].getNumber()==s)
{
return i;
}
else
{
return -1;
}
}
}
}
I solved it by assigning a variable to it rather than directly returning it, looks as if it works.
class Account {
private int number;
public int getNumber() {
return this.number;
}
public void setNumber(int number1) {
number = number1; }
}public class AccountDemo {
public static void main(String[] args) {
Account[] objArray = new Account[5];
objArray[0].setNumber(7);
objArray[1].setNumber(3);
objArray[2].setNumber(5);
objArray[3].setNumber(4);
objArray[4].setNumber(9);
int accountres = searchAccountByNumber(objArray, 63);
System.out.println("Output after first search: " + accountres);
int accountres1 = searchAccountByNumber(objArray, 4);
System.out.println("Output after second search: " + accountres1);
}
public static int searchAccountByNumber(Account[] objArray, int s) {
int finalreturn = 0;
int i = 0;
for (i = 0; i < 5; i++) {
if (objArray[i].getNumber() == s) {
finalreturn = i;
} else {
finalreturn = -1;
}
}
return finalreturn;
}
}
Good Luck!
Alright I am stuck on how do I implement this binary search that will receive data from other classes.
I am trying to implement it in my own ADT.
I have implemented a List ADT manually but now I want to add in a search operation which utilizes binary search algorithm manually and doesn't uses any built in Java API.
Example this is my sorted list interface that I implemented manually.
public class SortedArrayList<T extends Comparable<T>> implements SortedListInterface<T>{
private boolean binarySearch(// What parameters should I receive from Student Object?) {
// This will be my binary search implementation
}
}
The problem is I will be creating a Student class where I will add the instances of the student class into the sortedArrayList above.
Like how am I going to receive the data to be put into the binary search algorithm in a generics typed sortedArrayList?
Do note I am not allowed to use any JAVA Built-IN API , everything must be implemented manually else I can finish this easily but its a pain now since its limited.
Example I want to binary search by Student name from Student's class. How will I need to implement and receive data into this manually implemented ADT of mine?
public class SortedArrayList<T extends Comparable<T>> implements SortedListInterface<T>{
private T[] list;
private boolean binarySearch(int first, int last, T desiredItem) {
int mid = (first + last) / 2;
if(desiredItem.getFullName().equals(list[mid])
// This part over here. How do I access attributes from Student class in this ADT so that I can access the data and do comparison for the binary search..
}
}
How do I access attributes from Student class into my own ADT so that I can do comparisons on binary search algorithm?!
I am literally stuck.
I would appreciate someone giving me directions.
I repeat again no BUILT-IN APIs from JAVA, implementation manually only
ADT SortedList Interface
public interface SortedListInterface <T extends Comparable<T>> {
public boolean add(T element);
public T get(int index);
public boolean search(T element);
public T remove(int index);
public void clear();
public int getLength();
public boolean isEmpty();
public boolean isFull();
}
ADT SortedList Implementation Code
public class SortedArrayList<T extends Comparable<T>> implements SortedListInterface<T>{
//Data Types
private T[] list;
private int length;
private static final int SIZE = 10;
// Constructors
public SortedArrayList() {
this(SIZE);
}
public SortedArrayList(int size) {
length = 0;
list = (T[]) 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() {
T[] oldList = list;
int oldSize = oldList.length;
list = (T[]) 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(T 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;
}
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 T remove(int index) { // accepts given index
T 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 T get(int index) { // accepts given index and return the object
T object = null;
if ( index >= 1 && index <= length)
object = list[index - 1];
return object;
}
// Search Algorithms
#Override
public boolean search(T element) {
return binarySearch(element);
}
private boolean binarySearch(// Implementation here) {
// Implementation here
}
//To String Method
#Override
public String toString() {
String result = "";
for (int i = 0; i < length; i++)
result += list[i] + "\n";
return result;
}
}
Student Class Implementation
public class Student implements Comparable<Student>{
// Data Types
private Name name;
private char gender;
private String icNo;
private String mobileNo;
private Course course;
private int group;
private String dOB;
// Constructors
public Student() {
}
public Student(Name name, char gender, String icNo, String mobileNo, Course course, int group, String dOB) {
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 setName(Name name) {
this.name = name;
}
public void setGender(char 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(int group) {
this.group = group;
}
public void setdOB(String dOB) {
this.dOB = dOB;
}
// getter
public Name getName() {
return name;
}
public char getGender() {
return gender;
}
public String getIcNo() {
return icNo;
}
public String getMobileNo() {
return mobileNo;
}
public Course getCourse() {
return course;
}
public int 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 + '}';
}
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 - 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 - object.getGroup();
if(c == 0)
c = this.dOB.compareTo(object.getdOB());
return c;
}
}
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;
}
}
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 + '}';
}
The binary search algorithm relies on comparing a value being searched for with values in the list being searched. That's why the declaration of your class that implements the SortedListInterface is:
SortedArrayList<T extends Comparable<T>>
Note the extends Comparable<T>.
Comparable is an interface through which you can compare two objects. Hence in the search() method that you have to implement, you know that every object in the list defines the compareTo() method and you simply use that method to compare the object being searched for with individual objects in the list.
Here is a simple implementation of the binary search algorithm in the context of your project.
private T[] list; // The list to search.
private int count; // The number of non-null elements in 'list'.
public boolean search(T 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 {
found = true;
break;
}
}
return found;
}
With a method, you have a method parameter. In the method code you use the parameter name. But when you invoke that method from other code, you provide a value which is substituted for the parameter. In the same way, the code above uses a type parameter which is substituted with the name of an actual class when you create an instance of class SortedArrayList. In your case, T is substituted with Student and class Student must implement the compareTo() method. Hence method search(), in class SortedArrayList does not need to know about the members in class Student.
So you would first create an instance of SortedArrayList like this:
SortedArrayList<Student> theList = new SortedArrayList<>();
Then you can call the search() method like this:
Student s = new Student(/* relevant parameter values */);
theList.search(s);
EDIT
I understand that you don't necessarily want to search for a Student, you may want to search for the Name of a student or a student's mobile phone number. In that case I believe you need a Comparator. Here is the code for class SortedArrayList with the addition of a Comparator
import java.util.Comparator;
import java.util.Objects;
public class SortedArrayList<T extends Comparable<T>> implements SortedListInterface<T> {
private static final int SIZE = 10;
private Comparator<? super T> comparator;
private T[] list;
private int count;
#SuppressWarnings("unchecked")
public SortedArrayList(Comparator<? super T> c) {
comparator = c;
list = (T[]) 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
*/
}
#Override
public boolean add(T element) {
Objects.requireNonNull(element, "Cannot add null 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;
}
#Override
public T get(int index) {
checkIndex(index);
return list[index];
}
#Override
public boolean search(T element) {
if (comparator == null) {
return binarySearchComparable(element);
}
else {
return binarySearchComparator(element);
}
}
#Override
public T remove(int index) {
checkIndex(index);
T removed = list[index];
list[index] = null;
for (int i = index; i < count; i++) {
list[i] = list[i + 1];
}
count--;
list[count] = null;
return removed;
}
#Override
public void clear() {
for (int i = 0; i < count; i++) {
list[i] = null;
}
count = 0;
}
#Override
public int getLength() {
return count;
}
#Override
public boolean isEmpty() {
return count == 0;
}
#Override
public boolean isFull() {
return count == SIZE;
}
private boolean binarySearchComparable(T 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 {
found = true;
break;
}
}
return found;
}
private boolean binarySearchComparator(T key) {
int low = 0;
int high = count - 1;
while (low <= high) {
int mid = (low + high) >>> 1;
T midVal = list[mid];
int cmp = comparator.compare(midVal, key);
if (cmp < 0)
low = mid + 1;
else if (cmp > 0)
high = mid - 1;
else
return true; // key found
}
return false; // key not found.
}
private void checkIndex(int index) {
if (index < 0) {
throw new IllegalArgumentException("Negative index.");
}
if (index >= count) {
throw new IllegalArgumentException(String.format("Supplied index %d is not less than %d", index, count));
}
}
}
Here is an example Comparator for the Name of a Student
import java.util.Comparator;
public class NameComparator implements Comparator<Student> {
#Override
public int compare(Student student1, Student student2) {
int result;
if (student1 == null) {
if (student2 == null) {
result = 0;
}
else {
result = -1;
}
}
else {
if (student2 == null) {
result = 1;
}
else {
result = student1.getName().getFullName().compareTo(student2.getName().getFullName());
}
}
return result;
}
}
So in order to search the list according to any combination of Student attributes, simply implement an appropriate Comparator and pass it to the SortedArrayList class.
EDIT 2
Following your comments from November 17, 2019.
Below is code for a "name and mobile" Comparator. As I wrote in my previous Edit, you need to write an appropriate Comparator for a given combination of Student attributes.
import java.util.Comparator;
/**
* Compares {#code Student} name and mobile phone number.
*/
public class NameAndMobileComparator implements Comparator<Student> {
#Override
public int compare(Student student1, Student student2) {
int result;
if (student1 == null) {
if (student2 == null) {
result = 0;
}
else {
result = -1;
}
}
else {
if (student2 == null) {
result = 1;
}
else {
result = student1.getName().getFullName().compareTo(student2.getName().getFullName());
if (result == 0) {
result = student1.getMobileNo().compareTo(student2.getMobileNo());
}
}
}
return result;
}
}
I need help with my project for data structure course. I am suppose to read 10 employees data stored in a text file called Employee.txt and read them into an array then pass that array into the heapSort method and print the sorted employees into an output file called SortedEmployee.txt. For some reason my program is not working. Can anyone help please?
Class Employee
import java.util.ArrayList;
public class Employee
{
public String empId , empName , empDept , empPos;
public double empSalary;
public int empServ;
Employee()
{
empId = ("");
empName = ("");
empDept = ("");
empPos = ("");
empSalary = 0.0;
empServ = 0;
}
Employee(String id ,String name, double salary, String dept , String pos, int serv)
{
empId = id;
empName = name;
empDept = dept;
empPos = pos;
empSalary = salary;
empServ = serv;
}
public void setId(String id)
{
empId = id;
}
public void setName(String name)
{
empName = name;
}
public void setDept(String dept)
{
empDept = dept;
}
public void setPos(String pos)
{
empPos = pos;
}
public void setSalary(double salary)
{
empSalary = salary;
}
public void setServ(int serv)
{
empServ = serv;
}
public String getId()
{
return empId;
}
public String getName()
{
return empName;
}
public String getDept()
{
return empDept;
}
public String getPos()
{
return empPos;
}
public double getSalary()
{
return empSalary;
}
public int getServ()
{
return empServ;
}
public String toString()
{
String str = "Employee Name : " + empName + "\nEmployee ID : " + empId +
"\nEmployee Deaprtment : " + empDept + "\nEmployee Position : "
+ empPos + "\nEmployee Salary : " + empSalary
+ "\nEmployee Years Served : " + empServ;
return str;
}
public int compareTo(Employee emp)
{
int id = empId.compareToIgnoreCase(emp.empId);
if (id != 0)
return id;
return 0;
}
}
Class HeapSort
import java.util.Scanner;
import java.util.ArrayList;
import java.io.*;
class zNode
{
private int iData;
public zNode(int key)
{
iData = key;
}
public int getKey()
{
return iData;
}
public void setKey(int k)
{
iData = k;
}
}
class HeapSort
{
private int [] currArray;
private int maxSize;
private int currentSize;
private int currIndex;
HeapSort(int mx)
{
maxSize = mx;
currentSize = 0;
currArray = new int[maxSize];
}
//buildheap
public boolean buildHeap(int [] currArray)
{
int key = currIndex;
if(currentSize==maxSize)
return false;
int newNode = key;
currArray[currentSize] = newNode;
siftUp(currArray , currentSize++);
return true;
}
//siftup
public void siftUp(int [] currArray , int currIndex)
{
int parent = (currIndex-1) / 2;
int bottom = currArray[currIndex];
while( currIndex > 0 && currArray[parent] < bottom )
{
currArray[currIndex] = currArray[parent];
currIndex = parent;
parent = (parent-1) / 2;
}
currArray[currIndex] = bottom;
}
//siftdown
public void siftDown(int [] currArray , int currIndex)
{
int largerChild;
int top = currArray[currIndex];
while(currIndex < currentSize/2)
{
int leftChild = 2*currIndex+1;
int rightChild = leftChild+1;
if(rightChild < currentSize && currArray[leftChild] < currArray[rightChild] )
largerChild = rightChild;
else
largerChild = leftChild;
if( top >= currArray[largerChild] )
break;
currArray[currIndex] = currArray[largerChild];
currIndex = largerChild;
}
currArray[currIndex] = top;
}
//remove max element
public int removeMaxElement(int [] currArray)
{
int root = currArray[0];
currArray[0] = currArray[--currentSize];
siftDown(currArray , 0);
return root;
}
//heapsort
private void _sortHeapArray(int [] currArray)
{
while(currentSize != 0)
{
removeMaxElement(currArray);
}
}
public void sortHeapArray()
{
_sortHeapArray(currArray);
}
//hepify
private int[] heapify(int[] currArray)
{
int start = (currentSize) / 2;
while (start >= 0)
{
siftDown(currArray, start);
start--;
}
return currArray;
}
//swap
private int[] swap(int[] currArray, int index1, int index2)
{
int swap = currArray[index1];
currArray[index1] = currArray[index2];
currArray[index2] = swap;
return currArray;
}
//heapsort
public int[] _heapSort(int[] currArray)
{
heapify(currArray);
int end = currentSize-1;
while (end > 0)
{
currArray = swap(currArray,0, end);
end--;
siftDown(currArray, end);
}
return currArray;
}
public void heapSort()
{
_heapSort(currArray);
}
//main method
public static void main (String [] args) throws IOException
{
HeapSort mySort = new HeapSort(10);
Employee [] myArray = new Employee[10];
String firstFile = ("Employee.txt");
FileReader file = new FileReader(firstFile);
BufferedReader br = new BufferedReader(file);
String secondFile = ("SortedEmployee.txt");
PrintWriter outputFile = new PrintWriter(secondFile);
String[] currArray = new String[10];
String lineContent;
while ((lineContent = br.readLine()) != null)
{
for (int i = 0; i < currArray.length; i++)
{
lineContent = br.readLine();
currArray[i] = String.valueOf(lineContent);
mySort.heapSort();
outputFile.println(mySort);
}
}
outputFile.close();
System.out.print("Done");
}
}
I know that the problem is in the main method in the while loop but I just don't know how to solve it.
Employee.txt:
086244
Sally L. Smith
100000.00
Accounting
Manager
7
096586
Meredith T. Grey
150000.00
Physical Therapy
Doctor
9
875236
Christina R. Yang
190000.00
Cardiology
Resident
10
265893
George A. O'Malley
98000.00
Pediatrics
Attending
7
etc......
You have not implemented Comparable<Employee>. It should like this.
public class Employee implements Comparable<Employee>{
#Override
public int compareTo(Employee emp){
return this.empId.compareToIgnoreCase(emp.empId);
}
}
Simply use Arrays.sort() method to sort an array.
I want to accept input from user to populate an Array list of Person. for some reason. I can't get it to work. I can add an item into the list I have created below are my code for reference. in the SimplepersonDatabase class in switch function case 2:, I want to accept an an input of names, date of birth from the user and the program should automatically assign the position number starting from
e.g
001. Damien Kluk September, 12.09.1975
002. James Hunt January , 12.09.2000
I should be able to also delete a person and sort the list of Persons. here are what I have implemented so far.
public class Person { //Person.java
public String fn;
public String ln;
public Date dob;
public int id;
public Person() {
}
public Person(String fn, String ln, Date dob, int id) {
this.fn = fn;
this.ln = ln;
this.dob = dob;
this.id = id;
}
}
class List {//List.java
int MAX_LIST = 20;
Person[] persons;
int count;
public List() {
persons = new Person[MAX_LIST];
count=0;
}
public int numberOfPersons() {
return count;
}
public void add(Person person) {
checkUniqueId(person);
if (count >= persons.length) {
// Enlarge array
persons = Arrays.copyOf(persons, persons.length + 100);
}
persons[count] = person;
++count;
}
private void checkUniqueId(Person person) {
for (int i = 0; i < count; ++i) {
if (persons[i].id == person.id) {
throw new IllegalArgumentException("Already a person with id "
+ person.id);
}
}
}
public void remove(int personId) {
for (int i = 0; i < count; ++i) {
if (persons[i].id == personId) {
--count;
persons[i] = persons[count];
persons[count] = null;
return;
}
}
throw new IllegalArgumentException("No person known with id "
+ personId);
}
}
public class SimplePersonDataBase { //SimplePersonDataBase.java
private static List list;
private static int nextPersonId;
public static void main(String[] args) {
go();
}
public static void go() {
List link = new List();
TextIO.put("Welcome to the SimplePersonDatabase.\n");
TextIO.putln();
int option;
do{
TextIO.put("available options:\n1) list\n2) add\n3) remove\n4) sort\n5) find\n6) settings\n0) quit\nyour choice:");
option = TextIO.getInt();
switch(option){
case 1:
PersonFunctions.display();
break;
case 2: // Should accept inputs from a user and update the Persons database
TextIO.put("Firstname:");
String fn = TextIO.getlnWord();
TextIO.put("Lastname:");
String ln = TextIO.getlnWord();
Date date = DateFunctions.scanDate();
int pos = link.count;
Person item = new Person(fn,ln,date,pos);
add(item);
break;
case 3:
break;
case 4:
TextIO.putln("sort by:\n1) Firstname\n2) Birth\nall other values: lastname");
switch(TextIO.getInt()){
case 1:
break;
case 2:
break;
default :
break;
}
break;
case 5:
break;
case 6:
break;
case 0:
TextIO.put("Thank you for using the SimplePersonDatabase.");
break;
case 99:
break;
default :
TextIO.put("illegal option.");
break;
}
}while(option !=0);
}
public static boolean add(Person personadd) {
personadd.id = nextPersonId;
++nextPersonId;
list.add(personadd);
return true;
}
}
Your list is working well (I tried + or -)
import java.util.Arrays;
import java.util.Date;
class Person { // Person.java
public String fn;
public String ln;
public Date dob;
public int id;
public Person() {
}
public Person(String fn, String ln, Date dob, int id) {
this.fn = fn;
this.ln = ln;
this.dob = dob;
this.id = id;
}
}
the list
public class MyList {
int MAX_LIST = 20;
Person[] persons;
int count;
public MyList() {
persons = new Person[MAX_LIST];
count = 0;
}
public int numberOfPersons() {
return count;
}
public void add(Person person) {
checkUniqueId(person);
if (count >= persons.length) {
// Enlarge array
System.out.println("enlarging");
persons = Arrays.copyOf(persons, persons.length + 100);
}
persons[count] = person;
++count;
}
private void checkUniqueId(Person person) {
for (int i = 0; i < count; ++i) {
if (persons[i].id == person.id) {
throw new IllegalArgumentException("Already a person with id "
+ person.id);
}
}
}
public void remove(int personId) {
for (int i = 0; i < count; ++i) {
if (persons[i].id == personId) {
--count;
persons[i] = persons[count];
persons[count] = null;
return;
}
}
throw new IllegalArgumentException("No person known with id "
+ personId);
}
public Person get(int i) {
return persons[i];
}
public static void main(String[] args) {
MyList list = new MyList();
for (int i=0; i<1000; i++) {
list.add(new Person("fn"+i,"sn"+i,new Date(),i));
System.out.println(list.get(i) + " " + list.count);
}
}
}
the problem is in the "go" function, why you are using link and then you add in list?