首页 > 解决方案 > 当用户输入双精度以外的内容时,如何让 Java 引发异常?

问题描述

我正在编写一个程序,该程序根据墙壁的面积计算覆盖墙壁所需的油漆量。墙的高度和宽度(双打)由用户输入。如果给出无效输入(即字符串),我需要程序重新提示用户。如果用户输入无效数字(即负数),我已经有一个例外,但我找不到让程序显示我的错误消息并在输入字符串或字符时提示输入的方法。对此的任何帮助将不胜感激。

这是我的代码

导入 java.util.Scanner;

公共类油漆1 {

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;
    char userDone = 'n'; 

    // Implement a do-while loop to ensure input is valid
    while (userDone != 'q') {

        try {

    // Prompt user to input wall's height
            System.out.println("Enter wall height (feet): ");
            wallHeight = scnr.nextDouble();
            if (wallHeight <= 0) {  //error message for 0 or neg height input
                throw new Exception ("Invalid height.");
            }

    // Prompt user to input wall's width
            System.out.println("Enter wall width (feet): ");
            wallWidth = scnr.nextDouble();
            if (wallWidth <= 0) {  //error message for 0 or neg width input
                throw new Exception ("Invalid width.");
            }

    // 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");
        }
        catch (Exception excpt) {
            System.out.println(excpt.getMessage());
        }


    // Prompt user to quit or continue
            System.out.println("Would you like to start a new calculation? \n(press any key to continue or 'q' to quit)");
            userDone = scnr.next().charAt(0);

    }
}

}

标签: javaexception

解决方案


双#parseDouble

使用它来解析输入并使用所需消息处理异常,以防解析失败。

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner kb = new Scanner(System.in);
        double n;
        boolean valid;
        do {
            valid = true;
            System.out.print("Enter a number: ");
            try {
                n = Double.parseDouble(kb.nextLine());
                System.out.println("The number is " + n);
                // ...your business logic
            } catch (NumberFormatException | NullPointerException e) {
                System.out.println("Invalid input. Try again");
                valid = false;
            }
        } while (!valid);
    }
}

示例运行:

Enter a number: a
Invalid input. Try again
Enter a number: xyz
Invalid input. Try again
Enter a number: 4.5
The number is 4.5

推荐阅读