0

The Rectangle class

Design a class named Rectangle to represent a rectangle. The class contains:

  • Two double data fields named width and height that specify the width and height of the rectangle. The default values are 1 for both width and height.
  • A no-arg constructor that creates a default rectangle.
  • A constructor that creates a rectangle with the specified width and height.
  • A method named getArea() that returns the area of this rectangle.
  • A method named getPerimeter() that returns the perimeter.

Write a test program that allows the user to enter the data for the rectangles width and height. The program should include try-catch blocks and exception handling. Write the program so that after the user enters the input it is validated in the Class and if valid the appropriate results are shown. If not valid, the Class should throw an exception to the catch block in the Test class which notifies the user with a message about the error and then program should return to the input portions.

The Rectangle class I have created is below:

public class Rectangle {

    //two double data fields width and height, default values are 1 for both.
    private double width = 1;
    private double height = 1;
    private String errorMessage = "";

    //no-arg constructor creates default rectangle
    public Rectangle() {    
    }

    //fpzc, called by another program with a statement like Rectangle rec = new Rectangle(#, #);
    public Rectangle (double _width, double _height) throws Exception {
        setWidth(_width);
        setHeight(_height);
    }

    //get functions
    public double getArea(){
        return (width * height);
    }

    public double getPerimeter() {
        return (2*(width + height));
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    //set functions
    public void setWidth(double _width) throws Exception {
        if( !isValidWidth(_width)){
            Exception e = new Exception(errorMessage);
            throw e;
            //System.out.println(errorMessage);
            //return false;
        }
        width = _width;
    }

    public void setHeight(double _height) throws Exception {
        if ( !isValidHeight(_height)){
            Exception e = new Exception(errorMessage);
            throw e;
            //System.out.println(errorMessage);
            //return false;
        }
        height = _height;
    }

    //isValid methods
    public boolean isValidWidth(double _width) {
        //default check
        //if(_width == 1) {
        //  return true;
        //}

        if(_width > 0){
            return true;
        }
        else {
            errorMessage = "Invalid value for width, must be greater than zero";
            return false;
        }

    }

    public boolean isValidHeight(double _height) {
        //default check
        //if(_height == 1){
        //  return true;
        //}

        if(_height > 0){
            return true;
        }
        else {
            errorMessage = "Invalid value for height, must be greater than zero";
            return false;
        }
    }
}

And the test program i have so far below:

import java.util.Scanner;
import java.util.InputMismatchException;

public class TestRectangle {

    //default constructor
    public TestRectangle() {
    }

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        Rectangle rec = new Rectangle();
        boolean Continue = true;
        double _width = 1;
        double _height = 1;

        do {
            try {
                System.out.println("Please enter a numerical value for the rectangle's width:");
                _width = input.nextDouble();
                rec.setWidth(_width);
                Continue = false;
                }
            catch (Exception e){
                rec.getErrorMessage();
                Continue = true;
            }

        } while (Continue);

        do{
            try {
                System.out.println("Please enter a numerical value for the rectangle's height:");
                _height = input.nextDouble();
                rec.setHeight(_height);
                Continue = false;
            }
            catch (Exception e){
                rec.getErrorMessage();
                Continue = true;
            }
        } while (Continue);

        System.out.println("The rectangle has a width of " + _width + " and a height of " + _height);
        System.out.println("the area is " + rec.getArea());
        System.out.println("The perimeter is " + rec.getPerimeter());
    }
}

Te main issue I am having is that when the exception is caught it does not print out the respective errorMessage. Not sure what I am doing wrong on that one. I cannot just add a print statement into the catch method because the professor wants the error message to be sent from the isValid method in the rectangle class.

The second small issue I am having is how to add another step into the isValid method for both the width and height that makes sure the input from the user is not a letter or other character. And in turn how to add that additional exception as another catch in my try-catch block.

Any help would be much appreciated!

3 Answers 3

1

You're not printing anything out, only getting the error message.

Try System.err.println(rec.getErrorMessage()); instead of rec.getErrorMessage();

Sign up to request clarification or add additional context in comments.

2 Comments

could you tell me if using the InputMismatchException would stop the user from trying to input letters or characters into the double width or height?
Catching a InputMismatchException won't prevent the user from inputting illegal characters. For that you'd have to do something like loop through a try-catch block until the input is valid, and tell the user that the input was wrong in the catch block.
0

It looks like you may have some confusion about exception handling. You'll usually want to set the error message on the Exception object

public void foo() {
  throw new Exception("Oh no!");
}

Then if we call this method somewhere else

try {
  foo();
} catch (Exception e) {
  // e contains the thrown exception, with the message 
  System.out.println(e.getMessage());
}

We will catch the exception and this will print out the message we set in out foo method.

Comments

0

There are so many redundant fields and methods in your code snippet.Your Rectangle should be as following:

import java.util.InputMismatchException;

public class Rectangle
{

    private double width;
    private double height;


    public Rectangle()
    {
        width = 1;
        height = 1;
    }


    public Rectangle(double width, double height)
        throws Exception
    {
        setWidth(width);
        setHeight(height);
    }


    public double getArea()
    {
        return (width * height);
    }


    public double getWidth()
    {
        return width;
    }


    public double getHeight()
    {
        return height;
    }


    public double getPerimeter()
    {
        return (2 * (width + height));
    }


    public void setWidth(double w)
        throws Exception
    {
        if (!isValidWidth(w))
        {

            throw new InputMismatchException(
                "Invalid width value, must be greater than zero");

        }
        this.width = w;

    }


    public void setHeight(double h)
        throws Exception
    {
        if (!isValidHeight(h))
        {
            throw new InputMismatchException(
                "Invalid height value, must be greater than zero");
        }
        this.height = h;
    }


    public boolean isValidWidth(double w)
    {

        return (w > 0);

    }


    public boolean isValidHeight(double _height)
    {

        return (_height > 0);

    }
}

Then do your test class as the following:

import java.util.Scanner;
import java.util.InputMismatchException;

public class TestRectangle
{

    public static void main(String[] args)
        throws Exception
    {

        Scanner input = new Scanner(System.in);
        System.out.println("Enter your width: ");
        double width = input.nextDouble();
        input = new Scanner(System.in);
        System.out.println("Enter your height: ");
        double height = input.nextDouble();

        Rectangle rec = new Rectangle(width, height);
        System.out.println(
            "The rectangle has a width of " + rec.getWidth()
                + " and a height of " + rec.getHeight());

        System.out.println("the area is " + rec.getArea());
        System.out.println("The perimeter is " + rec.getPerimeter());

    }
}

You are already doing try-catch in your Rectangle class so there is no need to do it over in your test main class.Always try to reduce your code to bare necessities.The more line of redundant code you have , the worse your program will turn into.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.