Question

Needs Help In Java Programming language Exceptional Cars Purpose To review interfaces and exception usage. Directions...

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

0 0
Add a comment Improve this question Transcribed image text
Answer #1
import java.io.*;
import java.util.*;

//Exception class that denotes negative number
class NegativeNumberException extends Exception{
    NegativeNumberException(){

    }

    NegativeNumberException(String msg){
        super(msg);
    }
}

//Car class
class Car{
    //Private member variables
    private int position;
    private boolean headLightsOn;

    //Default constructor
    public Car(){
        position = 0;
        headLightsOn = false;
    }

    //Argumented constructor
    public Car(int position){
        this.position = position;
        headLightsOn = false;
    }

    @Override
    public String toString(){
        return "This car is in position "+position+" and its headlights "+(headLightsOn?"On":"Off");
    }

    //Method to toggle head lights
    public boolean toggleHeadLights(){
        headLightsOn =  !headLightsOn;
        return headLightsOn;
    }

    //method that takes car forward
    public int forward(int amount) throws NegativeNumberException {
        if(amount<0){
            throw new NegativeNumberException("You can't go forward a negative amount");
        }
        this.position += amount;
        return this.position;
    }
}

class Driver{
    public static void main(String[] args) {
        Car c1 = new Car();
        Car c2 = new Car(5);

        try {
            c1.forward(5);
            c2.forward(-2);
        } catch (NegativeNumberException e) {
            System.out.println(e);
        }
    }
}

OUTPUT :

Add a comment
Know the answer?
Add Answer to:
Needs Help In Java Programming language Exceptional Cars Purpose To review interfaces and exception usage. Directions...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Needs Help with Java Programming language! Lights Camera Action Purpose: To learn the basics of linked...

    Needs Help with Java Programming language! Lights Camera Action Purpose: To learn the basics of linked lists You are to implement 2 classes, Scene and Movie. The Scene class has the following fields and methods: private String event private Scene nextScene Public Scene(String event) - A constructor that creates a Scene object with the event set and nextScene set to null Public Scene(String event, Scene next) - A constructor that creates a Scene object with the event and the nextScene...

  • Java programming The purpose of this problem is to practice using a generic Urn class. NOTE:...

    Java programming The purpose of this problem is to practice using a generic Urn class. NOTE: Refer to the code for the ArrayStack class from Chapter 12. Use that code as a starting point to create the Urn class, modifying it to remove the methods in the ArrayStack class (push, pop, etc) then add the methods described below. Also change the variable names to reflect the new class. For example the array name should NOT be stack, instead it should...

  • I need help writing my main method**** Computer Science 111 Introduction to Algorithms and Programming: Java...

    I need help writing my main method**** Computer Science 111 Introduction to Algorithms and Programming: Java Programming Project #4 – Classes and Objects (20 Points) You will create 3 new classes for this project, two will be chosen from the list below and one will be an entirely new class you invent.Here is the list: Shirt Shoe Wine Book Song Bicycle VideoGame Plant Car FootBall Boat Computer WebSite Movie Beer Pants TVShow MotorCycle Design First Create three (3) UML diagrams...

  • Hello. I need help writing the following Java Program. Thank you Develop a class encapsulating the...

    Hello. I need help writing the following Java Program. Thank you Develop a class encapsulating the concept of a college course, assuming that a course has following attributers: code (for instance COSC1337), a description, and a number of credits (for instance 3). Include a constructor, the accessors, mutators and methods ‘toString’, ‘equals’, and ‘finalize’. Write a client class to test the behavior of the class and its methods. The outline of the class is given as follows: public class Course...

  • Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored in an ...

    Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored in an array. Implement all methods in ArrayStack class using resizable array strategy, i.e. usedoubleArray() Must throw StackException during exception events in methods:    peek(), pop(), ArrayStack(int initialCapacity) Do not change or add data fields Do not add new methods */ import java.util.Arrays; public class Arraystack«Т> implements Stack!nterface«T> private TI stack;// Array of stack entries private int topIndex; /7 Index of top entry private static...

  • DIRECTIONS FOR THE WHOLE PROJECT BELOW BigInt class The purpose of the BigInt class is to...

    DIRECTIONS FOR THE WHOLE PROJECT BELOW BigInt class The purpose of the BigInt class is to solve the problem using short methods that work together to solve the operations of add, subtract multiply and divide.   A constructor can call a method called setSignAndRemoveItIfItIsThere(). It receives the string that was sent to the constructor and sets a boolean variable positive to true or false and then returns a string without the sign that can then be processed by the constructor to...

  • Please help me do the java project For this project you will be reading in a...

    Please help me do the java project For this project you will be reading in a text file and evaluating it in order to create a new file that represents the Class that will represent the properties of the text file. For example, consider the following text file: students.txt ID              Name                              Age                    IsMale           GPA 1                Tom Ryan                       22                       True              3.1 2                Jack Peterson                31                       True              2.7 3                Cindy LuWho                12                       False             3.9 When you read in the header line, you...

  • Need help with writing a Client test in JAVA

    public class TutorialSpace {                  // slots — the number of available slots in a tutorial class         private int slots;         // activated — true if the tutorial class has been activated         private boolean activated;                  /**         * TutorialSpace(n) — a constructor for a tutorial class with n slots.         *          * @param n         */         public TutorialSpace(int n) {                 this.slots = n;                 this.activated = false;         }                  /**         * activate() — activates the tutorial class. Throws an exception if the         * tutorial class has already been activated.         *          * @throws NotActivatedException         */                  public void activate() throws NotActivatedException {                 if (activated) {                         throw new NotActivatedException("Already Activated");                 } else {                         activated = true;                 }         }                  /**         * reserveSlot()—enrol a student into the tutorial class by decreasing the         * number of slots left for enrolling in the class. Throws an exception if slot         * is either completely used or the tutorial class is not active.         *          * @throws EmptyException         */         public void reserveSlot() throws EmptyException {                                  if (!activated || slots == 0) {                         throw new EmptyException("Tutorial space is empty");                 } else {                         slots--;                 }         }                  /**         * slotsRemaining()—returns the number of slots remaining in the tutorial class.         */                  public int slotsRemaining() {                 return slots;         }          } public class NotActivatedException extends Exception {                  /**         *          */         private static final long serialVersionUID = 1L;                  public NotActivatedException(String msg) {                 super(msg);         }          } public class EmptyException extends Exception {                  /**         *          */         private static final long serialVersionUID = 1L;         public EmptyException(String msg) {                 super(msg);         }                  ...

  • Please answer the following question with Java Modify the Employee and ProductionWorker classes provided below so...

    Please answer the following question with Java Modify the Employee and ProductionWorker classes provided below so they throw exceptions when the following errors occur. - The Employee class should throw an exception named InvalidEmployeeNumber when it receives an employee number that is less than 0 or greater than 9999. - The ProductionWorker class should throw an exception named InvalidShift when it receives an invalid shift. - The ProductionWorker class should thrown anexception named InvalidPayRate when it receives a negative number...

  • Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored...

    Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored in an array. Implement all methods in ArrayStack class using resizable array strategy, i.e. usedoubleArray() Must throw StackException during exception events in methods:    peek(), pop(), ArrayStack(int initialCapacity) Do not change or add data fields Do not add new methods */ import java.util.Arrays; public class Arraystack«Т> implements Stack!nterface«T> private TI stack;// Array of stack entries private int topIndex; /7 Index of top entry private...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT