我需要帮助弄清楚如何返回从键盘输入的2d数组中所有数字的总和,这些数字可被3整除。我有我的计算和方法,它将正确返回一个测试用例,但是对于给定的每个案例它都没有正确计算。任何建议都会非常有帮助。我将加载我的代码,包括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 );
}
}
答案 0 :(得分:1)
// is startIndex really needed? you only ever use it unnecessarily, so, no.
public static int computeSumDivisibleBy3(int[] numbers, int startIndex, int endIndex){
// End condition, good, but the return value doesn't make any sense
// You always return the last one in the array, even it's not divisible by 3
//if (startIndex == endIndex)
// return numbers[endIndex];
// How about this instead (taking the removal of startIndex into consideration)
if( index == numbers.length - 1) {
return (numbers[index] % 3 == 0 ? numbers[index] : 0);
}
// now, on to regular operations
// all that's needed is to return the current element, or zero, plus the recursive result
return (numbers[index] % 3 == 0 ? numbers[index] : 0) + computeSumDivisibleBy3( numbers, ++index );
// or, if you'd prefer an if statement
int cur = 0;
if( current element % 3 is 0 ) {
cur = current element
}
return cur + recurse( numbers, ++index );
//else{
// int sum1 = computeSumDivisibleBy3(numbers, startIndex, endIndex-1);
// if (numbers[endIndex] % 3 == 0)
// return sum1 + numbers[endIndex];
// else
//return sum1;
}
}