Accessing array list methods from another class - java

I have two classes I want to use together. An array list class and a Text User Interface class which will call methods from the array list class in order to complete tasks.
Whenever I try to call methods with parameters in my array list class from my TUI class, it gives me an error.
I'm trying to access an (add) method in my arrayList class from a TUI class, which will add a user to my arrayList. Can somebody please tell me how to fix this. The method that is returning the error is the 'public void addBorrower()' at the bottom of my TUI class.
My two classes are below in full.
This is my TUI class.
import java.util.ArrayList;
import java.util.Scanner;
public class BorrowerTUI
{
private BorrowerList borrowerList;
private Scanner myScanner;
public BorrowerTUI()
{
myScanner = new Scanner(System.in);
BorrowerList borrowerList = new BorrowerList();
}
public void menu()
{
int command = -1;
while (command != 0)
{
displayMenu();
command = getCommand();
execute (command);
}
}
private void displayMenu()
{
System.out.println( "Options are" );
System.out.println( "Enter 1" );
System.out.println( "Enter 2" );
System.out.println( "Enter 3" );
System.out.println( "Enter 4" );
}
private void execute( int command)
{
if ( command == 1)
addBorrower();
else
if ( command == 2 )
getNumberOfBorrowers();
else
if ( command == 3)
quitCommand();
else
if ( command == 4)
quitCommand();
else
if ( command == 5)
quitCommand();
else
System.out.println("Unknown Command");
}
private int getCommand()
{
System.out.print ("Enter command: ");
int command = myScanner.nextInt();
myScanner.nextLine();
return command;
}
public void getNumberOfBorrowers()
{
int command = myScanner.nextInt();
System.out.println("We have" + borrowerList.getNumberOfBorrowers() + "borrowers");
}
public void quitCommand()
{
int command = myScanner.nextInt();
System.out.println("Application Closing");
System.exit(0);
}
public void addBorrower()
{
borrowerList.addBorrower(Borrower borrower);
}
}
This is my array list class.
import java.util.ArrayList;
public class BorrowerList
{
private ArrayList<Borrower> borrowers;
public BorrowerList()
{
borrowers = new ArrayList<Borrower>();
}
public void addBorrower(Borrower borrower)
{
borrowers.add(borrower);
}
public int getNumberOfBorrowers()
{
return borrowers.size();
}
public boolean getBorrower(String libraryNumber)
{
for(Borrower borrower : borrowers)
borrower.getLibraryNumber();
return true;
}
public void getBorrower(int borrowerEntry)
{
if (borrowerEntry < 0)
{
System.out.println("Negative entry: " + borrowerEntry);
}
else if (borrowerEntry < getNumberOfBorrowers())
{
Borrower borrower = borrowers.get(borrowerEntry);
borrower.printBorrowerDetails();
}
else
{
System.out.println("No such entry: " + borrowerEntry);
}
}
public void getAllBorrowers()
{
for(Borrower borrower : borrowers)
{
borrower.printBorrowerDetails();
System.out.println();
}
}
public void removeBorrower(int borrowerEntry)
{
if(borrowerEntry < 0)
{
System.out.println("Negative entry :" + borrowerEntry);
}
else if(borrowerEntry < getNumberOfBorrowers())
{
borrowers.remove(borrowerEntry);
}
else
{
System.out.println("No such entry :" + borrowerEntry);
}
}
public boolean removeBorrower(String libraryNumber)
{
int index = 0;
for (Borrower borrower: borrowers)
{
if (libraryNumber.equals(borrower.getLibraryNumber()))
{
borrowers.remove(index);
return true;
}
index++;
}
return false;
}
public int search(String libraryNumber)
{
int index = 0;
for (Borrower borrower : borrowers)
{
if (libraryNumber.equals(borrower.getLibraryNumber()))
{
return index;
}
else
{
index++;
}
}
return -1;
}
}
Borrower Class:
public class Borrower
{
private String firstName;
private String lastName;
private String libraryNumber;
private int noOfBooks;
private Address address;
public Borrower(String fName, String lName, String lNumber,
String street, String town, String postcode)
{
firstName = fName;
lastName = lName;
libraryNumber = lNumber;
noOfBooks = 1;
address = new Address(street, town, postcode);
}
public Borrower(String fName, String lName, String lNumber, int numberOfBooks,
String street, String town, String postcode)
{
firstName = fName;
lastName = lName;
libraryNumber = lNumber;
noOfBooks = numberOfBooks;
address = new Address(street, town, postcode);
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public String getLibraryNumber()
{
return libraryNumber;
}
public int getNoOfBooks()
{
return noOfBooks;
}
public void printBorrowerDetails()
{
System.out.println( firstName + " " + lastName
+ "\n" + address.getFullAddress()
+ "\nLibrary Number: " + libraryNumber
+ "\nNumber of loans: " + noOfBooks);
}
public void borrowBook()
{
noOfBooks = noOfBooks + 1;
System.out.println("Books on loan: " + noOfBooks);
}
public void borrowBooks(int number)
{
noOfBooks = noOfBooks + number;
System.out.println("Books on loan: " + noOfBooks);
}
public void returnBook ()
{
noOfBooks = noOfBooks - 1 ;
System.out.println("Books on loan: " + noOfBooks);
}
public String getAddress()
{
return address.getFullAddress();
}
public void setAddress(String street, String town, String postcode)
{
address.setFullAddress(street, town, postcode);
}
public void printAddress()
{
address.printAddress();
}
} // end class

Related

how to get the date from a class to the test class

here is what i have to do, and what I have already did
After a quick meeting with the head of the company, you got the following information:
It is required to store the whole data in one collection
Each flight has a number, a pilot and a specific date. In addition, passengers could be added or removed within a given limit for the maximum number of passengers who could be in the same flight. Furthermore, there are other attributes (add at least 3 attributes from your choice). Of course, flight number is unique within the same date.
Each pilot has a unique ID, a name and other attributes (add at least 2 attributes from your choice).
Each passenger has a unique passport number, a name and other attributes (add at least 2 attributes from your choice but one of them should be common with pilots).
Moreover, you have been informed that the following operations happen frequently:
Offering a new flight
Adding a passenger to a specified flight
Removing a passenger from a specified flight  Retrieving the average number of passengers per flight of a specified date
Displaying all available flights in a format similar to the following: date1: flightNo1 flightNo2 flightNo3 … date2: flightNo1 flightNo2 flightNo3 … … where dates and flights are sorted in ascending order
Saving all the data into a text file
this is what did
I am starting the test class and when I started I for some reason couldn't get the date so I tried a shitty way and I don't think I am right
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
public class Testclass {
public static void main(String[] args) {
Date date1 = new Date("11/12/2020");
Flights a = new Flight(1, date1, 50, 5, "saudi air", "complimentary");
}
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class Flight {
final List<Passenger> passengers = new ArrayList<>();
int number;
Pilot pilot;
Date date;
int maxPassengers;
int minPassengers;
String airline;
String food;
public Flight() {
}
public Flight(int number, Date date, int maxPassengers, int minPassengers, String airline, String food) {
this.number = number;
this.date = date;
this.maxPassengers = maxPassengers;
this.minPassengers = minPassengers;
this.airline = airline;
this.food = food;
}
public List<Passenger> getPassengers() {
return passengers;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public Pilot getPilot() {
return pilot;
}
public void setPilot(Pilot pilot) {
if (!pilotExistance(pilot)) {
this.pilot = pilot;
System.out.println("Pilot has been added.");
}
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public int getMaxPassengers() {
return maxPassengers;
}
public void setMaxPassengers(int maxPassengers) {
this.maxPassengers = maxPassengers;
}
public int getMinPassengers() {
return minPassengers;
}
public void setMinPassengers(int minPassengers) {
this.minPassengers = minPassengers;
}
public String getAirline() {
return airline;
}
public void setAirline(String airline) {
this.airline = airline;
}
public String getFood() {
return food;
}
public void setFood(String food) {
this.food = food;
}
public boolean pilotExistance(Pilot newPilot) {
boolean pilotExist = false;
for (Flight flight : Airport.flights) {
if (flight.getPilot() != null && flight.getPilot().getId().equals(newPilot.getId())) {
pilotExist = true;
System.out.println("Pilot id: " + newPilot.getId() + " pilots in plane of flight number: " + flight.getNumber());
break;
}
}
return pilotExist;
}
public boolean passengerExistance(Passenger newPassenger) {
boolean passengerExist = false;
for (Flight flight : Airport.flights) {
final List<Passenger> passengers = flight.getPassengers();
for (Passenger passenger : passengers) {
if (passenger.passportNumber.equals(newPassenger.passportNumber)) {
passengerExist = true;
System.out.println("Passenger with passport number: " + newPassenger.getPassportNumber() + " are on the flight with the flgit number: " + flight.getNumber());
break;
}
}
if (passengerExist) {
break;
}
}
return passengerExist;
}
public void addPassenger(Passenger passenger) {
if (passengers.size() < maxPassengers) {
if (!passengerExistance(passenger)) {
passengers.add(passenger);
System.out.println(" Included.");
}
} else {
System.out.println("The Max number of passengers has already been reached.");
}
}
public void removePassenger(Passenger passenger) {
if (passengers.size() > minPassengers) {
if (passengerExistance(passenger)) {
passengers.remove(passenger);
System.out.println("Passnger has been taken out of flight.");
} else {
System.out.println("Passnger with passport number: " + passenger.getPassportNumber() + " doesn't exist.");
}
} else {
System.out.println("The lowest amount of passengers have been reached.");
}
}
public void passengersInformation() {
if (passengers.isEmpty()) {
System.out.println("There are no passengers.");
} else {
for (Passenger passenger : passengers) {
System.out.println(passenger.toString());
}
}
}
#Override
public String toString() {
return "Number: " + number + ", Pilot: " + pilot != null ? pilot.toString() : "No pilot yet" + ", Date: " + date + ", airline: " + airline + ", food: " + food + ", Number of passengers: " + passengers.size();
}
}
public class Passenger {
String passportNumber;
String name;
String bloodtype;
String agecatagory;
public Passenger() {
}
public Passenger(String id, String name, String bloodtype, String agecatagory) {
this.passportNumber = id;
this.name = name;
this.bloodtype = bloodtype;
this.agecatagory = agecatagory;
}
public String getPassportNumber() {
return passportNumber;
}
public void setPassportNumber(String passportNumber) {
this.passportNumber = passportNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBloodtype() {
return bloodtype;
}
public void setBloodtype(String bloodtype) {
this.bloodtype = bloodtype;
}
public String getAgecatagory() {
return agecatagory;
}
public void setAgecatagory(String agecatagory) {
this.agecatagory = agecatagory;
}
#Override
public String toString() {
return "Passport Number: " + passportNumber + ", Name: " + name + ", Bloodtype: " + bloodtype + ", Age catagory: " + agecatagory;
}
}
public class Pilot {
String id;
String name;
String experiancelevel;
String pilotcatagory;
public Pilot() {
}
public Pilot(String id, String name, String experiancelevel, String pilotcatagory) {
this.id = id;
this.name = name;
this.experiancelevel = experiancelevel;
this.pilotcatagory = pilotcatagory;
}
public String getId() {
return id;
}
//This function to get pilot id
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getExperiancelevel() {
return experiancelevel;
}
public void setExperiancelevel(String experiancelevel) {
this.experiancelevel = experiancelevel;
}
public String getPilotcatagory() {
return pilotcatagory;
}
public void setPilotcatagory(String pilotcatagory) {
this.pilotcatagory = pilotcatagory;
}
#Override
public String toString() {
return "Id: " + id + ", Name: " + name + ", Experiance level: " + experiancelevel + ", Pilot catagory: " + pilotcatagory;
}
}
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
public class Airport {
public static final List<Flight> flights = new ArrayList<>();
public Airport() {
}
public List<Flight> getFlights() {
return flights;
}
public boolean flightExistance(Flight newFlight) {
boolean flightExist = false;
if (!flights.isEmpty()) {
for (Flight flight : flights) {
if (flight.date.equals(newFlight.date) && flight.number == newFlight.number) {
flightExist = true;
break;
}
}
}
return flightExist;
}
public void addFlight(Flight flight) {
if (!flightExistance(flight)) {
flights.add(flight);
System.out.println("Flight Included.");
} else {
System.out.println("Number of flight: " + flight.getNumber() + " already in place.");
}
}
public void averageNumberOfPassengersPerFlight(Date date) {
int passengersCount = 0;
int flightsCount = 0;
double average = 0.0;
for (Flight flight : flights) {
if (flight.getDate().equals(date)) {
flightsCount++;
passengersCount += flight.getPassengers().size();
}
}
System.out.println("Total number of passengers in the flight: " + passengersCount);
if (passengersCount > 0 && flightsCount > 0) {
average = passengersCount / flightsCount;
System.out.println("Average number of passengers per flight for the specific date(" + date + "): " + average);
} else {
System.out.println("Average number of passengers per flight for the specific date(" + date + "): " + 0.0);
}
}
public void display() {
final List<Date> dates = new ArrayList<>();
for (Flight flight : flights) {
if (!dates.contains(flight.getDate())) {
dates.add(flight.getDate());
}
}
Collections.sort(dates);
for (Date date : dates) {
System.out.print(date + ": ");
final List<Integer> numbers = new ArrayList<>();
for (Flight flight : flights) {
if (flight.getDate().equals(date)) {
numbers.add(flight.getNumber());
}
}
Collections.sort(numbers);
for (int number : numbers) {
System.out.print("flightNo." + number + " ");
}
System.out.println("---------");
}
}
public void saveInTextFile(String filePath) {
try {
final FileWriter writer = new FileWriter(filePath);
for (Flight flight : flights) {
writer.write(flight.toString());
writer.write("\n");
writer.write("---------");
}
writer.close();
System.out.println("Saved successfully");
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
#Override
public String toString() {
return "Number of flights: " + flights.size();
}
}
i'm here to learn but i had a time limit so with the case of using Local time, I don't want to use code that I still don't understand yet so I just continued with what I did, it kinda sucked how I had to make a new object for each time but it's wasn't too bad and I finished the main method.
here it is(of course this isn't the last version as i added many more variables and commands but i just wanted to give you the final draft before i finished it completely.
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
public class MainClass {
public static void main(String[] args) {
// public Flight(int number, Date date, int maxPassengers, int minPassengers, String airline, String food) {
Date d = new Date("11/12/2020");
Pilot h = new Pilot("qw2563", "zaid", "epxerianced", "main pilot");
Pilot h1 = new Pilot("qw2563", "zaid", "epxerianced", "main pilot");
Pilot h2 = new Pilot("qw2563", "zaid", "epxerianced", "main pilot");
Flight f = new Flight(1, d, 50, 5, "saudi air", "complimentary",h);
Passenger one = new Passenger("23546785", "ahmad", "B+", "adult");
Airport hq = new Airport();
hq.addFlight(f);
f.addPassenger(one);
f.addPassenger(one);
}
}

I don't know how to do an array to store for each semester the details. I am supposed to create a subclass of the class Student

The question wants me to do:
An array of Finance called financeRecord to store the details
of the payments for each semester.
This is my code
package lab5;
class Student_U extends Student {
public String student_name;
private String studentID;
public int student_age;
private byte currentSemester;
private byte TotalFinanceRecord;
private String cohort;
public Student_U() {
student_name = " ";
studentID = " ";
student_age = 0;
currentSemester = 1;
TotalFinanceRecord = 0;
cohort = " ";
}
public Student_U(String student_name, String studentID, int student_age,
String course, String year,
String section, String subject, String student_name2,
String studentID2, int student_age2,
byte currentSemester, byte totalFinanceRecord, String cohort) {
super(student_name, studentID, student_age, course, year,
section, subject);
student_name = student_name2;
studentID = studentID2;
student_age = student_age2;
this.currentSemester = currentSemester;
TotalFinanceRecord = totalFinanceRecord;
this.cohort = cohort;
}
public String getStudent_name() {
return student_name;
}
public void setStudent_name(String student_name) {
this.student_name = student_name;
}
public String getStudentID() {
return studentID;
}
public void setStudentID(String studentID) {
this.studentID = studentID;
}
public int getStudent_age() {
return student_age;
}
public void setStudent_age(int student_age) {
this.student_age = student_age;
}
public byte getCurrentSemester() {
return currentSemester;
}
public void setCurrentSemester(byte currentSemester) {
this.currentSemester = currentSemester;
}
public byte getTotalFinanceRecord() {
return TotalFinanceRecord;
}
public void setTotalFinanceRecord(byte totalFinanceRecord) {
TotalFinanceRecord = totalFinanceRecord;
}
public String getCohort() {
return cohort;
}
public void setCohort(String cohort) {
this.cohort = cohort;
}
public void initStudent() {
}
public void print() {
System.out.print("Student name: " + student_name + " ");
System.out.print("\nMatric No: " + studentID + " ");
System.out.print("\nAge: " + student_age + " ");
System.out.print("\nCurrent Semester: " + currentSemester + " ");
System.out.print("\nCohort: " + cohort + " ");
System.out.println();
}
}
Please help me fix my code I would appreciate it so much.
This is my lab assignment which needs to be submitted by tomorrow.
You could try this, but it's also better to review standard java concepts (arrays, classes, etc). After, just adapt your code as suitable.
public class Finance extends Student
{
public static void main(String args[])
{
Finance f1 = new Finance("Student_1");
System.out.println(f1);
f1.setPayment(1, 10);
System.out.println(f1);
f1.setPayment(2, 10.77);
System.out.println(f1);
Student s2 = new Student("Student 2");
Finance f2 = new Finance(s2);
f2.setPayment(2, 88.77);
System.out.println(f2);
}
Double finaceRecord[] = new Double[3];
private void initPayment()
{
for(int i=0;i<finaceRecord.length;i++)
{
finaceRecord[i]=0.0;
}
}
public Finance(Student s)
{
super(s.name);
initPayment();
}
public Finance(String name)
{
super(name);
initPayment();
}
//store first or second
public void setPayment(int i, double d)
{
if(d<=0) return;
if(i==1)
{
finaceRecord[i] = d;
}
else
{
finaceRecord[2] = d;
}
finaceRecord[0] = finaceRecord[2] + finaceRecord[1];
}
public String toString()
{
return "name="+super.name+", Total Paid="+finaceRecord[0]+","
+ " Sem1="+finaceRecord[1]+", Sem2="+finaceRecord[2];
}
}
...
public class Student
{
String name;
int Semester;
Student(String name)
{
this.name = name;
this.Semester = 1;
}
}
Ouptut
name=Student_1, Total Paid=0.0, Sem1=0.0, Sem2=0.0
name=Student_1, Total Paid=10.0, Sem1=10.0, Sem2=0.0
name=Student_1, Total Paid=20.77, Sem1=10.0, Sem2=10.77
name=Student 2, Total Paid=88.77, Sem1=0.0, Sem2=88.77
from what I understand you are supposed to create an array of Finance type
Finance []financeRecord = new Finance[totalFinanceRecord];
and then you can access the values of Finance class
financeRecord[indexNumber].methodName();

Pass a created object from one class to another and add to ArrayList?

I´ve created a function where you add a result for a participant in a event.
Now I want to pass the created object to an addResult-method in my participant class and thereafter add it to an ArrayList in the same class, but I can´t really figure out how to do this. I´ve been stuck on this for a while, and could need some help how to approach this further.
This is what I´ve coded so far for this:
public Participant getParticipant() {
int startNumber = readInt();
boolean participantFound = false;
for (int i = 0; i < allParticipants.size(); i++) {
if (allParticipants.get(i).getStartNumber() == (startNumber)) {
participantFound = true;
return allParticipants.get(i);
}
}
if (!participantFound) {
System.out.println("No participant with number " + startNumber + " exists. " + "\n");
runCommandLoop();
}
return null;
}
public Event getEvent() {
String eventName = norm();
boolean eventFound = false;
for (int a = 0; a < allEvents.size(); a++) {
if (allEvents.get(a).getEventName().equalsIgnoreCase(eventName)) {
eventFound = true;
return allEvents.get(a);
}
}
if (!eventFound) {
System.out.println("No event called " + eventName + " found! ");
runCommandLoop();
}
else {
System.out.println("To many attempts! ");
runCommandLoop();
}
return null;
}
public void addResult() {
System.out.println("Number: ");
Participant p = getParticipant();
if (p == null) {
}
System.out.println("Event: ");
Event e = getEvent();
if (e == null) {
}
System.out.println("Type in the result for " + p.getFirstName() + " " + p.getLastName() + " in "
+ e.getEventName() + ": ");
double result = readDouble();
while (result < 0) {
System.out.println("Must be greater than or equal to zero! Try again: ");
result = readDouble();
}
Result r = new Result();
**// THIS IS WHERE I´M STUCK RIGHT NOW**
r.addResult();
System.out.println("The result " + result + " is now registred");
}
And this is my Participant class:
import java.util.ArrayList;
public class Participant {
public ArrayList<Result> allResults = new ArrayList<>();
private String firstName;
private String lastName;
private String team;
private int startNumber;
public Participant(String firstName, String lastName, String team, int startNumber) {
this.firstName = firstName;
this.lastName = lastName;
this.team = team;
this.startNumber = startNumber;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getTeam() {
return team;
}
public void setTeam(String team) {
this.team = team;
}
public int getStartNumber() {
return startNumber;
}
public void setStartNumber(int startNumber) {
this.startNumber = startNumber;
}
public void addResult(Result r) {
allResults.add(r);
}
public String toString() {
return "\n" + "Name: " + firstName + "\n" + "Last name: " + lastName + "\n" + "Team: " + team + "\n"
+ "Start number: " + startNumber;
}
}
And my Result class:
public class Result {
private double result;
public Result(double result) {
this.result = result;
}
public double getResult() {
return result;
}
public void setResult(double result) {
this.result = result;
}
public void printResult() {
System.out.println(result);
}
}
What you are doing is
Result r = new Result();
**// THIS IS WHERE I´M STUCK RIGHT NOW**
r.addResult();
but I do not see addResult() Method in Result Class. What you need to do is
p.addResult(r); // p is your Participant
hope this helps

arraylist sorting alphabetically

i have gotten the assignment to make a phonebook with 3 classes, the driver that runs it all, phonebook,and a person class.
the problem i was having was i couldn't make the Collection.sort(telbook.personen)
get to work as how i have it in my code, what i want to know is what do i have to add or replace to make it sort the arraylist
as i have it now as a function that i can run by myself to check if it did sort, but that didn't work.
driver class:
/**
* Created by ricardo on 2/26/2015.
*/
import java.util.*;
public class Driver {
Phonebook telbook = new Phonebook();
Scanner scan = new Scanner(System.in);
String newLine = System.getProperty("line.separator");
String[] Commands = {"/addperson - add a person to my beautiful program",
"/listpersons - for full list of persons",
"/removeperson - to remove a made person",
"/sortlist - sorts the phonebook (alphabetically)"};
private boolean running;
private boolean startmessage = false;
public static void main(String[] args) {
Driver n = new Driver();
n.run();
}
public void run() {
running = true;
startProgram();
}
public void startProgram() {
while (running) {
if (!startmessage) {
System.out.println("Type /commands for all available commands.");
startmessage = true;
}
String entered = scan.nextLine();
if (entered.equals("/commands")) {
for (int i = 0; i < Commands.length; i++)
System.out.println(Commands[i]);
} else if (entered.equals("/addperson")) {
addPerson();
} else if (entered.equals("/listpersons")) {
listPersons();
} else if (entered.equals("/removeperson")) {
removePerson();
} else if (entered.equals("/sortlist")) {
sortList();
} else {
System.out.println("Command not available. Type /commands for full list of commands");
}
}
}
public void addPerson() {
System.out.println("Fill in your name");
String addname = scan.nextLine();
System.out.println("Fill in your adress");
String addadress = scan.nextLine();
System.out.println("Fill in your city");
String addcity = scan.nextLine();
System.out.println("Fill in your phonenumber");
String addphonenumber = scan.nextLine();
System.out.println("Your data has been saved!");
Person addperson = new Person(addname, addadress, addphonenumber, addcity);
telbook.personen.add(addperson);
//sortList();
}
public void removePerson() {
listPersons();
System.out.println("Insert the ID of the person to be removed");
int ID = Integer.parseInt(scan.nextLine());
if (ID > telbook.personen.size()) {
System.out.println("There is no person with this ID, please select a different ID");
removePerson();
} else {
telbook.personen.remove(ID);
System.out.println("Person with the ID of " + ID + " has been removed");
}
}
public void listPersons() {
int ID = 0;
if (telbook.personen.isEmpty()) {
System.out.println("There is no person added yet. type /addperson to do so");
}
for (int i = 0; i < telbook.personen.size(); i++) {
System.out.println("ID:" + ID + newLine + " name: " + telbook.personen.get(i).name + newLine + " adress: " + telbook.personen.get(i).adress + newLine + " city: " + telbook.personen.get(i).city + newLine + " phonenumber: " + telbook.personen.get(i).phonenumber);
ID++;
}
}
public void sortList() {
Collections.sort(telbook.personen);
}
}
phonebook class:
/**
* Created by ricardo on 2/26/2015.
*/
import java.util.*;
public class Phonebook {
ArrayList<Person> personen = new ArrayList<Person>();
}
person class:
/**
* Created by ricardo on 2/26/2015.
*/
public class Person {
String name, adress, phonenumber, city;
public Person(String name, String adress, String phonenumber, String city) {
this.name = name;
this.adress = adress;
this.city = city;
this.phonenumber = phonenumber;
}
// public String getCity() { return city; }
//
// public void setCity(String city) {
// this.city = city;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getAdress() {
// return adress;
// }
//
// public void setAdress(String adress) {
// this.adress = adress;
// }
//
// public String getPhonenumber() {
// return phonenumber;
// }
//
// public void setPhonenumber(String phonenumber) {
// this.phonenumber = phonenumber;
// }
}
You should make your Person class implement the Comparable interface, and specifically tell how one should compare two Person objects.
An alternative is to implement a Comparator, and use Collections.sort(arrayList,comparator)

adding objects to an ArrayList using an abstract class

I'm trying to add animal objects to a pet ArrayList using an accept method but I am getting an error saying cannot find symbol. I've been over it a bunch of times and am just not seeing it.
Thanks for your help.
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Scanner;
public class Shelter2 implements AnimalShelter {
private ArrayList<Animal2> pet;
private int Id;
Scanner in = new Scanner(System.in);
public Shelter2() {
pet = new ArrayList<Animal2>();
SimpleDateFormat DateFormat = new SimpleDateFormat("MM-dd-yyyy");
Date now = new Date();
String today = DateFormat.format(now).toString();
// pet.add(new Cat("Snow White", "Domestic Short Hair", "White", "F",
// "01-01-2012", null));
// pet.add(new Dog("Buster", "Beagle", "Brown/White/Black", "male",
// "12-25-2011", null));
// pet.add(new Reptile("Jack", "Lizard", "01-31-2012", null));
}
public String allAnimals() {
String str = "";
for (Animal2 p : pet) {
str = str + p + "\n\n";
}
return str;
}
public String available() {
String str = "";
for (int i = 0; i < pet.size(); i++) {
Animal2 p = pet.get(i);
if (p.getAdoptedDate() == null) {
str = str + p + "\n\n";
}
}
return str;
}
public String adopted() {
String str = "";
for (int i = 0; i < pet.size(); i++) {
Animal2 p = pet.get(i);
if (p.getAdoptedDate() != null) {
str = str + p + "\n\n";
}
}
return str;
}
public boolean adopt(int id) {
return true;
}
public boolean accept(Animal2 pet) {
String type = null;
System.out.println("What type of animal? (Cat, Dog, Reptile)");
type = in.next();
if (type == "Cat") {
System.out.println("Enter name: ");
String name = in.next();
System.out.println("Enter description: ");
String desc = in.next();
System.out.println("Enter color: ");
String color = in.next();
System.out.println("Enter sex: ");
String sex = in.next();
pet.add(new Cat(name, desc, color, sex, null, null));
}
return true;
}
}
public abstract class Animal2 {
public String name;
public String arrivalDate;
public String adoptedDate;
public String getName() {
return new String(name);
}
public void setName(String name) {
this.name = name;
}
public String getArrivalDate() {
return new String(arrivalDate);
}
public void setArrivalDate(String arrivalDate) {
this.arrivalDate = arrivalDate;
}
public String getAdoptedDate() {
return adoptedDate;
}
public void setAdoptedDate(String adoptedDate) {
this.adoptedDate = adoptedDate;
}
#Override
public String toString() {
return "\nName: " + name + "\nArrival Date: " + arrivalDate
+ "\nAdopted Date: " + adoptedDate;
}
}
class Cat extends Animal2 {
String desc;
String color;
String sex;
char s;
Cat(String name, String desc, String color, String sex, String arrivalDate,
String adoptedDate) {
super.setName(name);
super.setArrivalDate(arrivalDate);
super.setAdoptedDate(adoptedDate);
setDesc(desc);
setColor(color);
setSex(sex);
char s = ' ';
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
s = sex.toLowerCase().charAt(0);
if ((s == 'f') || (s == 'm')) {
this.sex = sex;
} else {
System.err.println("Illegal value for Cat sex field - " + sex);
}
}
#Override
public String toString() {
if (s == 'f') {
sex = "Female";
} else if (s == 'm') {
sex = "Male";
} else {
sex = null;
}
return "\nCat: " + super.toString() + "\nDescription: " + desc
+ "\nColor: " + color + "\nSex: " + sex;
}
}
class Dog extends Animal2 {
String bred;
String color;
String sex;
char s;
Dog(String name, String bred, String color, String sex, String arrivalDate,
String adoptedDate) {
super.setName(name);
super.setArrivalDate(arrivalDate);
super.setAdoptedDate(adoptedDate);
setBred(bred);
setColor(color);
setSex(sex);
char s = ' ';
}
public String getBred() {
return bred;
}
public void setBred(String bred) {
this.bred = bred;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
s = sex.toLowerCase().charAt(0);
if ((s == 'f') || (s == 'm')) {
this.sex = sex;
} else {
System.err.println("Illegal value for Dog sex field - " + sex);
}
}
#Override
public String toString() {
if (s == 'f') {
sex = "Female";
} else if (s == 'm') {
sex = "Male";
} else {
sex = null;
}
return "Dog: " + super.toString() + "\nBred: " + bred + "\nColor: "
+ color + "\nSex: " + sex;
}
}
class Reptile extends Animal2 {
String type;
Reptile(String name, String type, String arrivalDate, String adoptedDate) {
super.setName(name);
super.setArrivalDate(arrivalDate);
super.setAdoptedDate(adoptedDate);
setType(type);
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
#Override
public String toString() {
return "Reptile: " + super.toString() + "\nType: " + type;
}
}
I'm going to go out on a limb here and say that this line is giving you the error:
pet.add(new Cat(name, desc, color, sex, null, null));
You're getting this error because pet, within the scope of your accept method, is an Animal2. If you want to reference the field named pet, try:
this.pet.add(new Cat(name, desc, color, sex, null, null));
Also, in your Dog and Cat classes, you are not setting s. You are creating a new variable s and setting it to ' ' (char s = ' ';). I'm not sure how that will affect your project, but you probably aren't intending to do it.

Categories

Resources