簡體   English   中英

當用戶輸入非雙精度值時,如何獲取 Java 引發異常?

[英]How can a get Java to throw an exception when user enters something other than a double?

我正在編寫一個程序,該程序根據牆壁的面積計算覆蓋牆壁所需的油漆量。 牆的高度和寬度(雙打)由用戶輸入。 如果給出無效輸入(即字符串),我需要程序重新提示用戶。 如果用戶輸入無效數字(即負數),我已經有一個異常,但是我找不到讓程序顯示我的錯誤消息並在輸入字符串或字符時提示輸入的方法。 對此的任何幫助將不勝感激。

這是我的代碼

導入 java.util.Scanner;

公共 class 油漆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);

    }
}

}

雙#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

有關解決方案,請參閱Arvind 的答案

一種選擇是將輸入作為String檢索,然后使用Double#parseDouble function 來確保輸入是雙精度。 如果不是,則會引發異常,您可以處理該異常並為用戶提供一些 output。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM