输入负数时如何引起错误信息?

时间:2019-09-28 05:10:56

标签: java netbeans

我编写了代码,根据用户选择的座位数计算总数。问题是当我为其中一个座位输入负数时,总和仍在计算中。相反,当输入负数时,我希望弹出错误消息而不计算总数。

package javatheatreseating;
import java.util.Scanner;


public class JavaTheatreSeating {
    public static final double PREMIUM_PRICE = 45.00;
    public static final double STANDARD_PRICE = 30.00;
    public static final double ECONOMY_PRICE = 21.00;
    public static final double TAX_RATE = 0.0825;
    public static final double SURCHARGE = 5.00;        

    public static void main(String[] args) {
        int premiumSeats;
        int standardSeats;
        int economySeats;
        double subTotal;
        double salesTax;
        double surCharge;
        double total;

        Scanner stdin = new Scanner(System.in);

    //INPUT: number of seats sold 

        System.out.print ("Enter the number of Premium Seats Sold:  ");
        premiumSeats = stdin.nextInt(); 
        System.out.print ("Enter the number of Standard Seats Sold: ");
        standardSeats =  stdin.nextInt();
        System.out.print ("Enter the number of Economy Seats Sold: ");
        economySeats = stdin.nextInt(); 


    //PROCESS: i calculate the total and add the percent of tax based on the seats added
    subTotal = premiumSeats * PREMIUM_PRICE + standardSeats * STANDARD_PRICE + economySeats * ECONOMY_PRICE;
    salesTax = TAX_RATE * subTotal;
    total = subTotal + salesTax + SURCHARGE; 


    //OUTPUT:
        System.out.println();
        System.out.println("Subtotal: " + subTotal);
        System.out.println("Tax: " + salesTax);
        System.out.println("surCharge: " + SURCHARGE);
        System.out.println("Total: " + total);


    }

}

1 个答案:

答案 0 :(得分:1)

在每个变量输入周围进行while循环,并保持循环,直到用户正确使用为止。我没有检查它是否可以编译。

while (true) {
    try {
        System.out.print ("Enter the number of Premium Seats Sold:  ");
        premiumSeats = stdin.nextInt();
        if (premiumSeats >= 0){
            break;
        } else {
            System.out.print ("Please Enter a positive integer.\n");
        }
    }
    catch (Exception e){
        System.out.print ("Please Enter a number.\n");
    }
}