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

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);
}
}

Related

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();

I want to ask about exercise 11 (Level 2 Programming Exercises) in An Introduction to Object-Oriented Programming with Java (5th edition)

//My Extend Student class
public class ExtendStudent {
//data members
private String name;
private String email;
//constructor
public ExtendStudent(String StudentName, String StudentEmail){
name = StudentName;
email = StudentEmail;
}
//method
public String getName(){
return name;
}
public String getEmail(){
return email;
}
}
//My Extend Library Card class
public class ExtendLibraryCard {
//data members
private ExtendStudent owner;
private int numBorBooks;
private String expDate;
private int expDay;
private int expMonth;
private int expYear;
private boolean active;
private int thisYear;
private int thisMonth;
private int thisDay;
//constructor
public ExtendLibraryCard() {
numBorBooks = 0;
expDate = null;
expMonth = 0;
expYear = 0;
setActive(true);
}
//methods
//set the owner be the student
public void setOwner(ExtendStudent student) {
owner = student;
}
//get the name of the owner (which is the student)
public String getOwnerName() {
return owner.getName();
}
//get the email of the owner
public String getOwnerEmail(){
return owner.getEmail();
}
//number of books borrowed
public void totalBooksBorrowed(int totalBooks) {
numBorBooks = numBorBooks + totalBooks;
}
//get number of books borrowed
public int getNumBorBooks() {
return numBorBooks;
}
//print out
public String toStringExpDate() {
return "Expiration Date: " + expDay + "/" + expMonth + "/" + expYear;
}
//expiration date
public void setExpDate(int expDay, int expMonth, int expYear) {
this.expDay = expDay;
this.expMonth = expMonth;
this.expYear = expYear;
}
public int getExpMonth() {
return expMonth;
}
public void setExpMonth(int expMonth) {
this.expMonth = expMonth;
}
public int getExpYear() {
return expYear;
}
public void setExpYear(int expYear) {
this.expYear = expYear;
}
public int getExpDay() {
return expDay;
}
public void setExpDay(int expDay) {
this.expDay = expDay;
}
//set active
public void setActive(boolean state) {
active = state;
}
//getter and setter of the current time
public int getThisYear() {
return thisYear;
}
public void setThisYear(int thisYear) {
this.thisYear = thisYear;
}
public int getThisMonth() {
return thisMonth;
}
public void setThisMonth(int thisMonth) {
this.thisMonth = thisMonth;
}
public int getThisDay() {
return thisDay;
}
public void setThisDay(int thisDay) {
this.thisDay = thisDay;
}
public void testing(){
if(active = false)
System.out.println("Your card is out of date. Please buy a new one or you will not be allowed to enter the library!");
else
System.out.println(toString());
}
//print out every single info to the card
public String toString(){
return "Owner Name: " + getOwnerName() + "\n" +
"Owner Email: " +getOwnerEmail() + "\n" +
"Number of books borrowed: " + getNumBorBooks() + "\n" +
"Today: " + getThisDay() + "/" + getThisMonth() + "/" + getThisYear() + "\n" +
toStringExpDate();
}
}
//My Extend Librarian
public class ExtendLibrarian {
public static void main(String[] args) {
ExtendStudent student = new ExtendStudent("SKT Faker", "fakerskt#yahoo.com");
ExtendLibraryCard card = new ExtendLibraryCard();
card.setOwner(student);
card.getOwnerName();
card.totalBooksBorrowed(20);
card.setExpDate(20, 11, 2019);
card.setThisDay(10);
card.setThisMonth(11);
card.setThisYear(2019);
if (card.getThisYear() > card.getExpYear()) {
card.setActive(false);
} else if (card.getThisYear() == card.getExpYear()) {
if (card.getThisMonth() > card.getExpMonth()) {
card.setActive(false);
}
} else if (card.getThisYear() == card.getExpYear()) {
if (card.getThisMonth() == card.getExpMonth()) {
if (card.getThisDay() > card.getExpDay()) {
card.setActive(false);
}
}
}
else {
card.setActive(true);
}
card.testing();
}
}
So the thing is let just say my expiration day is Nov 20th 2019, and
if today is Nov 21st 2019, the code will print out "Your card is out of date", but then it's not. Can somebody help me please, thank you.
P/s: Sorry if my English is terrible
First of all in your ExtendLibraryCard Class change this line
if(active = false)
to
if (active == false)
Also in your main Librarian class change the conditions from else if to if
if (card.getThisYear() > card.getExpYear()) {
card.setActive(false);
}
if (card.getThisYear() == card.getExpYear()) {
if (card.getThisMonth() > card.getExpMonth()) {
card.setActive(false);
}
}
if (card.getThisYear() == card.getExpYear()) {
if (card.getThisMonth() == card.getExpMonth()) {
if (card.getThisDay() > card.getExpDay()) {
card.setActive(false);
}
}
} else
card.setActive(true);
card.testing();
}
Let me give you a dry run what's happening in your code:
When you have set thisYear= 2019 and ExpYear= 2019, your first else if statement is satisfied, since card.getThisYear() == card.getExpYear(), it doesn't matter even if both the month is same, greater or lesser(i.e it doesn't matter if, nested if is satisfied or not), because your getThisYear is equal to ExpThisYear and thus, 1st else if condition is satisfied, it won't check the final else if condition (which has your date checking nested if condition).
Thus setActive(false) isn't being executed.
Also since the else if condtion of this block
else if (card.getThisYear() == card.getExpYear()) {
if (card.getThisMonth() > card.getExpMonth()) {
card.setActive(false);
}
}
has been executed and it's returning true for the fist part year==year, even your else block won't be executed.
Thus it is necessary for you to change your condition to if statements because else if once condition has been met won't check other conditions unlike if.
Link : Read this for if vs else if condition vs else
Hope it helps :)

Polymorphism java loop error

I'm having a problem regarding a polymorphic invocation inside a loop.
I have an abstract class called Item that has two subclasses ClothingItem and SportItem and an abstract method called printBudgetGST(Items[] item) to return a string of an item with updated pricing which include tax.
Item Class :
public abstract class Item
{
private int code;
private double price;
private boolean isOnGST;
public Item()
{
}
public Item(int code,double price,boolean isOnGST)
{
this.code = code;
this.price = price;
this.isOnGST = isOnGST;
}
public void setGST(boolean isgst)
{
this.isOnGST = isgst;
}
public int getCode()
{
return code;
}
public boolean getIsOnGST()
{
return isOnGST;
}
public double getCurrentPrice()
{
return price;
}
public String toString() {
return "Item [code=" + code + ", price=" + price + ", isOnGST=" + isOnGST + "]";
}
public abstract String printBudgetGST(Item[] items);
}
ClothingItem class
public class ClothingItem extends Item
{
public ClothingItem(){
}
public ClothingItem(int code,double price,boolean isOnGST)
{
super(code,price,isOnGST);
}
#Override
public String printBudgetGST(Item[] item)
{
String stringitem ="";
for(int i=0;i<item.length;i++)
{
if(item[i].getIsOnGST()==true&&item[i].getCurrentPrice()<100.00)
{
double finalprice =(0.06*item[i].getCurrentPrice())+item[i].getCurrentPrice();
stringitem = stringitem + " " + "ClothingItem : " + item[i].getCode()+":"+"RM"+finalprice;
}
}
return stringitem;
}
}
SportsItem class:
public class SportsItem extends Item
{
public SportsItem(){
}
public SportsItem(int code,double price,boolean isOnGST)
{
super(code,price,isOnGST);
}
public String printBudgetGST(Item[] item)
{
String stringitem = "";
for(int i=0;i<item.length;i++)
{
if(item[i].getIsOnGST()==true &&item[i].getCurrentPrice()<150.00)
{
double finalprice =(0.06*item[i].getCurrentPrice())+item[i].getCurrentPrice();
stringitem = stringitem + "SportsItem : " + item[i].getCode()+":"+"RM"+finalprice;
}
}
return stringitem;
}
}
Test class :
public class Retail_Item
{
private Item[] itemList;
public Retail_Item()
{
itemList = new Item[10];
itemList[0] = new ClothingItem(10001,85,true);
itemList[1] = new ClothingItem(10002,150,false);
itemList[2] = new ClothingItem(10003,168,true);
itemList[3] = new ClothingItem(10004,43,true);
itemList[4] = new ClothingItem(10005,162,false);
itemList[5] = new SportsItem(10006,178,false);
itemList[6] = new SportsItem(10007,80,true);
itemList[7] = new SportsItem(10008,191,false);
itemList[8] = new SportsItem(10009,45,true);
itemList[9] = new SportsItem(10010,121,true);
}
public void printItem()
{
for(int i =0 ;i<itemList.length;i++)
{
if(itemList[i].getIsOnGST()==true && itemList[i].printBudgetGST(itemList).length()>0)
{
System.out.println(itemList[i].printBudgetGST(itemList));
}
}
}
}
public class TestRetailItem {
public static void main(String[] args)
{
Retail_Item ret = new Retail_Item();
ret.printItem();
}
}
OUTPUT :
The output should return a list of items which is on tax(GST) and with the updated pricing information like the example below
The problem is that you are passing to printBudgetGST the whole array of items and iterating over that array inside your implementations of printBudgetGST. Instead, you should remove that parameter and inside printBudgetGST you should simply call getCurrentPrice() and getCode() on this rather than on each item[i].
In addition, you are doing the check for maximum price (< 100 or < 150) inside the item subclasses but it's best to do this alongside the other checks in printItem. Because the max price depends on the subclass (SportsItem vs ClothinItem) I recommend you to create an abstract method boolean isOnBudget() in Item and implement accordingly in those two subclasses.
A fully fixed version of your code is
public abstract class Item {
private int code;
private double price;
private boolean isOnGST;
public Item()
{
}
public Item(int code,double price,boolean isOnGST)
{
this.code = code;
this.price = price;
this.isOnGST = isOnGST;
}
public void setGST(boolean isgst)
{
this.isOnGST = isgst;
}
public int getCode()
{
return code;
}
public boolean getIsOnGST()
{
return isOnGST;
}
public double getCurrentPrice()
{
return price;
}
public String toString() {
return "Item [code=" + code + ", price=" + price + ", isOnGST=" + isOnGST + "]";
}
public abstract String printBudgetGST();
public abstract boolean isOnBudget();
}
class ClothingItem extends Item {
public ClothingItem() {
}
public ClothingItem(int code, double price, boolean isOnGST) {
super(code, price, isOnGST);
}
#Override
public String printBudgetGST() {
String stringitem = "";
double finalprice = (0.06 * getCurrentPrice()) + getCurrentPrice();
stringitem = stringitem + " " + "ClothingItem : " + getCode() + ":" + "RM" + finalprice;
return stringitem;
}
#Override
public boolean isOnBudget() {
return getCurrentPrice() < 100.00;
}
}
class SportsItem extends Item {
public SportsItem() {
}
public SportsItem(int code, double price, boolean isOnGST) {
super(code, price, isOnGST);
}
public String printBudgetGST() {
String stringitem = "";
double finalprice = (0.06 * getCurrentPrice()) + getCurrentPrice();
stringitem = stringitem + "SportsItem : " + getCode() + ":" + "RM" + finalprice;
return stringitem;
}
#Override
public boolean isOnBudget() {
return getCurrentPrice() < 150.00;
}
}
class Retail_Item
{
private Item[] itemList;
public Retail_Item()
{
itemList = new Item[10];
itemList[0] = new ClothingItem(10001,85,true);
itemList[1] = new ClothingItem(10002,150,false);
itemList[2] = new ClothingItem(10003,168,true);
itemList[3] = new ClothingItem(10004,43,true);
itemList[4] = new ClothingItem(10005,162,false);
itemList[5] = new SportsItem(10006,178,false);
itemList[6] = new SportsItem(10007,80,true);
itemList[7] = new SportsItem(10008,191,false);
itemList[8] = new SportsItem(10009,45,true);
itemList[9] = new SportsItem(10010,121,true);
}
public void printItem() {
for(int i =0 ;i<itemList.length;i++) {
if(itemList[i].getIsOnGST()==true && itemList[i].printBudgetGST().length()>0 && itemList[i].isOnBudget())
{
System.out.println(itemList[i].printBudgetGST());
}
}
}
}
class TestRetailItem {
public static void main(String[] args) {
Retail_Item ret = new Retail_Item();
ret.printItem();
}
}

Accessing array list methods from another class

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

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)

Categories

Resources