Java try-catch 异常处理



矩形类

设计一个名为 Rectangle 的类来表示矩形。该类包含:

  • 两个名为宽度和高度的双精度数据字段,用于指定宽度和 矩形的高度。宽度和高度的默认值均为 1。
  • 创建默认矩形的无参数构造函数。
  • 创建具有指定宽度和高度的矩形的构造函数。
  • 一个名为 getArea() 的方法,它返回此矩形的面积。
  • 一个名为 getPerimeter() 的方法,用于返回周长。

编写一个测试程序,允许用户输入矩形宽度和高度的数据。该程序应包括 try-catch 块和异常处理。编写程序,以便在用户输入输入后在类中对其进行验证,如果有效,则显示相应的结果。如果无效,类应该向 Test 类中的 catch 块抛出异常,该异常通知用户有关错误的消息,然后程序应返回到输入部分。

我创建的矩形类如下所示:

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;
        }
    }
}

到目前为止,我在下面拥有的测试程序:

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());
    }
}

我遇到的主要问题是,当捕获异常时,它不会打印出相应的错误消息。不知道我在那个问题上做错了什么。我不能只是在 catch 方法中添加一个 print 语句,因为教授希望错误消息是从矩形类中的 isValid 方法发送的。

我遇到的第二个小问题是如何在 isValid 方法中添加另一个步骤,用于宽度和高度,以确保用户的输入不是字母或其他字符。反过来,如何将该附加异常添加为我的 try-catch 块中的另一个捕获。

任何帮助将不胜感激!

您没有打印任何内容,只会收到错误消息。

尝试System.err.println(rec.getErrorMessage());而不是rec.getErrorMessage();

看起来您可能对异常处理有些困惑。您通常需要在Exception对象上设置错误消息

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

那么如果我们在其他地方调用此方法

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

我们将捕获异常,这将打印出我们在方法foo设置的消息。

代码片段中有很多冗余字段和方法。您的Rectangle应如下所示:

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);
    }
}

然后按如下方式执行测试类:

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());
    }
}

您已经在 Rectangle 类中执行 try-catch,因此无需在测试主类中重新执行。始终尝试将代码减少到最基本的必要条件。你拥有的冗余代码行越多,你的程序就会变得越糟糕。

最新更新