gpt4 book ai didi

java - 输入负数时如何导致错误提示?

转载 作者:行者123 更新时间:2023-11-30 05:28:12 26 4
gpt4 key购买 nike

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

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);


}

}

最佳答案

在每个变量输入周围放置一个 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");
}
}

关于java - 输入负数时如何导致错误提示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58143540/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com