Question: Define the class InvalidSideException, which inherits from the Exception class. Also define a Square class, which has one method variable -- an intdescribing the side
Define the class InvalidSideException, which inherits from the Exception class. Also define a Square class, which has one method variable -- an intdescribing the side length. The constructor of the Square class should take one argument, an int meant to initialize the side length; however, if the argument is not greater than 0, the constructor should throw an InvalidSideError. The Square class should also have a method getArea(), which returns the area of the square. Create a Driver class with a main method to test your classes. Your program should prompt the user to enter a value for the side length, and then create a Square object with that side length. If the side length is valid, the program should print the area of the square. Otherwise, it should catch the InvalidExceptionError, print "Side length must be greater than 0.", and terminate the program.
Sample Run
Entersidelengthofsquare:-13? Sidelengthmustbegreaterthan0.?
Currently have:
import java.util.Scanner;
import java.util.logging.Level; import java.util.logging.Logger;
class InvalidSideException extends Exception {
private static final long serialVersionUID = 1L;
InvalidSideException(String s) { super(s); } }
class Square { int sideLength;
public Square(int sideLength) throws InvalidSideException {
if (sideLength <= 0) { throw new InvalidSideException("side length must be greater than 0"); } else { this.sideLength = sideLength; }
}
public int getArea() { return this.sideLength * this.sideLength; }
}
public class Driver {
public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.print("Enter side length of square:"); int length = sc.nextInt();
try { Square obj = new Square(length); System.out.println(obj.getArea()); }catch (InvalidSideException ex) { Logger.getLogger(Driver.class.getName()) .log(Level.SEVERE, null, ex); ex.printStackTrace(); } } }
Output Error:
Problems Detected: ? The contents of your standard output is incorrect.
Given the following was entered from the keyboard: 0 you displayed: Enter side length of square: instead of: Enter side length of square:Side length must be greater than 0.
Anyone know what I am doing wrong? Thank you
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
