|
发表于 2023-12-8 15:45:10
|
显示全部楼层
本楼为最佳答案
 代码中存在以下问题:
1. 在NewLoan类的构造方法中,只是调用了judge()方法进行判断,但没有在该方法中抛出异常。应该在judge()方法中使用if条件判断,当满足条件时,抛出IllegalArgumentException异常。
2. 在Main类的main方法中,使用了错误的方法签名,应该使用String[] args而不是String args。
下面是修改后的代码:
- import java.util.Scanner;
- public class Main {
- public static void main(String[] args) {
- Scanner input = new Scanner(System.in);
- while (input.hasNext()) {
- double AIR = input.nextDouble();
- int NOY = input.nextInt();
- double LA = input.nextDouble();
- try {
- NewLoan m = new NewLoan(AIR, NOY, LA);
- System.out.printf(m.printTotalPayment());
- System.out.printf("\n");
- } catch (IllegalArgumentException ex) {
- System.out.println(ex.getMessage());
- }
- }
- }
- }
- class NewLoan {
- private double AIR;
- private int NOY;
- private double LA;
- NewLoan(double air, int noy, double la) throws IllegalArgumentException {
- this.AIR = air;
- this.NOY = noy;
- this.LA = la;
- judge();
- }
- public void judge() throws IllegalArgumentException {
- if (this.AIR <= 0) {
- throw new IllegalArgumentException("Annual interest rate must be positive.");
- }
- if (this.NOY <= 0) {
- throw new IllegalArgumentException("Number of years must be positive.");
- }
- if (this.LA <= 0) {
- throw new IllegalArgumentException("Loan amount must be positive.");
- }
- }
- public String printTotalPayment() {
- double totalPayment = LA * Math.pow(1 + AIR / 100, NOY);
- return "totalPayment is " + String.format("%.3f", totalPayment);
- }
- }
复制代码
以上代码中,使用了私有变量来存储输入的年利率、年数和贷款总额,在judge()方法中进行判断,并抛出异常。printTotalPayment()方法计算总额,并返回格式化后的字符串。在Main类的main方法中,通过try-catch语句捕获异常并输出相应信息。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|