1. Engineering
  2. Computer Science
  3. needs help in java programming language exceptional cars purpose to...

Question: needs help in java programming language exceptional cars purpose to...

Question details

Needs Help In Java Programming language

Exceptional Cars

Purpose To review interfaces and exception usage.

Directions

Your task is to write a class called Car. Your class should have the following fields and methods:

private int position
private boolean
headlightsOn

public Car() - a constructor which initializes position to 0 and headlightsOn to false

public Car(int position) - a constructor which initializes position to the passed in value and headlightsOn to false, and it should throw a NegativeNumberException with a custom message when a negative number is passed
public String toString() - a method that returns a String of form
"This car is in position *position* and has its headlights on if headlightsOn is True” "This car is in position *position* and has its headlights off if headlightsOn is False”

Note : *position* denotes the value of the variable position

Your Car class also needs to implement a drivable interface which you will also make that includes the methods:
public boolean toggleHeadlights() - which toggles the headlightsOn variable between true and false

public int forward(int amount) - which adds the amount passed in to the position of the car, and throws a NegativeNumberException with a custom message when a negative number is passed

You will create the NegativeNumberException class which will have the following methods:
public NegativeNumberException() - a constructor that creates an exception with a blank message

public NegativeNumberException(String message) - a constructor which passes a message to the NegativeNumberException’s parent exception class

So in summary you are making a Car class, a drivable interface, and a custom exception

Testing:

You also need to create a class called Driver.java with a main method.

In main:
Create two Car objects

Surround all of the forward method calls with a single try catch block

Call forward on both of the Cars
Make one of the Cars throw a NegativeNumberException

Print out the toString of both cars

Example Output:

NegativeNumberException: You can't go forward a negative amount

at Car.forward(Car.java:15)
at Driver.main(Driver.java:13)

This car is in position 21 and has its headlights off

This car is in position 31 and has its headlights on

Solution by an expert tutor
Blurred Solution
This question has been solved
Subscribe to see this solution