Есть ли способ найти сложные проценты в java с входными данными с помощью JOptionPane? - PullRequest
1 голос
/ 17 июня 2020

Я пробовал использовать следующие входные данные:

основная сумма = 1000, ставка = 4, timesapplied = 2 (полугодие), прошедшие годы = 2

import javax.swing.*;
import java.math.BigDecimal;

public class CICalc {
    public static void main(String[] args) {
        Double principal;
        Double rate;
        Double timesapplied;
        Double elapsedyears;

        principal= Double.parseDouble(JOptionPane.showInputDialog("Enter the principal amount"));
        rate=Double.parseDouble(JOptionPane.showInputDialog("Enter the Rate of Interest"));
        timesapplied=Double.parseDouble(JOptionPane.showInputDialog("Enter the number of times the principal is compounded"));
        elapsedyears=Double.parseDouble(JOptionPane.showInputDialog("Enter the amount of time(In years and if in months, write them in this format- month/12) the principal is being invested for"));

        BigDecimal CI;
        BigDecimal inf;
        inf= BigDecimal.valueOf(Math.pow(rate+(1/timesapplied*100),elapsedyears*timesapplied));

        CI= (BigDecimal.valueOf(principal)).multiply(inf);
        BigDecimal P= CI.subtract(BigDecimal.valueOf(principal));

        JOptionPane.showMessageDialog(null,"The Compound Interest for "+elapsedyears+" years is "+CI+"$ and the the interest gained is "+P+"$");

    }
}

Может кто-нибудь указать на ошибки и помочь мне? На самом деле я сделал это, используя только Double, но проблема заключалась в том, что в результате было слишком много десятичных знаков. Поэтому мне пришлось использовать BigDecimal.

Ответы [ 2 ]

0 голосов
/ 17 июня 2020

На самом деле, я сделал это, используя только Double, но проблема заключалась в том, что в результате было слишком много десятичных знаков. Поэтому мне пришлось использовать BigDecimal.

Используйте BigDecimal setScale (int newScale, RoundingMode roundingMode) , чтобы округлить результат до необходимого количества десятичных знаков.

import java.math.BigDecimal;
import java.math.RoundingMode;

import javax.swing.JOptionPane;

class Main {
    public static void main(String[] args) {
        double principal = Double.parseDouble(JOptionPane.showInputDialog("Enter the principal amount"));
        double rate = Double.parseDouble(JOptionPane.showInputDialog("Enter the Rate of Interest"));
        double timesapplied = Double
                .parseDouble(JOptionPane.showInputDialog("Enter the number of times the principal is compounded"));
        double elapsedyears = Double.parseDouble(JOptionPane.showInputDialog("Enter the number of years"));

        double base = 1.0 + rate / (timesapplied * 100.0);
        double exponent = elapsedyears * timesapplied;

        double inf = Math.pow(base, exponent);
        double CI = principal * inf;
        double P = CI - principal;

        JOptionPane.showMessageDialog(null,
                "The Compound Interest for " + BigDecimal.valueOf(elapsedyears).setScale(2, RoundingMode.HALF_UP)
                        + " years is " + BigDecimal.valueOf(CI).setScale(2, RoundingMode.HALF_UP)
                        + "$ and the the interest gained is " + BigDecimal.valueOf(P).setScale(2, RoundingMode.HALF_UP)
                        + "$");
    }
}
0 голосов
/ 17 июня 2020

Ваша формула сложных процентов была неправильной. Формула :

final amount = initial amount times
    1 + interest rate / number of times interest applied
    raised to the power of number of times interest applied
    times number of time periods elapsed 

Процентная ставка, которая обычно определяется как процент в год, должна быть преобразована в число за период времени путем деления на 100 и деления на число. периодов времени в году.

Что касается вашего кода, я создал метод для получения входных значений.

Я также разбил расчет сложных процентов, чтобы я мог проверить результаты каждая часть расчета.

Вот исправленный код.

import java.text.NumberFormat;

import javax.swing.JOptionPane;

public class CICalc {
    public static void main(String[] args) {
        NumberFormat nf = NumberFormat.getCurrencyInstance();

        double principal = getValue("Enter the principal amount");
        double rate = getValue("Enter the yearly interest rate");
        double timesapplied = getValue("Enter the number of times "
                + "the principal is compounded per year");
        double elapsedmonths = getValue("Enter the amount of time "
                + "in months the principal is invested");

        double temp1 = 1.0d + rate * 0.01d / timesapplied;
        double temp2 = timesapplied * elapsedmonths / 12d;
        double finalAmount = principal * Math.pow(temp1, temp2);

        JOptionPane.showMessageDialog(null,
                "The total amount returned after " +
                elapsedmonths +
                " months is " + nf.format(finalAmount) +
                " and the the interest gained is " +
                nf.format(finalAmount - principal));
    }

    private static double getValue(String prompt) {
        String response = JOptionPane.showInputDialog(prompt);
        return Double.parseDouble(response);
    }
}
...