java - Getting a sum from ArrayList<Number> using non-loop recursion -


i working on lab assignment school , wondering if give me advice. instructor wants add different number objects array list , display result. wants addition in non-loop recursive format. i've done similar problem before integers, cannot seem solution because there more 1 primitive type time. here code have far:

main:

import java.math.biginteger; import java.util.arraylist;  public class testsummation {  public static void main(string[] args) {     arraylist<number> alist = new arraylist<number>();     alist.add(new integer(4));     alist.add(new double(3.423));     alist.add(new float(99.032));     alist.add(new biginteger("32432"));     double result = summation.sum(alist);     system.out.println(result);  }  } 

class holds recursive method:

import java.util.arraylist;  public class summation {  public static double sum(arraylist<number> alist) {      if (alist.size() < 1) {         return 0;     } else {         return sum(alist);     }  }  } 

right code throws stackoverflowexception , wondering if had advice me. know need add more it, feel i'm on right track current section of code. i'm hitting bad roadblock right now. in advance advice!

recursion works cons 2 different cases:

  • the base case used end recursion
  • the recursive case applied on specific n-th step

by thinking problem can consider base case either list of size 1 or list of size 0. let's choose first simplicity: the sum of values of list of size 1 value contained.

now let's recursive case: suppose list has length n. know the sum of elements of list of n elements n-th element added sum of list containing n-1 elements (by removing n-th element). it's pretty self explicatory of recursive implementations.

as can see recursive step reduces size of list algorithm step-by-step reaches base case, not happening code.


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -