I hardly understand what you're doing or why, but here's the recursive solution.. Recursion is unnecessary and stack-dangerous, by the way. (
StackOverflowErrors are ugly). Using a StringTokenizer is also unnecessary. I've included two examples, one is Your way, and the other is My way.
Your Way (Recursive and using a StringTokenizer)
public static void main (String[] args) {
String IntegerString = "1 2 3 4 5 6 7 8 9 10";
StringTokenizer Tokenizer = new StringTokenizer (IntegerString);
int[] ints = new int[Tokenizer.countTokens()];
for (int i = 0; i < ints.length; i++)
try { ints[i] = Integer.parseInt (Tokenizer.nextToken()); }
catch (Exception ex) { ints[i] = 0; /* PARSE ERROR */ }
System.out.println ( "The sum of the integers is: " + Summarize (ints, ints.length) );
}
public static int Summarize (int[] ints, int curpos) {
return (--curpos > 0 ? Summarize (ints, curpos) : 0) + ints[curpos];
}
// OR
public static int Summarize2 (int[] ints, int curpos) {
if (--curpos < 0) return 0;
return ints[curpos] + Summarize (ints, curpos);
}
My Way (Quicker, Fewer imports, No recursion)
public static void main (String[] args) {
String IntegerString = "1 2 3 4 5 6 7 8 9 10";
String[] Tokens = IntegerString.split ("\\s+");
int[] ints = new int[Tokens.length];
for (int i = 0; i < ints.length; i++)
try { ints[i] = Integer.parseInt (Tokens[i]); }
catch (Exception ex) { ints[i] = 0; /* PARSE ERROR */ }
System.out.println ( "The sum of the integers is: " + Summarize (ints) );
}
public static int Summarize (int[] ints) {
int Total = 0;
for (int i : ints) Total += i;
return Total;
}
Last edited by Cudmore; Oct 6th, 2006 at 6:55 pm. Reason: Improvement
Reputation Points: 20
Solved Threads: 6
Junior Poster in Training
Offline 74 posts
since Nov 2005