I am writing a program to simulate a parking ticket system. In total I 4 distinct classes, these being ParkedCar, ParkingMeter, ParkingTicket and PoliceOfficer. In my PoliceOfficer class I have an if statement to determine if the police officer should issue a ticket for the parked car.
I have the following statement to do such: return new ParkingTicket(this,car,meter). I get an incompatible type error. If I need to post my code for my other classes, let me know.
Parking Ticket Class:
import java.text.DecimalFormat;
public class ParkingTicket {
private static int ticketCount;
private ParkedCar car;
private PoliceOfficer officer;
private ParkingMeter meter;
private double fine;
public final double BASE_FINE = 25.0;
public final double HOURLY_FINE = 10.0;
public ParkingTicket (ParkedCar aCar, PoliceOfficer anOfficer, ParkingMeter aMeter) {
this.car = aCar;
this.officer = anOfficer;
this.meter = aMeter;
calculateFine();
}
public void calculateFine() {
// Calculate fine & increment ticket count
++ticketCount;
int timeOver = (int)Math.ceil((car.getMinutesParked() - meter.getMinutesPurchased() / 60.0));
fine = BASE_FINE * HOURLY_FINE * (timeOver - 1);
}
public String toString() {
DecimalFormat newDecimal = new DecimalFormat("$###.00");
return "Ticket Number: " + ticketCount + "\n" +
car + "\n" + meter + "\n" + "Fine: " + newDecimal.format(fine) + "\n"
+ officer;
}
}
Police Officer Class:
public class PoliceOfficer {
// Declare data fields
private String name;
private String badgeNumber;
// Default constructor
public PoliceOfficer (String name, String badgeNumber) {
this.name = name;
this.badgeNumber = badgeNumber;
}
// Copy of PoliceOfficer
public PoliceOfficer (PoliceOfficer OfficerCopy) {
this.name = OfficerCopy.name;
this.badgeNumber = OfficerCopy.badgeNumber;
}
// Class to check a parked car and determine if the
// cars time has expired
public ParkingTicket check(ParkedCar car, ParkingMeter meter) {
if (car.getMinutesParked() > meter.getMinutesPurchased()) {
// Creating a new object of ParkingTicket object
return new ParkingTicket(this,car,meter);
} else {
return null;
}
}
// toString class
public String toString() {
return "Officer Name: " + name + "/n" + "Badge ID: " + badgeNumber;
}
}
You've just got your arguments reversed. The ParkingTicket constructor requires its arguments to be:
(ParkedCar, PoliceOfficer, ParkingMeter)
But you're passing
(PoliceOfficer, ParkedCar, ParkingMeter)
All you need to do is change the call to new ParkingTicket(car, this, meter).
You mention instantiating ParkingTicket in PoliceOfficer (so this is PoliceOfficer)
new ParkingTicket(this,car,meter)
I believe it should be
new ParkingTicket(car,this,meter)
Because the constructor signature is ParkingTicket(ParkedCar, PoliceOfficer, ParkingMeter)
Related
First, I think the title of this post could be better, so if you want to edit it feel free to do so (or let me know how you think I should edit it).
I am going over practice problems for Java interviews. I am not interviewing right now, but I think this is the best way for me to find all my weak spots with Java. And before you say it, yes, I am finding I am VERY weak in many areas of Java and that I will need to do lots or review before interviewing.
I have some questions about the following code:
public class VehicleApp {
public static void main(String[] args) {
Ford myFord = new Ford();
System.out.println(myFord.countWheels());
Kawasaki myKawasaki = new Kawasaki(1985, "Eliminator");
System.out.println(myKawasaki.countWheels());
}
}
class Vehicle {
protected String make;
protected int numWheels;
public Vehicle() { }
public String countWheels() {
return "The number of wheels this " + make + " has is " + numWheels + ".";
}
}
class Ford extends Vehicle {
public Ford() {
make = "Ford";
numWheels = 4;
}
}
class Kawasaki extends Vehicle {
private String model;
private int year;
public Kawasaki(int year, String model) {
make = "Kawasaki";
numWheels = 2;
this.model = model;
this.year = year;
}
public String countWheels() {
return "The number of wheels this " + year + " " + make + " " + model + " has is " + numWheels + ".";
}
}
First, I notice that there are no references to super() in the code. I thought that when you are dealing with super classes and subclasses, it was required that the subclass constructor include a reference to the super class constructor in the form of super(); (and including parameters if the super class constructor has them). Yet this code seems to work without them. Am I wrong about this requirement? Am I missing something else in this picture?
Second, the Kawasaki class doesn't include the decoration #Override for the countWheels() method. Since this method has the same name (albeit different parameters) as the super class' countWheels() method, wouldn't it be required to have an #Override decoration? Or is that only if the parameters are the same type and same order?
Thanks!
If you do not explicitly call super() in your derived class, the Java compiler will automatically generate a call to super() for you. But this, of course, only works if the base class constructor takes no arguments. This can be demonstrated by adding a System.out.println("Constructor called."); statement to your otherwise empty Vehicle constructor.
The #Override decorator, as you have found out but have not convinced yourself of, is optional. But it is considered a "best practice" to use this when overriding a method for catching errors if you change the method signature.
The one, hopefully constructive, comment I would make is that since a Vehicle must have attributes make and numWheels, I personally would require that these be specified in the Vehicle constructor. Now there is no possibility of having a derived class with these attributes undefined.
public class VehicleApp {
public static void main(String[] args) {
Ford myFord = new Ford();
System.out.println(myFord.countWheels());
Kawasaki myKawasaki = new Kawasaki(1985, "Eliminator");
System.out.println(myKawasaki.countWheels());
}
}
class Vehicle {
protected String make;
protected int numWheels;
public Vehicle(String make, int numWheels) {
this.make = make;
this.numWheels = numWheels;
}
public String countWheels() {
return "The number of wheels this " + make + " has is " + numWheels + ".";
}
}
class Ford extends Vehicle {
public Ford() {
super("Ford", 4);
}
}
class Kawasaki extends Vehicle {
private String model;
private int year;
public Kawasaki(int year, String model) {
super("Kawasaki", 2);
this.model = model;
this.year = year;
}
#Override
public String countWheels() {
return "The number of wheels this " + year + " " + make + " " + model + " has is " + numWheels + ".";
}
}
I am having a problem when trying to print my ticket(child class) which is all my superclass variables are null or zero not initialized.
this is my superclass:-
public class movie {
protected int movieID;
protected String movieTitle;
movie(){};
movie(int movieID , String movieTitle ){
this.movieID = movieID;
this.movieTitle = movieTitle;
}
}
this is my childclass
public class ticket extends movie{
private int Number_of_ticket;
private int show_number ;
ticket(int Number_of_ticket , int show_number){
this.Number_of_ticket = Number_of_ticket;
this.show_number = show_number;
}
public void print_the_tacket(){
System.out.println("movie id is " + super.movieID);
System.out.println("movie name is " + super.movieTitle);
System.out.println("number of the ticket is " + Number_of_ticket);
System.out.println("show number is " + show_number);
}
}
the main
public class Main {
public static void main(String[] args) {
movie MyMovie = new movie(1234, "spiderman");
ticket myticket = new ticket(34 , 334);
myticket.print_the_tacket();
}
}
my output is
movie id is 0
movie name is null
number of the ticket is 34
show number is 334
I expect when I print my ticket the movie information why I am getting null values What is wrong here? thank you in advance.
When you reference super in the child class, it not bound to the Movie object you created in the main(). That is why you are getting a null value. Look here when I debug the code.
If you want to access the Movie object you created in main(), you can pass it and that will work.
To explain..
Note 1: There are 2 constructors created here. One is movie() without arguments, the other is with 2 arguments. What you extend and call is #1 not #2
public class movie {
protected int movieID;
protected String movieTitle;
movie() { //#1 - no args, so movieID=null, movieTitle=null
//you can debug by adding this line.
this.movieID = 1;
this.movieTitle = "I should not be printing this";
}
movie(int movieID , String movieTitle ){ //#2 - has args.
this.movieID = movieID;
this.movieTitle = movieTitle;
}
}
Note 2: Your problem is in ticket, when you do not write super(..) with args you are passing nothing, hence it is calling movie() without parameters. So if you are calling movie(), you get non declared variables. If you see sample above for debug you should see 1 and "I should not print this" instead to explain the scenario.
public class ticket extends movie{
private int Number_of_ticket;
private int show_number ;
ticket(int Number_of_ticket , int show_number){
//Not visible, but actually triggers super() and calling movie #1, not super(arg1, args2)
//super(1,"movie")
this.Number_of_ticket = Number_of_ticket;
this.show_number = show_number;
}
}
Note 3: You are making 2 different objects, object #1 is movie, and object #2 is ticket. To me it seems you only want 1 object which is ticket that extends movie. What happens here is that the codes are 2 different/seperated objects and they are not tied together.
public class Main {
public static void main(String[] args) {
movie MyMovie = new movie(1234, "spiderman"); //#Object 1
ticket myticket = new ticket(34 , 334); //#Object 2
myticket.print_the_tacket();
}
}
Approach: You may want the codes to be the following way where you create movie and ticket together in ticket call. This means when you create ticket your movie must be created. In a nutshell no movie created, no tickets to issue.
public class Movie { //Class name should always be captialized
protected int movieID; //you can declare final
protected String movieTitle;
Movie(int movieID , String movieTitle ){ //Only this
this.movieID = movieID;
this.movieTitle = movieTitle;
}
}
public class Ticket extends Movie { //Captialize class
private int Number_of_ticket; //should avoid _ and use Snakecase
private int show_number ;
Ticket(int Number_of_ticket , int show_number, int movieID, String movieTitle){
super(movieId, movieTitle); //always and must create movie object
this.Number_of_ticket = Number_of_ticket;
this.show_number = show_number;
}
public void print_the_tacket(){ //should use snake case printTheTacket
System.out.println("movie id is " + super.movieID);
System.out.println("movie name is " + super.movieTitle);
System.out.println("number of the ticket is " + Number_of_ticket);
System.out.println("show number is " + show_number);
}
}
public class Main {
public static void main(String[] args) {
Ticket myticket = new Ticket(34 , 334, 1234, "spiderman");
myticket.print_the_tacket();
}
}
Much ideal is that movie is created in ticket instead of passing 2 arguments or extending. In this case both are separated and tied and incase in future movie has also things like PG-13, GA parameters you can expand it. But i guess it's for school understanding on inheritance, your example fits for now.
public class Ticket {
private int numberOfTickets;
private int showNumber ;
private Movie movie;
Ticket(int numberOfTickets , int showNumber, Movie movie){
this.numberOfTickets = numberOfTickets;
this.showNumber = showNumber;
this.movie = movie
}
public void printTheTacket(){
System.out.println("movie id is " + movie.movieID);
System.out.println("movie name is " + movie.movieTitle);
System.out.println("number of the ticket is " + numberOfTickets);
System.out.println("show number is " + showNumber);
}
}
I am trying to have my driver class inherit the information from two different classes. I have to use the formula className objectName = new className(input parameters) to instantiate one of the classes. But I keep getting the symbol not recognized error.
I'm not sure how I could fix this problem. I tried creating an import statement, but the other two classes are part of the same package. I have also tried using the extends keyword, but also noluck
public class Corgi extends Dog {
// additional class variables
private static int weight;
private static int age;
// constructor
public Corgi(String type, String breed, String name, int pounds, int years) {
// invoke Dog class (super class) constructor
super(type, breed, name);
weight = pounds;
age = years;
}
// mutator methods
public static int setWeight(int pounds){
weight = pounds;
return pounds;
}
public static int setAge(int years){
age = years;
return years;
}
// override toString() method to include additional dog information
#Override
public String toString() {
return (super.toString() + "\nThe Corgi is " + age +
" years old and weighs " + weight + " pounds.");
}
}
public class Dog {
// class variables
private static String type;
private static String breed;
private static String name;
private static String topTrick;
// constructor
public Dog(){
type = "none";
breed = "none";
name = "none";
}
// methods
public static String setTopTrick(String trick){
topTrick = trick;
return trick;
}
// method used to print Dog information
public String toString() {
String temp = "\nDOG DATA\n" + name + " is a " + breed +
", a " + type + " dog. \nThe top trick is : " +
topTrick + ".";
return temp;
}
}
public class Main
{
public static void main(String[] args) {
Corgi tricker = new Corgi();
tricker.setTopTrick("Backflip");
System.out.println(tricker);
}
}
I am expecting to be able to have the main class inherit Corgi's info with the Corgi tricker = new Corgi(); statement. But I keep getting the error:
Main.java:6: error: cannot find symbol
Corgi tricker = new Corgi("Hunting", "Shiba", "Simon", 30, 7);
^
symbol: class Corgi
location: class Main
In your Corgi class you need to remove variables from super()
public Corgi(String type, String breed, String name, int pounds, int years) {
// invoke Dog class (super class) constructor
super();
weight = pounds;
age = years;
}
2.Then you have to add values in Corgi(); which is in `Main class'
public static void main(String[] args) {
Corgi tricker = new Corgi("puppy", "Husky", "Alex", 15, 1);
tricker.setTopTrick("Backflip");
System.out.println(tricker);
}
output -:
DOG DATA
none is a none, a none dog.
The top trick is : Backflip.
The Corgi is 1 years old and weighs 15 pounds.
Sorry everyone. My code wasn't the problem. I tried using the code in a different compiler and it worked just fine. I did tweak my code a little with Kalana's advice. Thanks everyone.
I am learning java. I would like to have a enum as a parameter in my constructor. But I am getting an error
(I have my enum in a separate class that is public and named AvailabilityState {AVAILABLE,ORDERED,REMOVED }
public class Facultymember extends User {
private int MAX_GENERALBOOKS = 5;
private int MAX_AUDIOBOOKS = 2;
private AvailabilityState aStatus;
public Facultymember(int genbook, int audbook,AvailabilityState aStatus ){
this.MAX_GENERALBOOKS=genbook;
this.MAX_AUDIOBOOKS=audbook;
this.aStatus = aStatus;
}
#Override
public String toString() {
return "Facultymember {" + "MAX_GENERALBOOKS=" + MAX_GENERALBOOKS+ ", MAX_AUDIOBOOKS =" + MAX_AUDIOBOOKS + "AvailabilityState," + aStatus + '}';
}
}**
If you require a parameter of type AvailabilityState, you should provide it, like so:
User availableFaculty = new Facultymember(5,2, AvailabilityState.AVAILABLE);
User orderedFaculty = new Facultymember(5,2, AvailabilityState.ORDERED);
User removedFaculty = new Facultymember(5,2, AvailabilityState.REMOVED);
Alternatively, define another constructor with default availability state:
public Facultymember(int genbook, int audbook) {
// assuming availability by default
this(genbook, audbook, AvailabilityState.AVAILABLE);
}
I am making a program that simulates a Store and a Member. I am trying to write a method, memberRegister2(). This method is the the Store class but calls the constructor from the Member class to make a member object. This method is to be passed the name, id and pinNumber as parameters and then creates the Member object, which is to be stored in a local variable 'member'. I have no idea how to do this. As you will see from the code below I have tried to use the 'Member member = new Member()' But i do not know how to make the parameters user input.
(P.S I am using BlueJ)
Here is my code for both classes hopefully making my question make more sense. I am very new to java so excuse bad coding.
public class Store
{
// instance variables
private String storeName;
private int total;
//Member member;
/**
* Constructor for objects of class Store
*/
public Store(String newStoreName, int newTotal)
{
// initialise instance variables
storeName = newStoreName;
total = newTotal;
}
//Accessor Methods
public String getStoreName()
{
return storeName;
}
public int getTotal()
{
return total;
}
public void memberRegister1(Member newMember)
{
System.out.println("Salford Thrifty " + storeName + ": Welcome " + newMember.getName() + " (id:" + newMember.getId() + ")" );
}
public void memberRegister2()
{
//Member member = new member(memberName, memberId, memberPinNumber);
}
//Mutator Methods
public void newStoreName(String newName)
{
storeName = newName;
}
public void newTotal(int newTotal)
{
total = newTotal;
}
}
and the Member class
public class Member
{
// instance variables
private String name;
private String id;
private String pinNumber;
/**
* Constructor for objects of class Member
*/
public Member(String memberName, String memberId, String memberPinNumber)
{
// initialise instance variables
name = memberName;
id = memberId;
pinNumber = memberPinNumber;
}
public Member()
{
// initialise instance variables
name = "Bob";
id = "ASD123";
pinNumber = "5678";
}
//Accessor Methods
public String getName()
{
return name;
}
public String getId()
{
return id;
}
public String getPinNumber()
{
return pinNumber;
}
//Mutator Methods
public void newName(String newMemberName)
{
name = newMemberName;
}
public void newId(String newMemberId)
{
name = newMemberId;
}
public void newPinNumber(String newMemberPinNumber)
{
name = newMemberPinNumber;
}
}
I have been told to keep the variable at the top private and use pointers? Not sure what this means but it has not been explained to me very well.
You can a Scanner to read the user's input like so.
Scanner s = new Scanner(System.in);
String userInput = s.nextLine();
Then just initialize your member instance using the strings entered by the user.
String memberName, memberId, memberPin;
Scanner s = new Scanner(System.in);
System.out.println("Enter a name");
memberName = s.nextLine();
System.out.println("Enter an id");
memberId = s.nextLine();
System.out.println("Enter a pin");
memberPin = s.nextLine();
Member m = new Member(memberName, memberId, memberPin);
Also, you probably want to make pin, and maybe the id ints instead of strings.
Here's something I have from an old class that should show you how:
SavingsAccount myAccount = new SavingsAccount(200, 5);
So when you want to create an object from another class you have to use that second class to initialize it as shown above the SavingsAccount is like int it instantiates the object and then the two integers SavingsAccount(200, 5); is used because the method within the second class is instantiated with two integers of its own so the object you are creating must have two integers of its own. And what I mean by the method has two integer instantiated is as shown in the code below:
public SavingsAccount(double amount, double rate)
{
super(amount);
interestRate = rate;
}
if you do not instantiate a method with two objects within the parentheses then you do not need them within:
SavingsAccount myAccount = new SavingsAccount(200, 5);
I hope this helps any with your question i'm fairly new myself and am trying to help with as much as I can My course uses BlueJ as well and I know a good bit about BlueJ so I hope this helps.