我的程序幾乎完成,除了一個問題。我在for循環中遇到了一個超出範圍的問題。該計劃的目標是綜合每月用戶輸入金額&期限的利息。Java超出範圍
在5000 $本金5%的輸出的例子爲3年利息爲:
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
}
}
}
}
}
看看這個[教程](http://www.cs.umd.edu/~clin/MoreJava/ControlFlow/block.html)。 – MarsAtomic 2014-11-04 02:29:48
謝謝,我會看看。 – Maxwell1222 2014-11-04 02:35:57