[JAVA] 3. Refactorización en Java

1. Refactorización

Para 贷款额度计算simplificar el procedimiento anterior y hacerlo más acorde con el principio de DRY.

Aquí, el número de entrada se extrae como una función, y luego el préstamo calculado se extrae como una función.

import java.util.Scanner;

public class Main {
    private static double getNumber(String prompt, double min, double max,Scanner scanner) {
        double value = 0;
        while (true) {
            System.out.print(prompt + ':');
            value = scanner.nextFloat();
            if (value > min && value < max)
                break;
            System.out.println("数据应当在" + min + " " + max + "之间。");
        }
        return value;
    }

    private static double getMortgage(float principle, float interest, byte years) {
        final byte MONTH = 12;
        final byte PERCENT = 100;
        float monthlyInterest = interest / MONTH / PERCENT;
        short numberOfMonth = (short) (MONTH * years);
        double mortgage = principle
                * monthlyInterest * Math.pow(1 + monthlyInterest, numberOfMonth)
                / (Math.pow(1 + monthlyInterest, numberOfMonth) - 1);
        return mortgage;

    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        float principle = (float)getNumber("请输入本金",1000,1_000_000,scanner);
        float interest = (float)getNumber("请输入年利率",1,2,scanner);
        byte years = (byte)getNumber("请输入贷款年限",5,20,scanner);
        double mortgage = getMortgage(principle,interest,years);
        System.out.println("月供为:"+mortgage);

    }
}

Al refactorizar más tarde, se encontrará con la situación en la que las dos funciones largas aparecen en múltiples funciones. En este momento, debemos colocar esta constante en la clase como una variable de clase. Por supuesto, tenga en cuenta que la función es estática, también Puede leer constantes estáticas. Luego, encontrará que los dos valores del mes y la tasa de interés mensual también se repiten, pero estos dos valores no se cambiarán en otras funciones, que son elementos independientes entre las funciones, por lo que, aunque se repitan, se pueden dejar sin cambios. (Por supuesto, desea usarlo como una variable dentro de la clase, pero al final, habrá más variables dentro de la clase).

Esto tendrá una mejor solución en la programación orientada a objetos posterior.

2. Imprima la cantidad restante (saldo) después del reembolso

import java.util.Scanner;

public class Main {
    final static byte MONTH = 12;
    final static byte PERCENT = 100;

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        float principle = (float) getNumber("请输入本金", 1000, 1_000_000, scanner);
        float interest = (float) getNumber("请输入年利率", 1, 2, scanner);
        byte years = (byte) getNumber("请输入贷款年限", 5, 20, scanner);

        double mortgage = getMortgage(principle, interest, years);
        System.out.println();
        System.out.println(" 贷 款 ");
        System.out.println("-------");
        System.out.println("月供为:" + mortgage);

        System.out.println();
        System.out.println(" 结 余 ");
        System.out.println("-------");
        for (short month = 1; month <= years * MONTH; month++) {
            double balance = getBalance(principle,interest,years,month);
            System.out.println(month+"月之后的结余: "+balance);
        }
    }

    private static double getNumber(String prompt, double min, double max, Scanner scanner) {
        double value = 0;
        while (true) {
            System.out.print(prompt + ':');
            value = scanner.nextFloat();
            if (value > min && value < max)
                break;
            System.out.println("数据应当在" + min + " " + max + "之间。");
        }
        return value;
    }

    private static double getBalance(
            float principle,
            float interest,
            byte years,
            short numberOfPaymentsMade
    ) {
        float monthlyInterest = interest / MONTH / PERCENT;
        short numberOfMonth = (short) (MONTH * years);
        double balance = principle
                * (Math.pow(1 + monthlyInterest, numberOfMonth) - Math.pow(1 + monthlyInterest, numberOfPaymentsMade))
                / (Math.pow(1 + monthlyInterest, numberOfMonth) - 1);
        return balance;
    }

    private static double getMortgage(float principle, float interest, byte years) {
        float monthlyInterest = interest / MONTH / PERCENT;
        short numberOfMonth = (short) (MONTH * years);
        double mortgage = principle
                * monthlyInterest * Math.pow(1 + monthlyInterest, numberOfMonth)
                / (Math.pow(1 + monthlyInterest, numberOfMonth) - 1);
        return mortgage;

    }
}

Supongo que te gusta

Origin www.cnblogs.com/modai/p/12669383.html
Recomendado
Clasificación