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?
Related
I have written a code in which I have made an interface and a class that implements that interface. Now when I run the code, i give my self 2 options i.e. 1 to Enter string and 2 to quit. Now when i run the code, if i select 1, it lets me put in string, but after this when i press 0, it gives me error: Exception in thread "main" java.lang. Can some body please help me figure out what I am missing here. Below is the code:
import java.util.ArrayList;
import java.util.List;
public interface ITimsSaveable {
List<String> write(); // this will save the data;
void read (List<String> savedValues); //this will print the data
}
import java.util.ArrayList;
import java.util.List;
public class TimsPlayers implements ITimsSaveable {
private String name;
private int hitPoints;
private int strength;
private String weapon;
public TimsPlayers(String name, int hitPoints, int strength) {
this.name = name;
this.hitPoints = hitPoints;
this.strength = strength;
this.weapon = "Sword";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getHitPoints() {
return hitPoints;
}
public void setHitPoints(int hitPoints) {
this.hitPoints = hitPoints;
}
public int getStrength() {
return strength;
}
public void setStrength(int strength) {
this.strength = strength;
}
public String getWeapon() {
return weapon;
}
public void setWeapon(String weapon) {
this.weapon = weapon;
}
//now go to generate > to string method
#Override
public String toString() {
return "TimsPlayers{" +
"name='" + name + '\'' +
", hitPoints=" + hitPoints +
", strength=" + strength +
", weapon='" + weapon + '\'' +
'}';
}
//now let us create stubs, i.e. the empty methods from interface
#Override
public List<String> write() {
List<String > values = new ArrayList<String >();
values.add(0,this.name);
values.add(1,""+this.hitPoints); //"" is quick trick to convert int to String
values.add(2,""+this.strength);
values.add(3,this.weapon);
return values;
}
#Override
public void read(List<String> savedValues) {
if ((savedValues != null) && (savedValues.size() > 0)) {
this.name = savedValues.get(0);
this.hitPoints = Integer.parseInt(savedValues.get(1));
this.strength = Integer.parseInt(savedValues.get(2));
this.weapon = savedValues.get(3);
}
// now let us go back to our main class
}
}
public class Main {
public static void main(String[] args) {
TimsPlayers tim = new TimsPlayers("Tim",10,15);
System.out.println(tim.toString());
saveObject(tim);
tim.setHitPoints(8);
System.out.println(tim);
tim.setWeapon("Stormbringer");
saveObject(tim);
loadObject(tim);
System.out.println(tim);
}
public static ArrayList<String> readValues() {
ArrayList<String> values = new ArrayList<String>();
Scanner scanner = new Scanner(System.in);
boolean quit = false;
int index = 0;
System.out.println("Choose\n" +
"1 to enter a string\n" +
"0 to quit");
while (!quit) {
System.out.print("Choose an option: ");
int choice = scanner.nextInt();
scanner.nextLine();
switch (choice) {
case 0:
quit = true;
break;
case 1:
System.out.print("Enter a string: ");
String stringInput = scanner.nextLine();
values.add(index, stringInput);
index++;
break;
}
}
return values;
}
public static void saveObject(ITimsSaveable objectToSave) { //ITims is the interface that is being implemented by the player
//class,so we can use ITims as object type
for (int i = 0; i < objectToSave.write().size(); i++) {
System.out.println("Saving " + objectToSave.write().get(i) + " to storage device");
}
}
public static void loadObject (ITimsSaveable objectToLoad) {
ArrayList<String > values = readValues();
objectToLoad.read(values);
}
}
Stacktrace:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 1 out of bounds for length 1
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
at java.base/java.util.Objects.checkIndex(Objects.java:373)
at java.base/java.util.ArrayList.get(ArrayList.java:427)
at org.mm.sandbox.so.TimsPlayers.read(TimsPlayers.java:77)
at org.mm.sandbox.so.Main.loadObject(Main.java:62)
at org.mm.sandbox.so.Main.main(Main.java:17)
This method
#Override
public void read(List<String> savedValues) {
if ((savedValues != null) && (savedValues.size() > 0)) {
this.name = savedValues.get(0);
this.hitPoints = Integer.parseInt(savedValues.get(1));
this.strength = Integer.parseInt(savedValues.get(2));
this.weapon = savedValues.get(3);
}
// now let us go back to our main class
}
expects the savedValues to be completely filled, i.e. having 4 elements - name, HP, strength and weapon. You do savedValues.size() > 0 but that doesn't mean you didn't just input one of the required and then stopped and it still tries to access an element which does not exist - this.hitPoints = Integer.parseInt(savedValues.get(1));
For some reason my getName() method and and addMemberList() is not working.
I have tried everything parsing and debugging with a friend but nothing seems to work.
main
public static void main(String[] args) throws FileNotFoundException {
initialUserGuide();
Scanner sc = new Scanner(new File("familytree.txt"));
Family fr = new Family(sc);
fr.displayAllMembersList();
processUserInput(fr);
}
static void initialUserGuide(){
System.out.println("The input file consists of names of all Humans");
System.out.println("Enter the Human name from below list, to display his/her maternal line, Paternal line and children");
}
static void processUserInput(Family fr)
{
Scanner input = new Scanner(System.in);
Person person;
System.out.println("newt Human ( enter told " + "quit)?");
String nextLine = input.nextLine();
while(nextLine.length() > 0){
person = fr.find(nextLine);
if(person == null)
System.out.println("NoMatch Occured");
else
{
displayMaternalLine(person);
displayPaternalLine(person);
displayChildren(person);
}
System.out.println("");
System.out.println("next Human (enter to quit)?");
nextLine = input.nextLine();
}
}
static void displayMaternalLine(Person mother)
{
System.out.println("Maternal Line");
int i = 0;
int count = 1;
while(mother != null)
{
for(i = 0;i < count; i++){
System.out.println("");
}
System.out.println(mother.getName());
mother = mother.getMother();
count++;
}
}
static void displayPaternalLine(Person father)
{
System.out.println("Paternal Line");
int i = 0;
int count = 1;
while(father != null)
{
for(i = 0;i < count; i++){
System.out.println("");
}
System.out.println(father.getName());
father = father.getMother();
count++;
}
}
static void displayChildren(Person person)
{
System.out.println("Children");
ArrayList ptr = person.getChildren();
if(ptr.size()==0)
{
System.out.println(" none");
}
for(int i = 0; i < ptr.size(); i++)
{
System.out.println("\t" + ptr.get(i).getName());
}
}
}
Family class
package assignment7;
import java.util.ArrayList;
import java.util.Scanner;
public class Family{
private ArrayList allMembersList;
public Family(Scanner sc){
allMembersList = new ArrayList();
addAllMembersList(sc);
makeParentChildRelation(sc);
}
Person find(String name)
{
for(int i = 0; i < allMembersList.size();i++)
{
if(allMembersList.get(i).getName().equalsIgnoreCase(name))
return (Person) allMembersList.get(i);
}
return null;
}
public void addAllMembersList(Scanner sc){
String line = sc.nextLine();
while(line.length() != 0)
{
Person person = new Person(line);
addMembersList.add(person);
line = sc.nextLine();
}
}
public void makeParentChildRelation(Scanner sc)
{
String nextLine;
String name,motherName,fatherName;
while(sc.hasNextLine())
{
name = sc.nextLine();
motherName = sc.nextLine();
fatherName = sc.nextLine();
Person personn = find(name);
if(!motherName.equals("unknown"))
{
Person mother = find(motherName);
personn.setMother(mother);
mother.addChildren(personn);
}
if(!fatherName.equals("unknown"))
{
Person father = find(fatherName);
personn.setFather(father);
father.addChildren(personn);
}
}
}
public void displayAllMembersList()
{
for(int i = 0; i < allMembersList.size(); i++)
{
Person person = (Person) allMembersList.get(i);
System.out.println(person.getName());
}
}
}
Person class
package assignment7;
import java.util.ArrayList;
public class Person {
private String name;
private Person mother;
private Person father;
private ArrayList children;
public Person(String name)
{
this.name = name;
children = new ArrayList();
}
public void setName(String name)
{
this.name = name;
}
public void setFather(Person Father){
this.father = Father;
}
public void setMother(Person Mother){
this.mother = Mother;
}
public void addChildren(Person Child)
{
children.add(Child);
}
public String getName()
{
return this.name;
}
public Person getFather()
{
return this.father;
}
public Person getMother()
{
return this.mother;
}
public ArrayList getChildren(){
return this.children;
}
}
familytree.txt
Maternal line:
Henry VIIII
Elizabeth of York
Paternal line:
Henry VIII
Henry VII
Children:
Mary I
Elizabeth I
Edward VI
Any help would be greatly appreciated here is the original problem.
Write a family database program. Create a class to represent a person and to store references to the person's mother, father, and any children the person has. Read a file of names to initialize the name and parent-child relationships of each Person. Store the overall list of Persons as an Arraylist. Write an overall main user interface that asks for a name and prints the maternal and paternal family line for that person.
The issue is you are using generic ArrayList to store List of Person objects. You should use List<Person>.
Also, addMembersList should be allMembersList (must be a typo).
Here is working code.
//main
import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
initialUserGuide();
Scanner sc = new Scanner(new File("familytree.txt"));
Family fr = new Family(sc);
fr.displayAllMembersList();
processUserInput(fr);
}
static void initialUserGuide() {
System.out.println("The input file consists of names of all Humans");
System.out.println("Enter the Human name from below list, to display his/her maternal line, Paternal line and children");
}
static void processUserInput(Family fr) {
Scanner input = new Scanner(System.in);
Person person;
System.out.println("newt Human ( enter told " + "quit)?");
String nextLine = input.nextLine();
while (nextLine.length() > 0) {
person = fr.find(nextLine);
if (person == null)
System.out.println("NoMatch Occured");
else {
displayMaternalLine(person);
displayPaternalLine(person);
displayChildren(person);
}
System.out.println("");
System.out.println("next Human (enter to quit)?");
nextLine = input.nextLine();
}
}
static void displayMaternalLine(Person mother) {
System.out.println("Maternal Line");
int i = 0;
int count = 1;
while (mother != null) {
for (i = 0; i < count; i++) {
System.out.println("");
}
System.out.println(mother.getName());
mother = mother.getMother();
count++;
}
}
static void displayPaternalLine(Person father) {
System.out.println("Paternal Line");
int i = 0;
int count = 1;
while (father != null) {
for (i = 0; i < count; i++) {
System.out.println("");
}
System.out.println(father.getName());
father = father.getMother();
count++;
}
}
static void displayChildren(Person person) {
System.out.println("Children");
List<Person> ptr = person.getChildren();
if (ptr.size() == 0) {
System.out.println(" none");
}
for (int i = 0; i < ptr.size(); i++) {
System.out.println("\t" + ptr.get(i).getName());
}
}
}
//Family
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Family {
private List<Person> allMembersList;
public Family(Scanner sc) {
allMembersList = new ArrayList<>();
addAllMembersList(sc);
makeParentChildRelation(sc);
}
Person find(String name) {
for (int i = 0; i < allMembersList.size(); i++) {
if (allMembersList.get(i).getName().equalsIgnoreCase(name))
return (Person) allMembersList.get(i);
}
return null;
}
public void addAllMembersList(Scanner sc) {
String line = sc.nextLine();
while (line.length() != 0) {
Person person = new Person(line);
allMembersList.add(person);
line = sc.nextLine();
}
}
public void makeParentChildRelation(Scanner sc) {
String nextLine;
String name, motherName, fatherName;
while (sc.hasNextLine()) {
name = sc.nextLine();
motherName = sc.nextLine();
fatherName = sc.nextLine();
Person personn = find(name);
if (!motherName.equals("unknown")) {
Person mother = find(motherName);
personn.setMother(mother);
mother.addChildren(personn);
}
if (!fatherName.equals("unknown")) {
Person father = find(fatherName);
personn.setFather(father);
father.addChildren(personn);
}
}
}
public void displayAllMembersList() {
for (int i = 0; i < allMembersList.size(); i++) {
Person person = (Person) allMembersList.get(i);
System.out.println(person.getName());
}
}
}
//Person
import java.util.ArrayList;
import java.util.List;
public class Person {
private String name;
private Person mother;
private Person father;
private List<Person> children;
public Person(String name) {
this.name = name;
children = new ArrayList<>();
}
public void setName(String name) {
this.name = name;
}
public void setFather(Person Father) {
this.father = Father;
}
public void setMother(Person Mother) {
this.mother = Mother;
}
public void addChildren(Person Child) {
children.add(Child);
}
public String getName() {
return this.name;
}
public Person getFather() {
return this.father;
}
public Person getMother() {
return this.mother;
}
public List<Person> getChildren() {
return this.children;
}
}
Ticket ticketObject = new Ticket(); //I create my object here
HashMap<Integer, Ticket> totalTickets = new HashMap<Integer, Ticket>(); //I create the hasmap
totalTickets.put(counter, ticketObject); // And after i have given values to my object via setters and getters I add i to has map
above let's say is my main class then, I re-run the main function by using:
main(args);
And when it tries to add a ticketObject to the hasmap with different values it doesn't. Is there any way to do that?
Each value object of the hash map will be mapped to an integer object. So, you can't aasign two different values to the same object.
You have to take care with boxed Integer because you will get the same object if you make "new Integer(1)" twice, for example, because the class has internal cache of integers. Check the method of Integer.valueof to understand better this behavior.
Check this article:
https://javapapers.com/java/java-integer-cache/
public class Ticket {
private String type; // "normal" "reduced"
private String kind; // "online" "printed"
private int duration;
private int trips;
private int serial;
public void constuct( ) {
type = "";
kind = "";
duration = 0;
trips = 0;
serial = 0;
}
public String getType() {
return type;
}
public String getKind() {
return kind;
}
public int getDuration() {
return duration;
}
public int getTrips() {
return trips;
}
public void setType(String newType) {
type = newType;
}
public void setKind(String newKind) {
kind = newKind;
}
public void setDuration(int newDuration) {
duration = newDuration;
}
public void setTrips(int newTrips) {
trips = newTrips;
}
public int getSerial() {
return serial;
}
public void setSerial(int serial) {
this.serial = serial;
}
}
here is my Ticket class
public class Main {
public static void main(String[] args) {
int menuChoice;
int counter = 0;
Ticket ticketObject = new Ticket();
SubTicket subTicketObject = new SubTicket();
Scanner input = new Scanner(System.in);
Menu menuObject = new Menu();
HashMap<Integer, Ticket> totalTickets = new HashMap<Integer, Ticket>();
ticketObject.constuct();
subTicketObject.constuctt();
menuObject.printMainMenu();
menuObject.printChoice();
menuChoice = input.nextInt();
switch (menuChoice) {
case 1:
menuObject.printChoiceType();
input.nextLine(); // throw away the /n
String tmp = input.nextLine();
if(tmp.equals("normal")) {
ticketObject.setType("normal");
menuObject.printChoiceTripsDur();
String tmp2 = input.nextLine();
if(tmp2.equals("trips")) {
menuObject.printTripsAmount();
int tripsAmount = input.nextInt();
if(tripsAmount!=1 || tripsAmount != 5 || tripsAmount!=11) {
menuObject.printError();
break;
}
ticketObject.setTrips(tripsAmount);
System.out.println(ticketObject.getTrips());
}else if(tmp2.equals("duration")){
menuObject.printDurationAmount();
int durationAmount = input.nextInt();
switch (durationAmount){
case 1:
counter++;
ticketObject.setDuration(90);
System.out.println("Your ticket serial is " + counter);
menuObject.printType();
int tmptype = input.nextInt();
if(tmptype == 1) {
subTicketObject.setType("online");
}else if(tmptype == 2){
subTicketObject.setType("printed");
}else {
menuObject.printError();
}
totalTickets.put(counter, ticketObject);
break;
case 2:
counter++;
ticketObject.setDuration(1440);
System.out.println("Your ticket serial is " + counter);
menuObject.printType();
int tmptype3 = input.nextInt();
if(tmptype3 == 1) {
subTicketObject.setType("online");
}else if(tmptype3 == 2){
subTicketObject.setType("printed");
}else {
menuObject.printError();
}
totalTickets.put(counter, ticketObject);
break;
case 3:
counter++;
ticketObject.setDuration(1080);
System.out.println("Your ticket serial is " + counter);
menuObject.printType();
int tmptype2 = input.nextInt();
if(tmptype2 == 1) {
subTicketObject.setType("online");
}else if(tmptype2 == 2){
subTicketObject.setType("printed");
}else {
menuObject.printError();
}
totalTickets.put(counter, ticketObject);
break;
case 4:
counter++;
subTicketObject.setDuration(43200);
menuObject.printAskUserFirstName();
input.nextLine(); // throw away the /n
String tmpfirstname = input.nextLine();
subTicketObject.setFirstname(tmpfirstname);
menuObject.printAskUserSecondName();
String tmpsecondname = input.nextLine();
subTicketObject.setFirstname(tmpsecondname);
menuObject.print30DurationPrice();
menuObject.printHowToPay();
int tmppay = input.nextInt();
if(tmppay == 1) {
menuObject.printInsertCash();
}else if(tmppay == 2) {
menuObject.printInsertCard();
}else {
menuObject.printError();
}
System.out.println("Your ticket serial is " + counter);
menuObject.printType();
int tmptype5 = input.nextInt();
if(tmptype5 == 1) {
subTicketObject.setType("online");
}else if(tmptype5 == 2){
subTicketObject.setType("printed");
}else {
menuObject.printError();
}
totalTickets.put(counter, subTicketObject);
break;
default:
menuObject.printError();
break;
}
}
}else if(tmp.equals("reduced")) {
ticketObject.setType("reduced");
// gotta ask for "stoixeia" here and save them somewhere
}else {
menuObject.printError();
}
}
System.out.println(totalTickets);
menuObject.printKeepRunning();
int tmprun = input.nextInt();
if (tmprun == 1) {
main(args);
}
}
}
here is my main
public class SubTicket extends Ticket{
private String firstname;
private String secondname;
public void constuctt( ) {
firstname = "";
secondname = "";
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getSecondname() {
return secondname;
}
public void setSecondname(String secondname) {
this.secondname = secondname;
}
}
and here is my SubTicket, the subclass
First of all the question is not clear. Please confirm if you are trying to add different counters as Key or for the same key you are trying to add ticketObject with different values.
If you are trying to map the different value to the same key, it will override the previous ticketObject as shown below.
import java.util.HashMap;
public class TestMap {
public static void main(String[] args) {
String[] counterArgs= {"1","2","3"};
Ticket ticketObject = (new TestMap()).new Ticket();
// I create my object here
HashMap<Integer, Ticket> totalTickets = new HashMap<Integer, Ticket>();
for (String counter : counterArgs) {
ticketObject.setCounter(Integer.valueOf(counter));
totalTickets.put(Integer.valueOf(counter), ticketObject);
}
totalTickets.entrySet().forEach(e->System.out.println(e.getKey()+"-"+e.getValue()));
}
class Ticket {
public int getCounter() {
return counter;
}
public void setCounter(int num) {
this.counter = num;
}
int counter;
#Override
public String toString(){
return ""+counter;
}
}
}
output:
1-3
2-3
3-3
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'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?