java - 错误捕获/异常处理

标签 java

我对使用 try/catch block 的错误捕获有了基本的了解,但是我的捕获方法使用户在输入无效字符后重新启动程序。

有人可以演示如何在允许程序运行的同时进行有效的错误捕获吗?

代码:

import java.io.*; //Input/Output command; this part is ESSENTIAL

class FindingTheSurfaceAreaOfAPyramid2
{
    public static void main (String[] args) throws IOException
    {
        BufferedReader myInput = new BufferedReader (new InputStreamReader (System.in));   //Loading the Text Box

        //Defining variables and string 'nicknames'
        String stringBaseLength, stringBaseWidth, stringTriangleHeight;  //named strings for organization's sake
        double convertToNumL, convertToNumW, convertToNumH, total1, total2, total3;   //'double' is nessesary for decimal answers as they commonly happen, using 'int' will round the result; inaccurate!
        //used in 'if' statements
        boolean realNumber = true;
        boolean realNumber2 = true;
        boolean realNumber3 = true;

        //First message and notice
        System.out.println ("Note: This program is compatible with ONLY rectangular based pyramids.");

        //Question 1: Units
        System.out.println ("First off, what unit is this pyramid in? (ex. cm, mm, in, ft. etc.)");
        String Units = myInput.readLine ();

        //Question 2: Length
        System.out.println ("1) Please enter the length of the base.");
        stringBaseLength = myInput.readLine ();
        try
        {
            Integer.parseInt (stringBaseLength);
            System.out.println ("Your base length is " + stringBaseLength + " " + Units + ".");  //this line is restating the the input as well as the unit of measurement
        }
        catch (NumberFormatException e)
        {
            //If they catch anything other than numbers, it would tell the user
            System.out.println ("That was either a smart remark, a negative number or jibberish.");
            System.out.println ("As a consequence, you have to restart the program.");
            realNumber = false;


        }
        if (realNumber)
        {
            //Question 3: Width
            System.out.println ("2) Please enter the width of the base");
            stringBaseWidth = myInput.readLine ();


            try
            {
                Integer.parseInt (stringBaseWidth);
                System.out.println ("Your base width is " + stringBaseWidth + " " + Units + ".");

            }
            catch (Exception e)
            {
                System.out.println ("That was either a smart remark, a negative number or jibberish.");
                System.out.println ("As a consequence, you have to restart the program.");
                realNumber2 = false;

            }
            if (realNumber2)
            {
                //Question 4: Height
                System.out.println ("3) Please enter the height of the triangle face.");
                stringTriangleHeight = myInput.readLine ();

                try
                {
                    Integer.parseInt (stringTriangleHeight);
                    System.out.println ("Your triangle height is " + stringTriangleHeight + " " + Units + ".");
                }
                catch (Exception e)
                {
                    System.out.println ("That was either a smart remark, a negative number or jibberish.");
                    System.out.println ("As a consequence, you have to restart the program.");
                    realNumber3 = false;
                }
                if (realNumber3)
                {

                    //Converting the input to 'double' to express the answer(s) in decimal format
                    convertToNumH = Double.parseDouble (stringTriangleHeight);
                    convertToNumL = Double.parseDouble (stringBaseLength);
                    convertToNumW = Double.parseDouble (stringBaseWidth);
                    total1 = convertToNumL * convertToNumW;         //base area, length x width
                    total2 = convertToNumL * convertToNumH / 2;     //triangle area using sidelength 'length', base x height / 2
                    total3 = convertToNumW * convertToNumH / 2;     //triangle area using sidelength 'width  ,  base x height / 2

                    //Calculations and concluding sentences
                    System.out.println ("The area of the triangle with base length " + convertToNumL + " cm is " + total2 + Units + "^2.");
                    System.out.println ("The area of the triangle with base length " + convertToNumW + " cm is " + total3 + Units + "^2.");
                    System.out.println ("The base area is " + total1 + " " + Units + "^2.");
                    System.out.println ("The total surface area is " + (total1 + total2 + total2 + total3 + total3) + " " + Units + "^2.");
                }
            }
        }
    }
} //end

最佳答案

您发布了很多代码,但在发生错误后继续的一种模式非常简单。在伪代码中:

boolean validInput = false;
while (!validInput) {
    // Read some input from the user
    // If it's of the right format, set validInput to true
    // Else print an error message, and don't change validInput
}

循环将继续执行,直到用户输入有效的内容(当然,或者终止程序)。

关于java - 错误捕获/异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15097767/

相关文章:

java - testng 测试通过 selenium 网格返回 ie 驱动程序路径错误,但测试适用于 Firefox

java - 如何使用 Guava 在 GWT 中缓存服务器结果?

java - GWT native 到长转换

java - 将对象转换为 Java 中的自定义 DTO 列表

java - 我必须删除已调用 NewGlobalRef 的对象吗?

java - 嵌套单表继承

java - couchdb 的连接池

java - myBatis中与JAVA对象映射时如何将integer[]直接转换为List<Integer>

java - 无法通过 spring-boot 应用程序访问 Angular 页面

java - 从具有完整 future 的循环中的数据库获取结果