gpt4 book ai didi

Java 超出范围

转载 作者:行者123 更新时间:2023-12-01 12:20:07 25 4
gpt4 key购买 nike

除了一个问题之外,我的程序已基本完成。我遇到了 for 循环超出范围的问题。该计划的目标是根据用户输入的金额和期限计算复利。

3 年期本金 5000 美元、利息 5% 的产出示例如下:

Month:  Interest:   Principal:
1 $20.83 $5020.83
2 $20.92 $5041.75
etc etc etc

Starting Balance = $ 5000.00 // having problem outputting these w/ for-loop
Final Account Balance = $ 5807.36 // System.out.print keeps repeating multiple times
Total Interest Paid = $ 807.36 // but i can't use variables outside of loop

我的问题是,在 for 循环期间,每次程序执行循环时,我都会不断输出起始余额、最终余额和总利息。但是,如果我尝试在循环外部使用变量,它就会超出范围,如果我尝试在循环外部声明变量,我就无法在循环内部使用它们,因为它已经在构造函数中声明了。

有人能给我一些提示或建议吗?

我的代码:

    public class Calculator
{

public Calculator()
{
Scanner input = new Scanner(System.in);
boolean error = false;

while (!error){
System.out.print("Please input the following: principal, interest rate, term >> ");
double principal = input.nextDouble();
double interest_rate = input.nextDouble();
int term = input.nextInt();
String Month = input.next();


char dollar_sym = 36;

if (interest_rate <= 0 || term <= 0 || principal <= 0) // input validation
{
System.out.println("The term, interest rate and principal must be greater
than zero");
continue;
}
if (!Month.equals("month")) // input validation
{
System.out.println("Please input month after term");
continue;
}

System.out.println("Month: " + " Interest: " + "Principal: ");

if (Month.equals("month"))
{
for (int month = 1; month <= term; month++)
{
double interest = (principal * interest_rate / 100) / 12;
principal = principal + interest;

System.out.printf("%4d %c%5.2f %c%5.2f\n", month,
dollar_sym, interest, dollar_sym, principal );

double start_principal = principal - interest; // problem
double final_principal = principal; // problem
double total_interest = interest * interest_rate; // problem

System.out.println(" Starting balance = " + start_principal ); // problem
System.out.println("Final account balance = " + final_principal ); // problem
System.out.println("Total Interest Paid = " + total_interest); // problem
}
}
}
}
}

最佳答案

在循环开始之前声明它们,这样它们将存在于循环内部和循环之后:

double start_principal = 0;
double final_principal = 0;
double total_interest = 0;

Scanner input = new Scanner(System.in);
boolean error = false;

while (!error) {
// ...
}

// ...

关于Java 超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26726699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com