我试图返回我的数组的总和,但是我没有使用递归对数组求和,数组总和刚回来为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);
}
}
}
答案 0 :(得分:4)
在代码中,在填充数组之前调用函数sumDanceScore
。因此,您将一个填充了零的数组(作为默认值)传递给函数。
答案 1 :(得分:0)
如何解决:
first
初始化为零。sumDanceScore
递归如何适用于您的sumDanceScore
?
首先,为sumDanceScore
和first == 0
数组调用last == danceScore.length - 1
。然后,sumDanceScore
离开范围的初始元素(位于first
位置),并将移位的位置调用下一个sumDanceScore
。此first == 1
和此变量与第一次调用sumDanceScore
时不同。每次first
轮换,直到first
与last
匹配。
这是正确的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);