Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I have looked on here and spent some time on this and now I have hit a brick wall.
I am wokring on the Parking Ticket simulator in Java.
I am not very good at Java, but seem to have most of it working.
The only problem is that I put in a demo/test file and it gives me the same answer all the time. Even with ridiculous values.
Can someone point me in the right direction on how to resolve this?
Thanks, All the code is below:
/**
* #(#)ParkedCar.java
*
* ParkedCar application
*
*
* #version 3.00 2014/2/9
*/
public class ParkedCar
{
//Define Variables
private String CarMake;
private String CarModel;
private String CarColour;
private String CarLicensePlate;
private static int NumberOfMinutesParked;
//Define Constructors
// NO ARGUMENT CONSTRUCTOR
// Set Vaules to Zero or null
public ParkedCar()
{
CarMake = " ";
CarModel = " ";
CarColour = " ";
CarLicensePlate = " ";
NumberOfMinutesParked = 0;
}
// CONSTRUCTOR WHICH ACCEPTS AN INPUT
public ParkedCar(String Make,String Model,String Colour,String Reg, int NoMinsPkd)
{
CarMake = Make;
CarModel = Model;
CarColour = Colour;
CarLicensePlate = Reg;
NumberOfMinutesParked = NoMinsPkd;
}
// Use the SET Method
// Set the variables - no needed
public void setMake(String Make)
{
CarMake = Make;
}
public void setModel(String Model)
{
CarModel = Model;
}
public void setColour(String Colour)
{
CarColour = Colour;
}
public void setReg(String Reg)
{
CarLicensePlate = Reg;
}
public void setNoMinsPkd(int NoMinsPkd)
{
NumberOfMinutesParked = NoMinsPkd;
}
// USE THE GET METHODS
// Get the Variables - used to read in values
public String getMake()
{
return CarMake;
}
public String getModel()
{
return CarModel;
}
public String getColour()
{
return CarColour;
}
public String getReg()
{
return CarLicensePlate;
}
public static int getNoMinsPkd()
{
return NumberOfMinutesParked;
}
// USE THE TO STRING METHODS
// Output to a Sting
public String toString()
{
String PkdCar = "Make: " + CarMake
+ "\nModel: " + CarModel
+ "\nColor: " + CarColour
+ "\nLicense Plate: " + CarLicensePlate;
return PkdCar;
}
}
Then
/**
* #(#)ParkingMeter.java
*
* ParkedCar application
*
*
* #version 4.00 2014/2/9
*/
public class ParkingMeter
{
//Define Variables
private static int MinsPurchsed;
//Define Constructors
// NO ARGUMENT CONSTRUCTOR
// Set Vaules to Zero or null
public ParkingMeter()
{
// MinsPurchsed = 0;
}
// CONSTRUCTOR WHICH ACCEPTS AN INPUT
public ParkingMeter(int Purchased)
{
MinsPurchsed = Purchased;
}
// Use the SET Method
// Set the variables - not needed
public void setPurchased(int Purchased)
{
MinsPurchsed = Purchased;
}
// USE THE GET METHODS
// Get the Variables
public static int getPurchased()
{
return MinsPurchsed;
}
// USE THE TO STRING METHODS
// Output to a Sting
public String toString()
{
String MeterString = "Minutes Purchased: " + MinsPurchsed;
return MeterString;
}
}
Then
/**
* #(#)GardaOfficer.java
*
* ParkedCar application
*
*
* #version 3.00 2014/2/9
* #version 4.50 2014/4/13
*/
public class GardaOfficer //extends ParkedCar
{
// Define all the variables
//==========================
private String Name;
private String BadgeNumber;
private double Ticket;
// Constructor to accept all the variables
//========================================
public GardaOfficer(String n, String num)
{
Name = n;
BadgeNumber = num;
}
// NO ARGUMENT CONSTRUCTOR
//========================
public GardaOfficer()
{
Name = "";
BadgeNumber = "";
}
// SET METHODS
//===============
public void setName(String n)
{
Name = n;
}
public void setBadgeNumber(String num)
{
BadgeNumber = num;
}
// GET METHODS
//===============
public String getName()
{
return Name;
}
public String getBadgeNumber()
{
return BadgeNumber;
}
// TO STRING METHOD
//=================
public String toString()
{
String GardaString = "Garda : " + this.Name
+ "\nBadge: " + BadgeNumber
+ "\nTicket: " + Ticket;
return GardaString;
}
public ParkingTicket search(ParkedCar car, ParkingMeter meter)
{
GardaOfficer Garda = new GardaOfficer(this.Name,this.BadgeNumber);
int time = ParkedCar.getNoMinsPkd() - ParkingMeter.getPurchased();
if(ParkedCar.getNoMinsPkd() > ParkingMeter.getPurchased())
{
if(time <= 60)
{
Ticket = 50;
}
else
{
Ticket = 50 + (10 * (time/60));
}
}
if(time <0)
return null;
return new ParkingTicket(car, Garda, getTicket(), time);
}
public double getTicket()
{
return Ticket;
}
public void setTicket(double ticket)
{
this.Ticket = Ticket;
}
}
Then
/**
* #(#)ParkingTicket.java
*
* ParkedCar application
*
*
* #version 4.00 2014/2/9
*/
public class ParkingTicket
{
//Define Variables
private ParkedCar Vehicle;
private GardaOfficer GuardString;
private double ParkingFine;
private int Minutes;
private double firstFine = 50;
private double moreFine = 50;
public ParkingTicket()
{
}
// CONSTRUCTOR WHICH ACCEPTS AN INPUT
public ParkingTicket(ParkedCar car, GardaOfficer Guard, double guyFine, int mins)
{
Vehicle = car;
GuardString = Guard;
ParkingFine = guyFine;
Minutes = mins;
}
// Use the SET Method
// Set the variables - not needed
// USE THE GET METHODS
// Get the Variables
public void getTotalFine()
{
int time = ParkedCar.getNoMinsPkd() - ParkingMeter.getPurchased();
if (time <= 60)
{
ParkingFine = firstFine;
}
else
{
ParkingFine = firstFine + moreFine * (time / 60);
}
}
public double getFirstFine()
{
return firstFine;
}
public double getMoreFine()
{
return moreFine;
}
public ParkedCar getVehicle()
{
return Vehicle;
}
public GardaOfficer getGuardString()
{
return GuardString;
}
public int getMinutes()
{
return Minutes;
}
public double getFine()
{
return ParkingFine;
}
// USE THE TO STRING METHODS
// Output to a Sting
public String toString()
{
String TicketString = "Fine : " + this.ParkingFine
+ "\nMinutes: " + Minutes
+ "\n" + Vehicle.toString()
+ "\n" + this.getGuardString().toString();
return TicketString;
}
}
Finally
//This is a demo file to show the program
public class DemoCar
{
public static void main(String[] args)
{
ParkedCar Test1 = new ParkedCar("BMW", "2014", "Yellow", "141D12345", 30);
ParkingMeter parking = new ParkingMeter(50);
GardaOfficer Murphy = new GardaOfficer("Guard Murphy", "10");
ParkingTicket ticket = Murphy.search(Test1, parking);
if (ticket != null)
{
System.out.println(ticket.toString());
}
else
{
System.out.println("No ticket issued!");
}
// A second car checked to see if it passes or not, it's over
ParkedCar Test2 = new ParkedCar("VW", "2001", "Green", "01D321", 225);
ParkingMeter parking2 = new ParkingMeter(200);
ParkingTicket ticket2 = Murphy.search(Test2, parking2);
if (ticket != null)
{
System.out.println(ticket.toString());
}
else
{
System.out.println("No ticket issued!");
}
}
}
You're printing ticket instead of ticket2 the second time around.
Also you should always make your variables lowercase.
Related
This question already has answers here:
Java Error: The constructor is undefined
(8 answers)
Closed 3 years ago.
I have created two classes, PassCar and Motor. My project requires that I create a Motor instance for each PassCar, but I am struggling to do so. When I try to create an instance of Motor in PassCar, it does not work.
I've attempted
Motor motor = new Motor();
and
private Motor motor = new Motor();
Below is my code for PassCar
The error states that the constructor Motor is undefined.
public class PassCar extends Vehicle{
private Motor motor = new Motor();// the error
private int numPass;
private boolean AC;
public PassCar(String make, String model, int year, double price, int numPass, boolean aC, Motor motor) {
super(make, model, year, price);
this.numPass = numPass;
AC = aC;
this.motor = motor;
}
public int getNumPass() {
return numPass;
}
public void setNumPass(int numPass) {
this.numPass = numPass;
}
public boolean isAC() {
return AC;
}
public void setAC(boolean aC) {
AC = aC;
}
public Motor getMotor() {
return motor;
}
public void setMotor(Motor motor) {
this.motor = motor;
}
public void description() {
System.out.print("In this application, a passenger car is an every day vehicle registered to an individual");
}
#Override
public String toString() {
String s = super.toString();
s += "PassCar numPass = " + numPass + ", AC = " + AC + ", motor = " + motor;
return s;
}
}
code for Motor class
public class Motor {
private String name;
private int cylinders;
private int bhp;
private double displacement;
public Motor(String name, int cylinders, int bhp, double displacement) {
super();
this.name = name;
this.cylinders = cylinders;
this.bhp = bhp;
this.displacement = displacement;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCylinders() {
return cylinders;
}
public void setCylinders(int cylinders) {
this.cylinders = cylinders;
}
public int getBhp() {
return bhp;
}
public void setBhp(int bhp) {
this.bhp = bhp;
}
public double getDisplacement() {
return displacement;
}
public void setDisplacement(double displacement) {
this.displacement = displacement;
}
#Override
public String toString() {
return "Motor name = " + name + ", cylinders = " + cylinders + ", bhp = " + bhp + ", displacement = " + displacement;
}
}
code to print information entered
public class VehicleTest {
public static void main(String[] args) {
PassCar p1 = new PassCar("Ford", "Mustang", 2016, 44500.0, 5, true, "EcoBoost", 6, 310, 2.3);
System.out.print(p1);
}
}
The issue is here
public Motor(String name, int cylinders, int bhp, double displacement) {
super();
this.name = name;
this.cylinders = cylinders;
this.bhp = bhp;
this.displacement = displacement;
}
You've created a constructor that takes some argument but you're trying to call the constructor with no arguments here
private Motor motor = new Motor(); //cant find constructor that takes no arguments
To fix the issue you have to declare a constructor with no arguments along with your other one.
public Motor(){
//code here
}
Try adding the following code in the Motor classs
public Motor(){
}
Add the empty parameter constructor to your Motor class. Like this;
public Motor() {
}
I'm made a program that creates an invoice but when it comes numbers in the thousands the output isn't neat and ruins everything. How do I fix this so the program's columns are more aligned with numbers like this? Here is the code I used to create the program. If anyone could help, it would be much appericated.
Here's the one with the main method...
public class InvoicePrinter
{
public static void main(String[] args)
{
Address samsAddress=new Address("Sam's Small Appliances", "100 Main
Street", "Anytown", "CA", "98765");
Invoice samsInvoice =new Invoice(samsAddress);
samsInvoice.add(new Product("Toaster", 29.95),3);
samsInvoice.add(new Product("Hair Dryer", 24.95),1);
samsInvoice.add(new Product("Car Vacuum",19.99),2);
samsInvoice.add(new Product("Nano Parts",100000),1);
samsInvoice.addSimple(new Product("Shipping",5.00));
System.out.println(samsInvoice.format());
}
}
These are the other programs needed for the program to work
import java.util.ArrayList;
public class Invoice
{
public Invoice(Address anAddress)
{
items=new ArrayList<LineItem>();
billingAddress=anAddress;
simpleItems= new ArrayList<SimpleLineItem>();
}
public void addSimple(Product aProduct)
{
SimpleLineItem anItem= new SimpleLineItem(aProduct);
simpleItems.add(anItem);
}
public void add(Product aProduct, int quantity)
{
LineItem anItem=new LineItem(aProduct,quantity);
items.add(anItem);
}
public String format()
{
String r=" I N V O I C E\n\n"+billingAddress.format()+String.format("\n\n%-30s%8s%5s%8s\n","Description", "Price","Qty","Total");
for(LineItem i:items)
{
r=r+i.format()+"\n";
}
for(SimpleLineItem j:simpleItems)
{
r=r+j.format() + "\n";
}
r = r + String.format("\nAMOUNT DUE: $%8.2f", getAmountDue());
return r;
}
public double getAmountDue()
{
double amountDue = 0;
for (LineItem i : items)
{
amountDue = amountDue + i.getTotalPrice();
}
for(SimpleLineItem j:simpleItems)
{
amountDue = amountDue + j.getPrice();
}
return amountDue;
}
private Address billingAddress;
private ArrayList<LineItem> items;
private ArrayList<SimpleLineItem> simpleItems;
}
Few more
public class LineItem
{
public LineItem(Product aProduct, int aQuantity)
{
theProduct = aProduct;
quantity = aQuantity;
}
public double getTotalPrice()
{
return theProduct.getPrice() *quantity;
}
public String format()
{
return String.format("%'-30s%'8.2f%'5d%'8.2f", theProduct.getDescription(),theProduct.getPrice(),quantity,getTotalPrice());
}
private int quantity;
private Product theProduct;
}
Another one
public class SimpleLineItem
{
public SimpleLineItem(Product aProduct)
{
theProduct=aProduct;
}
public double getPrice()
{
return theProduct.getPrice();
}
public String format()
{
return String.format("%-30s" +" " + "%8.2f",
theProduct.getDescription(), theProduct.getPrice());
}
private Product theProduct;
}
Two more
public class Product
{
public Product(String aDescription,double aPrice)
{
description = aDescription;
price = aPrice;
}
public String getDescription()
{
return description;
}
public double getPrice()
{
return price;
}
private String description;
private double price;
}
Last one
public class Address
{
public Address(String aName, String aStreet, String aCity, String
aState,String aZip)
{
name = aName;
street = aStreet;
city = aCity;
state = aState;
zip = aZip;
}
public String format()
{
return name + "\n" + street + "\n" + city + ", " + state + " " + zip;
}
private String name;
private String street;
private String city;
private String state;
private String zip;
}
Maybe you can take a look at the javadocs by Oracle on System.out.format and DecimalFormat class
Formatting Numeric Print Output
So basically this happens when you cannot decide the total length of your number column until you print out everything. For this you will need to set the number column's length to the lengthiest number or in your case price length and justify right all the numbers. So you'll need to add all the numbers to an array and loop through them to find the lengthiest number.
When I try to print out the data within departments, it prints only the memory of their address.
How can I print the departments and the data?
I want the College department to get all the parameters that are in the Lecturer department. That means that when I create a new College I want it to create a new Lecturer with all the parameters inside.
In College class, I added a method (NewLecturer) that adds an additional Lecturer. Is it written correctly?
public class main {
public static void main(String[] args) {
Lecturer[] L1 = new Lecturer[] { new Lecturer("Dani", 2, "Banana", 1001) };
College FirstCollege = new College("Hmpson", 2, L1);
for (int i = 0; i < L1.length; i++) {
System.out.print(L1[i]);
}
System.out.print(L1);
System.out.print(FirstCollege);
}
}
First class:
public class Lecturer {
public String nameOfLecturer = "";
public int numOfTimesPenFalls = 0;
public String favoriteIceCream = "";
public int numAuto = 1000;
//constructors, same name like class
public Lecturer(String name, int TimesPenFalls, String IceCream, int num) {
nameOfLecturer = name;
numOfTimesPenFalls = TimesPenFalls;
favoriteIceCream = IceCream;
numAuto = num;
int maxLecturer = 10;
}
//Copy constructor
public Lecturer(Lecturer other) {
nameOfLecturer = other.nameOfLecturer;
numOfTimesPenFalls = other.numOfTimesPenFalls;
favoriteIceCream = other.favoriteIceCream;
numAuto = other.numAuto;
}
}
Second class:
public class College {
public String CollegeName = "";
public int numOfLecturers = 0;
public Lecturer[] allLecturers;
// constructors, same name like class
public College(String name, int numLecturers, Lecturer[] dataBase) {
CollegeName = name;
numOfLecturers = numLecturers;
allLecturers = dataBase;
int maxLecturer = 10;
}
// getter, only private
public String getCollegeName() {
return CollegeName;
}
// setter, only private
public void setCollegeName(String newcollegeName) {
CollegeName = newcollegeName;
}
public boolean newLecturer(Lecturer addNewLecturer, int maxLecturer) {
if (numOfLecturers < maxLecturer || numOfLecturers == maxLecturer) {
numOfLecturers += 1;
return true;
} else {
System.out.print("Sorry, Max Lecturer!");
return false;
}
}
public void sortLecturer(Lecturer[] arrAllLecturers) {
int numOfTimesPenFalls = 0;
}
}
System.out.print(Object) will call the toString() method of the parameter Object.
The default toString method of Object gives you nothing interesting, so you will have to override toString to fit your needs, for example :
In class Lecturer :
#Override
public String toString() {
return "Lecturer [nameOfLecturer=" + nameOfLecturer + ", numOfTimesPenFalls=" + numOfTimesPenFalls
+ ", favoriteIceCream=" + favoriteIceCream + ", numAuto=" + numAuto + "]";
}
In class College :
#Override
public String toString() {
return "College [CollegeName=" + CollegeName + ", numOfLecturers=" + numOfLecturers + ", allLecturers="
+ Arrays.toString(allLecturers) + "]";
}
create setter / getter and toString method for your Lecturer and College classes.
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();
}
}
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.