简体   繁体   English

Java超出范围

[英]Java out of scope

My program is nearly done except for one problem. 除了一个问题,我的程序几乎完成了。 I'm having an out of scope problem with the for loop. 我在for循环中遇到范围外的问题。 The goal of the program is to compound monthly interest for a user inputted amount & term. 该计划的目标是使用户输入的金额和期限的每月利息增加。

An example of output at $5000 principal with 5% interest for 3 years would be: 以3年期,利率为5%的本金$ 5000计算的输出示例为:

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

My problem is that during my for loop, I keep outputting Starting Balance, Final Balance and Total Interest every time the program goes through the loop. 我的问题是在我的for循环中,每次程序执行循环时,我都会一直输出“ 起始余额”,“最终余额”和“总利息 ”。 but if I try to use the variables outside the loop it goes out of scope and if I try to declare variables outside of the loop I can't use them inside the loop because it's already been declared in the constructor. 但是,如果我尝试在循环外使用变量,则超出范围;如果我尝试在循环外声明变量,则无法在循环内使用变量,因为它已在构造函数中声明。

Can anyone give me some hints or advice? 谁能给我一些提示或建议?

My code: 我的代码:

    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
           } 
         }
       }
     }
   }

Declare them before the loop begins, so they will exist inside the loop and after it: 在循环开始之前声明它们,以便它们将在循环内部及其之后存在:

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

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

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

// ...

In my answer, I am assuming that when you say goes out of scope , you mean that you get a compile time error. 在我的回答中,我假设当您说goes out of scope ,您的意思是您遇到了编译时错误。 (note, it would make the answer easier to address if you provided the error message and the line that is causing the error message). (请注意,如果您提供了错误消息和引起错误消息的行,它将使答案更容易解决)。

The scope of a variable refers to where the variable is accessible. 变量的范围是指在哪里可以访问该变量。 For example, if you declare a variable inside of an if statement, the scope is that if statement. 例如,如果你声明的内部的一个变量if声明,范围是 if声明。 Some example code: 一些示例代码:

public void updateStatus(){
    Boolean shouldCheckStatus = true;//this variable is declared inside of the updateStatus method, so that is the scope of the variable
    if(shouldCheckStatus == true){
        Int hitCounter = 0;//this variable is declared inside of the if statement, so it is only accessible inside of the if statement
        //do some work
        if(hitCounter > 100){
            self.registerHits(hitCounter);//hitCounter is still accessible here, because it is still inside of the if statement
        }
        else{
            shouldCheckStatus = false;
        }
    }//close the if statement and so close the scope...
    //the hitCounter variable is no longer in scope, because we are no longer in the if statement
    //but shouldCheckStatus is still in scope, because we are still in the method
    if(shouldCheckStatus == true){
       self.callAnotherMethod();
    }
}

So in your problem, you need to declare your variable above where you want to use it, inside of the scope that you want to use it. 因此,在您遇到的问题中,您需要在要使用它的范围内,在要使用它的位置上方声明变量。 And then not declare it again. 然后不再声明。 So declare before the loop. 因此在循环之前声明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM