【问题标题】:Using methods to calculate account balance使用方法计算账户余额
【发布时间】:2018-01-28 23:03:07
【问题描述】:

我正在尝试返回考虑了年数、账户金额和利率的银行余额。但是,当我编译程序时,我在 return 语句中收到错误。当我尝试将 return 放在循环之外时,我得到另一个错误。

循环中:

Exercise3.java:35: error: missing return statement

循环外:

Exercise3.java:34: error: cannot find symbol
}return sum;
        ^
symbol:   variable sum
location: class Exercise3
1 error

代码如下

import java.util.Scanner;//import scanner class


public class Exercise3{//Name of prograsm

    public static void main(String args[]){ //declare main method

        Scanner sc = new Scanner(System.in);//Declare the scanner method

        System.out.println("How much in in your account?");//ask user for balance details 
        double accBalance = sc.nextDouble();//Store balance details

        System.out.println("how many years are you saving? "); //ask the user for how many years they will be saveing
        double yrSaving = sc.nextDouble();// Amount of years stored

        System.out.println("What is the yearly interest rate ?");//ask the user for the interest rate
        double rateInterest = sc.nextDouble();//store the interest rate

        double results = balanceAccount(accBalance, yrSaving, rateInterest);//invoke the methofd
        System.out.println(results); //print thte  results of the method 
    }

////////////////////////////////////////////////////////////////////////////////
//Calculate the balance of the account method

    public static double balanceAccount(double accBalance, double yrSaving, double rateInterest){

        double rate = rateInterest / 100;

        for(int x = 0; x <= yrSaving; x++){

            double sum = accBalance*rate;
            return sum;
        }
    }
}

【问题讨论】:

  • 我建议你离开你的电脑,手动做一些例子。完成后,向你的妈妈或室友或其他人解释如何进行计算。现在用文字写下你是如何做到这一点的。然后将您的话与您在此处的代码进行比较。这些词与您的代码的作用相符吗?

标签: java methods


【解决方案1】:

将此作为您方法的主体。你的问题是你没有在每种情况下都返回。你的sum 逻辑也有问题。

 double rate = rateInterest / 100;
 double sum = 0;
 for(int x = 0; x <= yrSaving; x++){
   sum += accBalance * rate;
 }
 return sum;

【讨论】:

  • 这仍然不能正确计算复利。
  • @Code-Apprentice 这不需要回答他的问题,也没有被问到。这是一道数学题,这里的问题是修正错误。
  • 是的。因此,我在答案下方的评论解释了解决此类问题所需的基本技能。
【解决方案2】:

我就是这样做的

public static double balanceAccount(double accBalance, double yrSaving, double rateInterest){

double rate = rateInterest / 100;
double sum = 0;
double finishAmt = 0;

    sum += accBalance * rate;

    finishAmt = sum * yrSaving +(accBalance);
    return finishAmt;
}

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-31
    相关资源
    最近更新 更多