从文本文件中获取数字的总和

时间:2013-11-06 01:43:32

标签: java

文字档案:

2 3
5 5
6 6
3 4
3 4
4 5
5 6
3 3
4 5

对于学校来说,我们必须做的一个项目的一部分是得到“所有洞的最高得分总和”。基本上,程序必须从上面的文本文件中读取,并且必须显示哪一行具有最高总和。例如,第1行的总和为5,第2行的总和为10,等等。输出应为“12”,因为第3行的总和最高。

我尝试做的是创建两个变量:currentSumScoresumScorescurrentSumScore是一项测试,sumScores将包含最高金额。

for (int roundNum = 1; roundNum <= 9; roundNum++)
{               
    player1Score = in.nextInt();
    player2Score = in.nextInt();

    currentSumScore = player1Score + player2Score;
    if (currentSumScore >= player1Score + player2Score)
    {
        sumScores = currentSumScore;
    }

    else
    {
        sumScores = player1Score + player2Score;    
    }
}

我在这里尝试的是添加第一行的前两个数字并将其设置为currentSumScore。然后,我输入了一个if-else。如果第2行的总和大于第1行,则十sumScores将替换为第1行。我试过这个,但它只返回最后一行的总和。

3 个答案:

答案 0 :(得分:1)

currentSumScore = player1Score + player2Score;
    if (currentSumScore >= player1Score + player2Score)

您将currentSumScore设为player1Score + player2Score的总和,因此当它检查if条件时,它将始终为true。您需要将当前总和与之前找到的较大值进行比较。

currentSumScore = player1Score + player2Score;
if (currentSumScore >= sumScores )
{
    //Actual sum is greater than previous
    sumScores = currentSumScore;
}

else
{
    //Do nothing, this line is not greater than one found before
    //This else is not needed
}

从一个小值的sumScores开始,所以第一行总是更大(0,-1 ......)

答案 1 :(得分:0)

currentSumScore = player1Score + player2Score; if (currentSumScore >= player1Score + player2Score)

您正在设置currentSumScore = player1Score + player2Score

然后你说是否是&gt;或=到。它总是等于它之前的线。

在阅读任何分数之前先从currentSumScore = 0开始,然后检查player1Score + player2Score是否为&gt;,而不是&gt; =。

答案 2 :(得分:0)

您必须检查

中保存的最后一个值
  

sumScores

if (currentSumScore > sumScores) {
     sumScores = currentSumScore;
}

没有必要分开。尝试一下,它应该可以工作。

相关问题