鱼C论坛

 找回密码
 立即注册
查看: 1146|回复: 1

[已解决]java异常处理

[复制链接]
发表于 2023-12-8 15:45:10 | 显示全部楼层    本楼为最佳答案   
代码中存在以下问题:

1. 在NewLoan类的构造方法中,只是调用了judge()方法进行判断,但没有在该方法中抛出异常。应该在judge()方法中使用if条件判断,当满足条件时,抛出IllegalArgumentException异常。

2. 在Main类的main方法中,使用了错误的方法签名,应该使用String[] args而不是String args。

下面是修改后的代码:
  1. import java.util.Scanner;
  2. public class Main {
  3.     public static void main(String[] args) {
  4.         Scanner input = new Scanner(System.in);
  5.         while (input.hasNext()) {
  6.             double AIR = input.nextDouble();
  7.             int NOY = input.nextInt();
  8.             double LA = input.nextDouble();
  9.             try {
  10.                 NewLoan m = new NewLoan(AIR, NOY, LA);
  11.                 System.out.printf(m.printTotalPayment());
  12.                 System.out.printf("\n");
  13.             } catch (IllegalArgumentException ex) {
  14.                 System.out.println(ex.getMessage());
  15.             }
  16.         }
  17.     }
  18. }
  19. class NewLoan {
  20.     private double AIR;
  21.     private int NOY;
  22.     private double LA;
  23.     NewLoan(double air, int noy, double la) throws IllegalArgumentException {
  24.         this.AIR = air;
  25.         this.NOY = noy;
  26.         this.LA = la;
  27.         judge();
  28.     }
  29.     public void judge() throws IllegalArgumentException {
  30.         if (this.AIR <= 0) {
  31.             throw new IllegalArgumentException("Annual interest rate must be positive.");
  32.         }
  33.         if (this.NOY <= 0) {
  34.             throw new IllegalArgumentException("Number of years must be positive.");
  35.         }
  36.         if (this.LA <= 0) {
  37.             throw new IllegalArgumentException("Loan amount must be positive.");
  38.         }
  39.     }
  40.     public String printTotalPayment() {
  41.         double totalPayment = LA * Math.pow(1 + AIR / 100, NOY);
  42.         return "totalPayment is " + String.format("%.3f", totalPayment);
  43.     }
  44. }
复制代码

以上代码中,使用了私有变量来存储输入的年利率、年数和贷款总额,在judge()方法中进行判断,并抛出异常。printTotalPayment()方法计算总额,并返回格式化后的字符串。在Main类的main方法中,通过try-catch语句捕获异常并输出相应信息。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-9-28 05:43

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表