Note that there are some explanatory texts on larger screens.

plurals
  1. POCalculate sum divisible by 3 using recursion
    primarykey
    data
    text
    <p>I need help in figuring out how to return the sum of all numbers in a 2d array entered from a keyboard which are divisible by three. I have my compute sum method that will return one test case correctly, however it does not calculate correctly for every case given. Any suggestions would be very helpful. I will load my code including the while loop to make it easier to find where I am calculating wrong.</p> <pre><code>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"); } </code></pre> <p>here is the method to calculate the sum divisible by 3</p> <p>//instead of this original method, I've implemented yours just below this and it returns correctly</p> <pre><code>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 ); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload