Calling a parametrized method from LibraryCollection class to main Class - java

I am working on library management system project. Below is my LibraryCollection class. I would like to call my findMaterials() and checkOutMaterial() methods in the main class.
I have been trying to call as in below method but I don't get any value in the console.
public static LibraryCollection librarycollectObj1 = new LibraryCollection(10);
String search = null;
librarycollectObj1.findMaterial(search);
Thanks;
//LibraryCollection Class
public class LibraryCollection
{
private int collectionMaxSize;
private Material[] libraryCollection;
public LibraryCollection(int theMaxSize)
{
collectionMaxSize = theMaxSize;
libraryCollection = new Material[collectionMaxSize];
}
public LibraryCollection(int theCollectSize, Material[] theArray)
{
collectionMaxSize = theCollectSize;
libraryCollection = theArray;
}
//(1)----------------Find MATERIAL-----------------
public Material findMaterial(String theFindMaterial)
{
if(theFindMaterial == null)
{
return null;
}
for(int i = 0; i < libraryCollection.length; i++)
{
if(libraryCollection[i] !=null && theFindMaterial.equals(libraryCollection[i].getMaterialId()))
{
return libraryCollection[i];
}
}
return null;
}
//Material ID & checkedOutPtron ID;
public boolean checkOutMaterial(String matrlID, String patronId)
{
Material thisMaterial = findMaterial(matrlID);
if(thisMaterial == null)
{
System.out.println("The material doesn't exist" );
return false;
}
if(thisMaterial.checkedOut())
{
System.out.println("The material has been already checked out " );
return false;
}
thisMaterial.setCheckedOut(true);
thisMaterial.setPatronCheckout(Integer.parseInt(patronId));//Convert string value into int
return true;
}
//Material Class
public class Material
{
private static int materialID = 0 ;
private int mtrId;
private String title;
private boolean checkedOut ;
private int checkedOutPatron;
public Material()
{
mtrId = 0;
title = "";
checkedOut = false;
checkedOutPatron = 0;
}
public Material(int theId, String theTitle)
{
mtrId = theId;
title = theTitle;
}
//Getter Method
public String getMaterialId()
{
return mtrId + "";
}
public String getTitle()
{
return title;
}
public void setCheckedOut(boolean theCheckout)
{
checkedOut = theCheckout;
}
public void setPatronCheckout(int patronCheckout)
{
checkedOutPatron = patronCheckout;
}
public boolean checkedOut()
{
return checkedOut;
}
public int getCheckedOutPatron()
{
return checkedOutPatron;
}
//ToString Method
public String toString()
{
return " \nMaterial ID: " + mtrId + " \nMaterial Title: " + title + " \nChecked Out: "
+ checkedOut + " \nPatron check out: " + checkedOutPatron;
}
public static int getNextID()
{
materialID++;
return materialID;
}
}

When you run:
String search = null
librarycollectObj1.findMaterial(search);
You execute
public Material findMaterial(String theFindMaterial)
{
if(theFindMaterial == null)
{
return null;
}
Since theFindMaterial = search and search = null then you exit the method without doing anything because theFindMaterial = null.
You could do something like this:
public static LibraryCollection librarycollectObj1 = new LibraryCollection(10);
// Initialize the object somehow
for (int i = 0; i < 10; i++) {
librarycollectObj1.libraryCollection[i] = new Material(i, "");
}
String search = "1";
// Do some null checking in production code
System.out.println(librarycollectObj1.findMaterial(search). getMaterialId());

Related

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 :)

Call non static methods from another class in constructor

I have a car class and its constructor looks like this:
public Cars(String carID, String plateNum, String position, Attendant assignedTo, long currTime) {
this.carID = carID;
this.plateNum = plateNum;
this.position = position;
this.assignedTo = assignedTo;
this.currTime = currTime;
}
The constructor is initialized in another class(main) when I press for create car from the menu.
The parameters of the constructor are all created/initiated by methods in the car class. The system should be the one giving the information like(the ID, position and time in).
The problem is that the car object have not be initialized yet so I can't get the methods to work.
But I really need the cars object to contain its information(like car ID:CR1).
The information are all strings except for the time.
How can I do that?
PS: Im new to programming. At first I was using static but it turns out static methods cause another bigger trouble with my code.
I posted something where there was my static methods and everyone told me to remove the statics.
public void addCar() {
Cars car1 = new Cars(car1.getID(), car1.askCarID(), Cars.getPosition(), Attendant.askForAtt(), System.currentTimeMillis());
myGarage.add(car1);
if(!(car1.getAssignedTo()).equals(null)){
car1.getAssignedTo().setAssign(car1);
car1.getAssignedTo().setAvailable(false);
}
}
This is what is called when I want to create a new car.
I also put the whole car class in case you need it:
import java.util.ArrayList;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
import javax.swing.text.Position;
public class Cars {
private String carID;
private String plateNum;
private String position;
private Attendant assignedTo;
private long currTime;
static ArrayList<String> tempArray2 = new ArrayList<String>();
public Cars(String carID, String plateNum, String position, Attendant assignedTo, long currTime) {
this.carID = carID;
this.plateNum = plateNum;
this.position = position;
this.assignedTo = assignedTo;
this.currTime = currTime;
}
public void createCarsID() {
for (int x = 0; x < Garage.getCarsCapacity(); x++) {
String tempCarID = ("CR" + (x + 1));
tempArray2.add(tempCarID);
}
}
public String getID() {
createCarsID();
String tempID = null;
String tempPos = null;
for (int x = 0; x < Garage.getCarsCapacity(); x++) {
if (tempArray2.get(x) != null) {
tempID = tempArray2.get(x);
tempPos = tempArray2.get(x);
tempArray2.remove(tempArray2.get(x));
getPos(tempPos);
//tempArray2.get(x) = null;
break;
}
}
return tempID;
}
public static void getPos(String IdToPos) {
String strPos = IdToPos.substring(2);
int pos = Integer.parseInt(strPos);
position = "GR" + pos;
}
public String getPlateNum() {
return plateNum;
}
public static String getCarID() {
return carID;
}
public static String getPosition() {
return position;
}
public long getCurrTime() {
return currTime;
}
public Attendant getAssignedTo() {
return assignedTo;
}
public static String askCarID() {
boolean valid = false;
System.out.println("Please enter your car's plate number.");
Scanner scanCarID = new Scanner(System.in);
String scannedCarID = scanCarID.nextLine();
while (!valid) {
if (scannedCarID.matches("^[A-Za-z][A-Za-z] [0-9][0-9][0-9]$")) {
valid = true;
System.out.println(scannedCarID);
} else {
System.out.println("Please enter a valid plate number. Ex: AF 378");
askCarID();
}
}
return scannedCarID.toUpperCase();
}
public String convert(long miliSeconds) {
int hrs = (int) TimeUnit.MILLISECONDS.toHours(miliSeconds) % 24;
int min = (int) TimeUnit.MILLISECONDS.toMinutes(miliSeconds) % 60;
int sec = (int) TimeUnit.MILLISECONDS.toSeconds(miliSeconds) % 60;
return String.format("%02d:%02d:%02d", hrs, min, sec);
}
#Override
public String toString() {
return "Car:" + plateNum + " ID:" + carID + " Position:" + position + " Assigned to:" + assignedTo.getId()
+ "(" + assignedTo.getName() + ")" + " Parked at:" + convert(currTime);
}
}
I attach you a code that can help you:
first as all the parameters can be statics i move then to the constructor.
second i move the static method "createCarsID();" to a static init block, in order to avoid unwanted calls.
The example is fully functional.
package test;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
import javax.swing.text.Position;
public class Cars {
private String carID;
private String plateNum;
private String position;
private Attendant assignedTo;
private long currTime;
static ArrayList<String> tempArray2 = new ArrayList<String>();
static{
createCarsID();
}
public Cars() {
this.carID = Cars.getID();
this.plateNum = Cars.askCarID();
this.position = Cars.generatePosition();
this.assignedTo = Attendant.askForAtt();
this.currTime = System.currentTimeMillis();
}
public static void createCarsID() {
for (int x = 0; x < Garage.getCarsCapacity(); x++) {
String tempCarID = ("CR" + (x + 1));
tempArray2.add(tempCarID);
}
}
public static String getID() {
String tempID = null;
String tempPos = null;
for (int x = 0; x < Garage.getCarsCapacity(); x++) {
if (tempArray2.get(x) != null) {
tempID = tempArray2.get(x);
tempPos = tempArray2.get(x);
//tempArray2.remove(tempArray2.get(x));
//getPos(tempPos);
//tempArray2.get(x) = null;
break;
}
}
return tempID;
}
public static String generatePosition() {
String tempID = null;
String tempPos = null;
for (int x = 0; x < Garage.getCarsCapacity(); x++) {
if (tempArray2.get(x) != null) {
tempID = tempArray2.get(x);
tempPos = tempArray2.get(x);
tempArray2.remove(tempArray2.get(x));
return getPos(tempPos);
//tempArray2.get(x) = null;
}
}
return null;
}
public static String getPos(String IdToPos) {
String strPos = IdToPos.substring(2);
int pos = Integer.parseInt(strPos);
return "GR" + pos;
}
public String getPlateNum() {
return plateNum;
}
public String getCarID() {
return carID;
}
public String getPosition() {
return position;
}
public long getCurrTime() {
return currTime;
}
public Attendant getAssignedTo() {
return assignedTo;
}
public static String askCarID() {
boolean valid = false;
System.out.println("Please enter your car's plate number.");
Scanner scanCarID = new Scanner(System.in);
String scannedCarID = scanCarID.nextLine();
while (!valid) {
if (scannedCarID.matches("^[A-Za-z][A-Za-z] [0-9][0-9][0-9]$")) {
valid = true;
System.out.println(scannedCarID);
} else {
System.out.println("Please enter a valid plate number. Ex: AF 378");
askCarID();
}
}
return scannedCarID.toUpperCase();
}
public String convert(long miliSeconds) {
int hrs = (int) TimeUnit.MILLISECONDS.toHours(miliSeconds) % 24;
int min = (int) TimeUnit.MILLISECONDS.toMinutes(miliSeconds) % 60;
int sec = (int) TimeUnit.MILLISECONDS.toSeconds(miliSeconds) % 60;
return String.format("%02d:%02d:%02d", hrs, min, sec);
}
#Override
public String toString() {
return "Car:" + plateNum + " ID:" + carID + " Position:" + position + " Assigned to:" + assignedTo.getId()
+ "(" + assignedTo.getName() + ")" + " Parked at:" + convert(currTime);
}
}
Finally in order to call this function:
package test;
public class main {
public static void main(String [] args){
main test = new main();
test.addCar();
}
public void addCar() {
Cars car1 = new Cars();
Garage myGarage = new Garage();
myGarage.add(car1);
if(!(car1.getAssignedTo()).equals(null)){
car1.getAssignedTo().setAssign(car1);
car1.getAssignedTo().setAvailable(false);
}
}
}

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

I am getting "Exception in thread "main" java.lang.NullPointerException even though no values are set to null

public class ParkedCar {
private String make;
private String model;
private String color;
private String licenseNum;
public ParkedCar(String make, String model, String color, String licenseNum) {
this.make = make;
this.model = model;
this.color = color;
this.licenseNum = licenseNum;
}
public void setMake(String ma) {
make = ma;
}
public void setModel(String mo) {
model = mo;
}
public void setColor(String c) {
color = c;
}
public void setLicenseNum(String ln) {
licenseNum = ln;
}
public String getMake() {
return make;
}
public String getModel() {
return model;
}
public String getColor() {
return color;
}
public String getLicenseNum() {
return licenseNum;
}
}
public class ParkingMeter {
private ParkedCar parkedcar;
private int timePurchased;
private int timeParked;
public ParkingMeter(ParkedCar parkedcar, int timePurchased, int timeParked) {
this.parkedcar = parkedcar;
this.timePurchased = timePurchased;
this.timeParked = timeParked;
}
/*public ParkingMeter (ParkedCar parkedcar) {
this.parkedcar = null;
}*/
public void setTimePurchased(int timePurchased) {
this.timePurchased = timePurchased;
}
public int getTimePurchased() {
return timePurchased;
}
public void setTimeParked(int timeParked) {
this.timeParked = timeParked;
}
public int getTimeParked() {
return timeParked;
}
public int TimeExpired() {
if (timeParked > timePurchased)
return timeParked - timePurchased;
else
return 0;
}
public String toString() {
return "Make: " + parkedcar.getMake() + "\nModel: " + parkedcar.getModel() + "\nColor: " + parkedcar.getColor() + "\nLicense Number: " + parkedcar.getLicenseNum();
}
}
public class ParkingTicket {
private ParkingMeter parkingmeter;
public ParkingTicket(ParkingMeter parkingmeter) {
this.parkingmeter = parkingmeter;
}
public int TicketCost() {
if (parkingmeter.getTimeParked() > parkingmeter.getTimePurchased()) {
if (parkingmeter.getTimeParked() <= 60)
return 25;
else
return 25 + (10*(parkingmeter.TimeExpired())/60);
}
else
return 0;
}
}
public class PoliceOfficer {
private String OfficerName;
private int OfficerNum;
private ParkingMeter pm;
private ParkingTicket pt;
public PoliceOfficer(ParkingTicket pt, String OfficerName, int OfficerNum) {
this.OfficerName = OfficerName;
this.OfficerNum = OfficerNum;
}
public void setOfficerName(String OfficerName) {
this.OfficerName = OfficerName;
}
public void setOfficerNum(int OfficerNum) {
this.OfficerNum = OfficerNum;
}
public String getOfficerName() {
return OfficerName;
}
public int getOfficerNum() {
return OfficerNum;
}
public boolean isExpired() {
if (pm.getTimeParked() > pm.getTimePurchased())
return true;
else
return false;
}
public String toString() {
return "Officer Name: " + OfficerName + "\nOfficer Number: " + OfficerNum + "\n" + "\nFine: " + pt.TicketCost();
}
}
public class ParkingTicketDemo {
public static void main(String[] args) {
ParkedCar pc = new ParkedCar("Toyota", "Camry", "Blue", "BXZ 152");
System.out.println(pc);
ParkingMeter pm = new ParkingMeter(pc, 60, 120);
ParkingTicket pt = new ParkingTicket(pm);
PoliceOfficer po = new PoliceOfficer(pt, "Roger", 337);
System.out.println(po);
}
}
I have been trying to create a program to create and issue a parking ticket and have run into the problem where it compiles, but when it runs it gives out the error message Exception in thread "main" java.lang.NullPointerException. I am a fairly new programmer and this is the first time I have encountered the problem so I have yet fully understand it and cannot seem to fix it. i have tried reading other things online, but just do not understand I would love a simple explaination to my problem.
The NPE happens because of these two lines:
PoliceOfficer po = new PoliceOfficer(pt, "Roger", 337);
System.out.println(po);
In your constructor for PoliceOfficer, you don't do anything with the ParkingTicket instance pt.
public PoliceOfficer(ParkingTicket pt /* not set anywhere */, String OfficerName, int OfficerNum) {
this.OfficerName = OfficerName;
this.OfficerNum = OfficerNum;
}
The fields ParkingMeter pm and ParkingTicket pt remain null since you haven't initialized them.
Then you try to print the object: System.out.println(po); What this does is call toString() on po, it is equivalent to this:
System.out.println(po.toString());
Now because your toString()
public String toString() {
return "Officer Name: " + OfficerName + "\nOfficer Number: " + OfficerNum + "\n" + "\nFine: " + pt.TicketCost();
}
uses the pt, it creates a NullPointerException, since pt is null.
Since you are already passing a ParkingTicket instance into the constructor for PoliceOfficer, use that instance to assign its member variable pt.

Cannot run through loop to getAllPassengers

Hey i want to loop through planes to get all passengers and add them to a count to display all passengers for all planes. But im getting an error: Cannot iterate over an array or an instance.
Here is the method:
public int getAllPassengers()
{
int passengers = 0;
for(Plane plane : plane.getPassengerNumber())
{
passengers += plane.getPassengerNumber();
}
return passengers;
}
Plane
import java.util.LinkedList;
public class Plane implements Comparable
{
private String flightNumber;
public String airlineName;
private double fuelRemaining;
private int overdue;
private int passengerNumber;
private AIRPLANETYPE planeType;
private boolean isLanded = false;
public enum AIRPLANETYPE
{
AIRBUS("1"), CORPORATE("2"), PRIVATE("3");
private String planeName;
private AIRPLANETYPE(String planeName)
{
this.planeName = planeName;
}
public String getPlaneName()
{
return this.planeName;
}
}
public Plane(String flightNumber, String airlineName,
double fuelRemaining, int overdue, int passengerNumber,
AIRPLANETYPE planeType, boolean isLanded)
{
this.flightNumber = flightNumber;
this.airlineName = airlineName;
this.fuelRemaining = fuelRemaining;
this.passengerNumber = passengerNumber;
this.overdue = overdue;
this.planeType = planeType;
this.isLanded = isLanded;
}
public Plane()
{
}
public String getAirlineName() {
return airlineName;
}
public void setAirlineName(String airlineName) {
this.airlineName = airlineName;
}
public void setOverdue(int overdue) {
this.overdue = overdue;
}
public int getOverdue(){
return overdue;
}
public String getFlightNumber() {
return flightNumber;
}
public void setFlightNumber(String flightNumber) {
this.flightNumber = flightNumber;
}
public double getFuelRemaining() {
return fuelRemaining;
}
public void setFuelRemaining(double fuelRemaining) {
this.fuelRemaining = fuelRemaining;
}
public int getPassengerNumber() {
return passengerNumber;
}
public void setPassengerNumber(int passengerNumber) {
this.passengerNumber = passengerNumber;
}
public AIRPLANETYPE getPlaneType() {
return planeType;
}
public void setPlaneType(AIRPLANETYPE planeType) {
this.planeType = planeType;
}
public boolean isLanded() {
return isLanded;
}
public void setLanded(boolean isLanded) {
this.isLanded = isLanded;
}
public int compareTo(Object arg0) {
if((arg0 != null) && (arg0 instanceof Plane))
{
Plane p = (Plane) arg0;
return (int)Math.ceil(this.overdue - p.getOverdue());
}
return 0;
}
public String toString() {
return "Plane: flightNumber=" + flightNumber + "."
+ " airlineName=" + airlineName + "."
+ " fuelRemaining=" + fuelRemaining + " litres."
+ " overdue=" + overdue + " minutes."
+ " passengerNumber="+ passengerNumber + "."
+ " airplaneType=" + planeType +
"hasLanded=" + isLanded+ ".\n";
}
}
passengerNumber is an int. You need to iterate over an Iterable such as an ArrayList:
for (Plane plane: myPlaneList) {
passengers += plane.getPassengerNumber();
}
You are trying to iterate through Plane objects, but your collection is just an int. You'll need a collection of Plane objects
int passengers = 0;
for(Plane plane : myPlanes)
{
passengers += plane.getPassengerNumber();
}
You are trying to iterate over an int, you need to iterate over an java.util.Iterable
Your posted code does not contain the information needed to answer this question.
You are showing us the class Plane, but in order to have more than one plane, you probably have a List<Plane> or a Plane[] somewhere else in the code. Here's one example that would work:
public class Main {
List<Plane> allPlanes; // Load in the omitted code somewhere else
public int getAllPassengers()
{
int passengers = 0;
for(Plane plane : allPlanes) // note the change
{
passengers += plane.getPassengerNumber();
}
return passengers;
}
}

Categories

Resources