【问题标题】:How can I loop my java tax calculator so it restarts after throwing an exception?如何循环我的 Java 税收计算器,以便在引发异常后重新启动?
【发布时间】:2021-07-12 23:57:09
【问题描述】:

我正在学习 Java 课程,但我坚持练习。我创建了一个税收计算器,它对用户输入的金额应用不同的税收百分比,具体取决于金额所在的范围。计算器完全按照预期工作。我添加了一个 try/catch 语句,因此如果有人输入文本而不是整数,它会抛出 NumberFormatException 并打印一个“请引入一个有效的数字行”。我希望我的计算器循环回到第一个 System.out.println() 并在触发 NumberFormatException 时重新启动程序。我尝试使用布尔值通过 do/while 循环执行此操作,但无法使其正常工作。这是我的没有循环的计算器:

public class Application {
public static void main(String[] args) {
    System.out.println("Por favor introduce el importe de las ganancias en euros.");
    Scanner reader = new Scanner(System.in);
    int minimumAmount = 0;
    int lowerLimit1 = 5000;
    int higherLimit1 = 25000;
    int lowerLimit2 = 25000;
    int higherLimit2 = 55000;
    int lowerLimit3 = 55000;
    int higherLimit3 = 200000;
    int lowerLimit4 = 200000;
    int higherLimit4 = 1000000;
    int gains = Integer.parseInt(reader.nextLine());

    try {
        if (gains > minimumAmount && gains < lowerLimit1) {
            System.out.println("Tus ganancias están libres de impuestos.");
        } else if (gains >= lowerLimit1 && gains < higherLimit1) {
            float taxes = 8F;
            System.out.println("Tus ganancias han sido de " + (gains - lowerLimit1) + " euros. Por tanto, con un " + taxes + "% de impuestos tendrás que pagar " + ((gains - lowerLimit1) * (taxes / 100)) + " euros.");
        } else if (gains >= lowerLimit2 && gains < higherLimit2) {
            float taxes = 10F;
            System.out.println("Tus ganancias han sido de " + (gains - lowerLimit2) + " euros. Por tanto, con un " + taxes + "% de impuestos tendrás que pagar " + ((gains - lowerLimit2) * (taxes / 100)) + " euros.");
        } else if (gains >= lowerLimit3 && gains < higherLimit3) {
            float taxes = 12F;
            System.out.println("Tus ganancias han sido de " + (gains - lowerLimit3) + " euros. Por tanto, con un " + taxes + "% de impuestos tendrás que pagar " + ((gains - lowerLimit3) * (taxes / 100)) + " euros.");
        } else if (gains >= lowerLimit4 && gains < higherLimit4) {
            float taxes = 15F;
            System.out.println("Tus ganancias han sido de " + (gains - lowerLimit4) + " euros. Por tanto, con un " + taxes + "% de impuestos tendrás que pagar " + ((gains - lowerLimit4) * (taxes / 100) + " euros."));
        } else if (gains > higherLimit4) {
            float taxes = 17F;
            System.out.println("Tus ganancias han sido de " + (gains - higherLimit4) + " euros. Por tanto, con un " + taxes + "% de impuestos tendrás que pagar " + ((gains - higherLimit4) * (taxes / 100) + " euros."));
        }


    } catch (NumberFormatException e) {
        System.out.println("Por favor introduce un número válido.");
    }
}

这就是我尝试循环它的方式:

public class Application {
public static void main(String[] args) {
    System.out.println("Por favor introduce el importe de las ganancias en euros.");
    Scanner reader = new Scanner(System.in);
    int minimumAmount = 0;
    int lowerLimit1 = 5000;
    int higherLimit1 = 25000;
    int lowerLimit2 = 25000;
    int higherLimit2 = 55000;
    int lowerLimit3 = 55000;
    int higherLimit3 = 200000;
    int lowerLimit4 = 200000;
    int higherLimit4 = 1000000;
    int gains = Integer.parseInt(reader.nextLine());
    boolean isValid = true;

    do {
        try {
            if (gains > minimumAmount && gains < lowerLimit1) {
                System.out.println("Tus ganancias están libres de impuestos.");
            } else if (gains >= lowerLimit1 && gains < higherLimit1) {
                float taxes = 8F;
                System.out.println("Tus ganancias han sido de " + (gains - lowerLimit1) + " euros. Por tanto, con un " + taxes + "% de impuestos tendrás que pagar " + ((gains - lowerLimit1) * (taxes / 100)) + " euros.");
            } else if (gains >= lowerLimit2 && gains < higherLimit2) {
                float taxes = 10F;
                System.out.println("Tus ganancias han sido de " + (gains - lowerLimit2) + " euros. Por tanto, con un " + taxes + "% de impuestos tendrás que pagar " + ((gains - lowerLimit2) * (taxes / 100)) + " euros.");
            } else if (gains >= lowerLimit3 && gains < higherLimit3) {
                float taxes = 12F;
                System.out.println("Tus ganancias han sido de " + (gains - lowerLimit3) + " euros. Por tanto, con un " + taxes + "% de impuestos tendrás que pagar " + ((gains - lowerLimit3) * (taxes / 100)) + " euros.");
            } else if (gains >= lowerLimit4 && gains < higherLimit4) {
                float taxes = 15F;
                System.out.println("Tus ganancias han sido de " + (gains - lowerLimit4) + " euros. Por tanto, con un " + taxes + "% de impuestos tendrás que pagar " + ((gains - lowerLimit4) * (taxes / 100) + " euros."));
            } else if (gains > higherLimit4) {
                float taxes = 17F;
                System.out.println("Tus ganancias han sido de " + (gains - higherLimit4) + " euros. Por tanto, con un " + taxes + "% de impuestos tendrás que pagar " + ((gains - higherLimit4) * (taxes / 100) + " euros."));
            }


        } catch (NumberFormatException e) {
            System.out.println("Por favor introduce un número válido.");
            isValid = false;
        }
    } while (isValid != false);
}

有了这个循环,try 部分工作得很好,但是一旦我输入文本控制台就会抛出这个错误:

Exception in thread "main" java.lang.NumberFormatException: For input string: "text"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Integer.parseInt(Integer.java:660)
at java.base/java.lang.Integer.parseInt(Integer.java:778)
at Application.main(Application.java:209)

我做错了什么?

【问题讨论】:

  • 移动 int gains = Integer.parseInt(reader.nextLine()); 尝试阻止
  • 不会抛出错误但会结束程序@sanjeevRm
  • 检查更新的答案,您可以从用户输入中读取nextLong,避免字符串到数字的转换

标签: java loops exception java.util.scanner calculator


【解决方案1】:

你可以这样做。使用Scanner.nextInt() 并继续处理,直到您有有效的输入。

public static void main(String[] args) {
            boolean notValid = true;
            Scanner reader = new Scanner(System.in);
            int minimumAmount = 0;
            int lowerLimit1 = 5000;
            int higherLimit1 = 25000;
            int lowerLimit2 = 25000;
            int higherLimit2 = 55000;
            int lowerLimit3 = 55000;
            int higherLimit3 = 200000;
            int lowerLimit4 = 200000;
            int higherLimit4 = 1000000;
            int gains = 0;
            while (notValid) {
               try {
                  System.out.println("Por favor introduce el importe de las ganancias en euros.");
                  gains = reader.nextInt();
                  notValid = false;
               }  catch (InputMismatchException e) {
                  System.out.println("Por favor introduce un número válido.");
                  reader.nextLine(); // clear input buffer
               }
            }
           
            // rest of your code (conditionals and output) goes here.

您也可以将 try/catch 替换为以下内容:

while (notValid) {
    System.out.println("Por favor introduce el importe de las ganancias en euros.");
    if (reader.hasNextInt()) {
        gains = reader.nextInt();
        notValid = false;
    } else {
         System.out.println("Por favor introduce un número válido.");
        reader.nextLine(); // clear input buffer
    }
}

【讨论】:

  • 如果您有任何问题,请告诉我。
【解决方案2】:

您在 try/catch 之前收到 NumberFormatException ,您需要将 int gains = Integer.parseInt(reader.nextLine()); 移动到 try/catch 块,如下所示

do {
        try {
            int gains = Integer.parseInt(reader.nextLine());
            if (gains > minimumAmount && gains < lowerLimit1) {
                System.out.println("Tus ganancias están libres de impuestos.");
            } else if (gains >= lowerLimit1 && gains < higherLimit1) {
                float taxes = 8F;
                System.out.println("Tus ganancias han sido de " + (gains - lowerLimit1) + " euros. Por tanto, con un " + taxes + "% de impuestos tendrás que pagar " + ((gains - lowerLimit1) * (taxes / 100)) + " euros.");
            } else if (gains >= lowerLimit2 && gains < higherLimit2) {
                float taxes = 10F;
                System.out.println("Tus ganancias han sido de " + (gains - lowerLimit2) + " euros. Por tanto, con un " + taxes + "% de impuestos tendrás que pagar " + ((gains - lowerLimit2) * (taxes / 100)) + " euros.");
            } else if (gains >= lowerLimit3 && gains < higherLimit3) {
                float taxes = 12F;
                System.out.println("Tus ganancias han sido de " + (gains - lowerLimit3) + " euros. Por tanto, con un " + taxes + "% de impuestos tendrás que pagar " + ((gains - lowerLimit3) * (taxes / 100)) + " euros.");
            } else if (gains >= lowerLimit4 && gains < higherLimit4) {
                float taxes = 15F;
                System.out.println("Tus ganancias han sido de " + (gains - lowerLimit4) + " euros. Por tanto, con un " + taxes + "% de impuestos tendrás que pagar " + ((gains - lowerLimit4) * (taxes / 100) + " euros."));
            } else if (gains > higherLimit4) {
                float taxes = 17F;
                System.out.println("Tus ganancias han sido de " + (gains - higherLimit4) + " euros. Por tanto, con un " + taxes + "% de impuestos tendrás que pagar " + ((gains - higherLimit4) * (taxes / 100) + " euros."));
            }


        } catch (NumberFormatException e) {
            System.out.println("Por favor introduce un número válido.");
            isValid = false;
        }
    } while (isValid != false);

您可以通过将此增益类型更改为 long 并从扫描仪读取 long 来避免此数字格式异常

do {
  ...
  long gains = reader.nextLong();
  ...
} while(reader.hasNextLong());

【讨论】:

  • 如果您输入有效数字,它可以让您尽可能多次地使用计算器,但如果您输入文本或任何其他无效字符,catch 的System.out.println() 将被执行并且程序完成退出代码为 0。我希望它在输入无效字符时重新启动程序
  • 因为改成nextLong后不会出现NumberFormat异常,所以需要将行设置isValid从catch块中移出,改为检查reader.hasNextLong()
猜你喜欢
  • 2023-03-24
  • 2019-06-15
  • 2018-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多