试图返回数组之和,方法调用错误

时间:2015-02-03 18:26:47

标签: java for-loop recursion methods

我试图返回我的数组的总和,但是我没有使用递归对数组求和,数组总和刚回来为0.我就是在那个地方,我想我可能会忽略一些东西。额外的一双眼睛会有所帮助。

public class JavaSandbox {

/**
 * @param args the command line arguments
 */
public static int sumDanceScore(int danceScore[], int first, int last)
{


  if (first > last) 
    {
      return 0;
    }
 else
    {
     int total = sumDanceScore(danceScore,first+1,last) + danceScore[first];
     return total;
    }
}
  public static void main(String[] args)
 {
    Scanner kbd = new Scanner(System.in);
    System.out.println("Enter number of contestants : ");

   int numContest = kbd.nextInt();
   int danceScore[] = new int[numContest + 1];
   int first = 0;
   int last = danceScore.length - 1;

   System.out.println("Enter dance scores: ");

  int numContestIndex;
  for (numContestIndex = 1; numContestIndex <= numContest; numContestIndex++) {
  danceScore[numContestIndex] = kbd.nextInt();
}

     int danceScoreTotal = sumDanceScore(danceScore, first, last);
     System.out.println("SUM DANCE SORE METHOD: "+danceScoreTotal);
     for(int danceScoreIndex = 1; danceScoreIndex <= danceScore.length-1; danceScoreIndex++)
  {
     int danceScoreShare = danceScore[danceScoreIndex] /  danceScoreTotal;
    System.out.println("DANCE SCORE SHARE "+danceScoreShare);
  }

}

}

2 个答案:

答案 0 :(得分:4)

在代码中,在填充数组之前调用函数sumDanceScore。因此,您将一个填充了零的数组(作为默认值)传递给函数。

答案 1 :(得分:0)

如何解决:

  • index first初始化为零。
  • 填写数组后
  • 函数sumDanceScore

递归如何适用于您的sumDanceScore

首先,为sumDanceScorefirst == 0数组调用last == danceScore.length - 1。然后,sumDanceScore离开范围的初始元素(位于first位置),并将移位的位置调用下一个sumDanceScore。此first == 1和此变量与第一次调用sumDanceScore时不同。每次first轮换,直到firstlast匹配。

这是正确的main正文:

Scanner kbd = new Scanner(System.in);
System.out.println("Enter number of contestants : ");

int numContest = kbd.nextInt();
int danceScore[] = new int[numContest + 1];
int first = 0;
int last = danceScore.length - 1;

System.out.println("Enter dance scores: ");

int numContestIndex;
for (numContestIndex = 1; numContestIndex <= numContest; numContestIndex++) {
    danceScore[numContestIndex] = kbd.nextInt();
}

int danceScoreTotal = sumDanceScore(danceScore, first, last);

System.out.println("SUM DANCE SORE METHOD: " + danceScoreTotal);