首页 > 解决方案 > Java 所得税计算器需要为任何小于等于 0 的数字添加错误消息

问题描述

我有一个作为所得税计算器的 java 项目,我应该向它添加一条错误消息,以便程序不会响应收入提示中的 0 或更少的数字。我只是不确定在哪里放置提示或完成此操作需要什么类型的错误消息。代码:

   import java.util.Scanner;
   public class TaxCalculator {
    static void calculate() {
    // The tax rates for different types of customers.
    final double RATE1 = 0.20;
    final double RATE2 = 0.25;
    final double RATE3 = 0.10;
    final double RATE4 = 0.15;
    final double RATE5 = 0.30;
    final double RATE1_SINGLE_LIMIT = 1;
    final double RATE2_MARRIED_LIMIT = 1;
    final double RATE3_COHABITATING_LIMIT = 20000;
    final double RATE4_COHABITATING_LIMIT = 50000;
    double tax = 0;
    Scanner in = new Scanner(System.in);
    //Prompt for user to enter the customers income
    System.out.print("Enter customer's income: ");
    double income = in.nextDouble();
    in.nextLine();
    System.out.print("Please enter 's' for single, 'm' for married, or 'c' for cohabitating: ");
    String maritalStatus = in.next();
    in.nextLine();
    // Where the taxes are calculated
    if (maritalStatus.equals("s") && income > RATE1_SINGLE_LIMIT) {
        tax = RATE1 * income;
    } else if (maritalStatus.equals("m") && income > RATE2_MARRIED_LIMIT) {
        tax = RATE2 * income;
    } else if (maritalStatus.equals("c") && income <= RATE3_COHABITATING_LIMIT) {
        tax = RATE3 * income;
    } else if (maritalStatus.equals("c") && income <= RATE4_COHABITATING_LIMIT) {
        tax = RATE4 * income;
    } else {
        tax = RATE5 * income;
    }
    System.out.print("Your income tax is: $" + tax);
    }
    // asks user if they would like to process another customer.
    public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    String newResponse = "";
    do {
    calculate();
    System.out.println();
    System.out.println("Process another response?. Please enter 'y' for yes, or 'n' for no: ");
    newResponse = in.next();
    in.nextLine();
    } while (newResponse.equals("y"));

    }
    }

标签: java

解决方案


您可以在打印适当的提示后添加循环:

System.out.print("Enter customer's income: ");
double income;

while ((income = in.nextDouble()) <= 0) {
    System.out.print("Income " + income + " is invalid. Please input correct income which must be greater than 0: ");
    in.nextLine();
}

System.out.print("Please enter 's' for single, 'm' for married, or 'c' for cohabitating: ");
String maritalStatus;

while (!(maritalStatus = in.next()).matches("[smc]")) {
    System.out.print("Marital status " + maritalStatus + " is invalid. Please input correct value: 's', 'm', or 'c': ");
    in.nextLine();
}

输出:

Enter customer's income: -12
Income -12.0 is invalid. Please input correct income which must be greater than 0: -23
Income -23.0 is invalid. Please input correct income which must be greater than 0: 2300
Please enter 's' for single, 'm' for married, or 'c' for cohabitating: 1
Marital status 1 is invalid. Please input correct value: 's', 'm', or 'c': m

推荐阅读