繁体   English   中英

如何在捕获异常后保持我的代码运行 (Java)

[英]How to keep my code running after an exception is caught (Java)

我正在尝试为一个可以处理来自用户的所有异常和无效条目的类项目编写代码。

import java.util.Scanner;

public class Paint1 {

public static void main(String[] args) {
    Scanner scnr = new Scanner(System.in);
    double wallHeight = 0.0;
    double wallWidth = 0.0;
    double wallArea = 0.0;
    double gallonsPaintNeeded = 0.0;

    final double squareFeetPerGallons = 350.0;

    // Implement a do-while loop to ensure input is valid
    // Prompt user to input wall's height
    try {
        //System.out.println("Enter wall height (feet): ");
        do {//wallHeight = scnr.nextDouble();
            System.out.println("Enter wall height (feet): ");
            wallHeight = scnr.nextDouble();
            if (wallHeight <= 0) {
                System.out.println("Invalid height");
            }
        } while (wallHeight <= 0);
    } catch (Exception excpt) {
        System.out.println("Invalid height");
        wallHeight = scnr.nextDouble();
    }

    // Implement a do-while loop to ensure input is valid
    // Prompt user to input wall's width
    do {
        System.out.println("Enter wall width (feet): ");
        wallWidth = scnr.nextDouble();
        if (wallWidth <= 0) {
            System.out.println("Invalid Width");
        }
    } while (wallWidth <= 0);


    // Calculate and output wall area
    wallArea = wallHeight * wallWidth;
    System.out.println("Wall area:  " + wallArea + " square feet");

    // Calculate and output the amount of paint (in gallons) needed to paint the wall
    gallonsPaintNeeded = wallArea/squareFeetPerGallons;
    System.out.println("Paint needed: " + gallonsPaintNeeded + " gallons");

}
}

我试图通过分配的检查是为 wallHeight 输入一个字符串而不是双精度值。 它打印“无效高度”,但随后程序停止运行并返回错误。 如何让它继续运行并再次提示用户输入有效信息?

if (in.hasNextDouble()) {
        double a = in.hasNextDouble() ; 
        System.out.println(a);
    } else {
        System.out.println("Invalid input");
    }

这甚至可以防止 InputMismatchException 被抛出,因为在阅读它之前你总是确保它匹配。

您当前提示输入的方法(在wallWidthwallHeight )存在缺陷,因为您捕获了一个几乎可以肯定是InputMismatchException的异常(然后您未能使用不是数字的标记)。 我强烈建议您将提示提取到另一种方法; 就像是

private static double readWallDimension(Scanner scnr, String dimension) {
    for (;;) {
        try {
            System.out.printf("Enter wall %s (feet):%n", dimension);
            double dim = scnr.nextDouble();
            if (dim <= 0) {
                System.out.printf("Invalid %s%n", dimension);
            } else {
                return dim;
            }
        } catch (InputMismatchException excpt) {
            System.out.printf("Invalid %s%n", dimension);
            scnr.nextLine();
        }
    }
}

然后您的main方法要简单得多,调用该方法两次(并且两次都在本地处理异常)。

public static void main(String[] args) {
    Scanner scnr = new Scanner(System.in);
    final double squareFeetPerGallons = 350.0;

    double wallHeight = readWallDimension(scnr, "height");
    double wallWidth = readWallDimension(scnr, "width");

    // Calculate and output wall area
    double wallArea = wallHeight * wallWidth;
    System.out.println("Wall area:  " + wallArea + " square feet");

    // Calculate and output the amount of paint (in gallons) needed to paint the
    // wall
    double gallonsPaintNeeded = wallArea / squareFeetPerGallons;
    System.out.println("Paint needed: " + gallonsPaintNeeded + " gallons");
}

这是基于您的代码的工作变体,带有修复和解释:

    // Implement a do-while loop to ensure input is valid
    // Prompt user to input wall's height
    do { // moved one level up <- enable repeated input until it is valid
        try { // moved one level down <- catch exception where it occurs
            System.out.println("Enter wall height (feet): ");
            wallHeight = scnr.nextDouble();
            if (wallHeight <= 0) {
                System.out.println("Invalid height");
            }
        } catch (Exception excpt) { // generally better: InputMismatchException
            System.out.println("Invalid height");
            scnr.nextLine(); // SKIP THIS INVALID LINE.
            // Otherwise calling nextDouble() only throws the same exception as previously.
        }
    } while (wallHeight <= 0);

请注意,这应该符合 OP。 除此以外:

  • 如果您可能会在您的类项目中引入新方法,那么将do - while提取到用于读取任何数字输入的专用方法应该是可行的方法。
  • 如果您想避免处理异常,您可以使用scnr.hasNextDouble() + scnr.nextLine()的组合。 您可以阅读这些方法的javadoc以完全了解它们的作用。
import java.util.Scanner;

public class Paint1 {

    public static void main(String[] args) {
        Scanner scnr = new Scanner(System.in);
        double wallHeight = 0.0;
        double wallWidth = 0.0;
        double wallArea = 0.0;
        double gallonsPaintNeeded = 0.0;
        boolean validNumber = false;
        
        final double squareFeetPerGallons = 350.0;
        
        // Implement a do-while loop to ensure input is valid
        // Prompt user to input wall's height
        do {
        System.out.println("Enter wall height (feet): ");
        if (scnr.hasNextDouble()) {
            wallHeight = scnr.nextDouble();
            validNumber = true;
            if (wallHeight >0) {
                wallHeight = wallHeight;
            } else {
                System.out.println("Must be greater than 0.  Try again.");
                validNumber = false;
            }
        } else {
            System.out.println("Invalid input.  Try again.");
            System.out.println();
            validNumber = false;
            scnr.next();
        } 
        } while (!validNumber);
        
        

        // Implement a do-while loop to ensure input is valid
        // Implement if-else loops to ensure correct value/type is given
        // Prompt user to input wall's width
        validNumber = false;
        do {
            System.out.println("Enter wall width (feet): ");
            if (scnr.hasNextDouble()) { 
                wallWidth = scnr.nextDouble();  
                validNumber = true;
                if (wallWidth >0) {  
                    wallWidth = wallWidth;
                } else {
                    System.out.println("Must be greater than 0.  Try again.");
                    validNumber = false;
                }
            } else {
                System.out.println("Invalid input.  Try again.");
                System.out.println();
                validNumber = false;
                scnr.next();
            }    
        } while (!validNumber); 

        // Calculate and output wall area
        wallArea = wallHeight * wallWidth;
        System.out.println("Wall area: " + wallArea + " square feet");

        // Calculate and output the amount of paint (in gallons) needed to paint the wall
        gallonsPaintNeeded = wallArea/squareFeetPerGallons;
        System.out.println("Paint needed: " + gallonsPaintNeeded + " gallons");

    }
}

暂无
暂无

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

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