繁体   English   中英

Java Try-Catch异常处理

[英]Java Try-Catch Exception Handling

矩形类

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

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

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

我创建的Rectangle类如下:

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

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

我遇到的第二个小问题是如何在isValid方法中为宽度和高度添加第二步,以确保来自用户的输入不是字母或其他字符。 进而在我的try-catch块中,如何将其他异常添加为另一个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,因此无需在测试主类中进行遍历。 始终尝试将代码减少到几乎没有必要。多余的代码行越多,程序将变得越糟。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM