Java передать массив в метод для расчета и вернуть массив - PullRequest
0 голосов
/ 02 апреля 2012

Я натолкнулся на этот пост " передать массив методу Java " о том, как передать массив методу, однако при попытке адаптировать его к моему калькулятору интереса у меня возникли ошибки, такие как "theОператор / не определен для типов аргументов double [], double ", и я не могу его разрешить.Я также надеюсь вернуть весь массив, так как мне нужно распечатать результаты позже и в конечном итоге отсортировать их.

Например, я определяю свои массивы и их размеры, а затем обращаюсь к пользователю с просьбой ввести сумму кредита, проценты и рассчитанную частоту.После того, как я получу данные и их все в формате массива, я затем вычеркну целые массивы, чтобы вычислить простой процент, и хочу вернуть результаты в виде массива, а затем передам те же начальные массивы, чтобы найти сложный процент по месяцу, неделе и днюно я получаю ранее упомянутую ошибку, когда он пытается выполнить деление, связанное с "A = P (1+ (r / n)) ^ (n * t)" Сбор данных работает нормально, я просто не могу правильно передать массивы илиперебирайте их, как только я это сделаю, ЕСЛИ я передаю их правильно

Любая и вся помощь приветствуется как всегда.

Relevent code

вызов данных от пользователя

do {
        arrPrincipalAmt[i] = getPrincipalAmount();
        arrInterestRate[i]= getInterestRate();
        arrTerm[i] = getTerm();
        i++;
        if (i < 4)
        {
          /*
           * if "i" comes to equal 4 it is the last number that will fit in the array of 5
           * and will Skip asking the user if they want to input more
           */

          System.out.println("Enter another set of Data? (Yes/No):");
          boolean YN = askYesNo();
          if (YN == true)
          {
            more = true;
          }
          else if (YN == false)
          {
            more=false;
          }
        }
        else
        {
          more = false;
        }
      }while(more);


      while (run)
      {

        //Start calculations call methods
        final int dINy = 365; //days in year
        final int mINy = 12; //months in year
        final int wINy = 52; //weeks in year
        double loanYears =(double) arrTerm[i]/mINy; //convert loan months into fraction of years, or whole years with decimals.
        arrSimple= calculateSimpleInterest(arrPrincipalAmt, arrInterestRate,loanYears);
        //Simple IntrestloanAmount * (annualInterestRate/100.0) * loanYears;
        arrCompoundMonthly = calculateCompundInterest(arrPrincipalAmt, arrInterestRate,mINy,loanYears);
        //rewrite month compound:loanAmount * Math.pow((1+((annualInterestRate/100)/mINy)),(loanYears*mINy)) - loanAmount;

простой процент, который не удается

public static double[] calculateSimpleInterest(double[] arrPrincipalAmt, double[] arrInterestRate, double Years)
  {
    for(int i=0; i<arrPrincipalAmt.length; i++)
    {
      double simpInterest= arrPrincipalAmt[i] * (arrInterestRate[i]/100.0) * Years; //Simple Interest Calculation
    }
    return simpInterest;
  }

сложный процент, который не удается

 public static double[] calculateCompundInterest(double[] arrPrincipalAmt, double[] 

arrInterestRate, double frequency, double time)
  {
    /*The Compound Interest calculation formation is as follows:A = P(1+ (r/n))^(n*t) - P
     A = total interest amount only.
     P = principal amount (loan amount or initial investment).
     r = annual nominal interest rate (as a decimal not a percentage).
     n = number of times the interest is compounded per year.
     t = number of years (don't forget to convert number of months entered by user to years).
     */
    for (int i=0; i < arrPrincipalAmt.length; i++)
    {
      double[] compound= arrPrincipalAmt[i] * Math.pow((1+(arrInterestRate[i]/100.0)/frequency),(frequency*time)) - arrPrincipalAmt[i]; //Compound Interest  monthly, weekly and daily depending on the frequency passed
    }
    return compound;
  }

Ответы [ 2 ]

3 голосов
/ 02 апреля 2012

Если вы получаете сообщение об ошибке типа the operator / is undefined for the argument types double[],double, это означает, что вы пытаетесь разделить весь массив по значению, а не по одному элементу.

Изменить строку как myarray / value на myarray[i] / value

1 голос
/ 02 апреля 2012

Я проверил ваш код, и проблема в том, что в строке 227 вы определяете состав как двойной массив, в то время как результат выражения в этой строке просто двойной.Я думаю, что вы хотите сделать это:

double[] compound = new double[arrPrincipalAmt.length];

for (int i=0; i < arrPrincipalAmt.length; i++) {
    compound[i] = arrPrincipalAmt[i] * Math.pow((1+(arrInterestRate[i]/100.0)/frequency),(frequency*time)) - arrPrincipalAmt[i];
}

return compound;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...