我需要帮助来弄清楚如何返回从键盘输入的二维数组中所有数字的总和,这些数字可以被三整除。我有我的计算总和方法,可以正确返回一个测试用例,但是它不能正确计算给定的每个用例。任何建议都会非常有帮助。我将加载我的代码,包括 while 循环,以便更容易找到我计算错误的地方。
try
{
InputStreamReader stream = new InputStreamReader (System.in);
BufferedReader scan = new BufferedReader(stream);
inputParser = Integer.parseInt(input);
int i = 0;
while(inputParser != 0)
{
input = scan.readLine();
inputParser = Integer.parseInt(input);
if(inputParser == 0)
{
inputParser = 0;
}
else
{
numbers1[i] = inputParser;
i++;
}
}
sum = computeSumDivisibleBy3(numbers1,0,numbers1.length-1);
System.out.println("The sum of the numbers divisible by 3 is " + sum);
}
catch(NumberFormatException exception)
{
System.out.println("Please enter integers only");
}
这是计算可被3整除的总和的方法
//而不是这个原始方法,我在下面实现了你的方法,它正确返回
public static int computeSumDivisibleBy3(int[] numbers, int startIndex, int endIndex){
if (startIndex == endIndex)
return numbers[endIndex];
else{
int sum1 = computeSumDivisibleBy3(numbers, startIndex, endIndex-1);
if (numbers[endIndex] % 3 == 0)
return sum1 + numbers[endIndex];
else
return sum1;
}
}
//newly implemented code
public static int computeSumDivisibleBy3(int[] numbers, int startIndex, int endIndex){
if (startIndex == numbers.length-1)
return numbers[startIndex] % 3 == 0 ? numbers[startIndex] : 0;
else{
return (numbers[startIndex] % 3 == 0 ? numbers[startIndex] : 0) + computeSumDivisibleBy3( numbers, ++startIndex, endIndex );
}
}