I want to use recursion in order to collapse the overridden add()
methods in the code and allow the user to provide any number of terms.
I've made a couple of changes to my code, but I'm not getting the desired result.
Examples of user input and expected output.
Output (for input 3 4
)
7.0
Output (for input 3 4 5
)
12.0
The code I have:
import java.util.*;
public class Recursion {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
String exp = input.nextLine();
System.out.println(solver(exp.split(" ")));
}
public static double solver(String[] expression) {
double result = 0;
if (expression.length == 3) {
result = add(Double.parseDouble(expression[0]), Double.parseDouble(expression[2]));
}
else if (expression.length == 5) {
result = add(Double.parseDouble(expression[0]), Double.parseDouble(expression[2]),
Double.parseDouble(expression[4]));
}
else if (expression.length == 7) {
result = add(Double.parseDouble(expression[0]), Double.parseDouble(expression[2]),
Double.parseDouble(expression[4]), Double.parseDouble(expression[6]));
}
else if (expression.length == 9) {
result = add(Double.parseDouble(expression[0]), Double.parseDouble(expression[2]),
Double.parseDouble(expression[4]), Double.parseDouble(expression[6]),
Double.parseDouble(expression[8]));
}
else if (expression.length == 11) {
result = add(Double.parseDouble(expression[0]), Double.parseDouble(expression[2]),
Double.parseDouble(expression[4]), Double.parseDouble(expression[6]),
Double.parseDouble(expression[8]), Double.parseDouble(expression[10]));
}
return result;
}
public static double add(double a, double b) {return a b;}
public static double add(double a, double b, double c) {return a b c;}
public static double add(double a, double b, double c, double d) {return a b c d;}
public static double add(double a, double b, double c, double d, double e) {return a b c d e;}
public static double add(double a, double b, double c, double d, double e, double f) {return a b c d e f;}
}
CodePudding user response:
You are not passing the correct indexes to the various add methods. For example, if you want to add three numbers, you should do the following:
result = add(Double.parseDouble(expression[0]), Double.parseDouble(expression[1]), Double.parseDouble(expression[2]));
CodePudding user response:
That's doable with recursion.
But before diving into recursive implementation, it's worth to find out how to solve this problem iteratively because it'll give you a better understanding of what the recursion does.
Firstly, I want to point out at issues with the code you've provided.
Your existing solution is brittle since it depends on the consistency of the user input, and it will fail because of the single additional white space or if a white space will be missing.
Another draw-back is that you have a lot of methods and with them, you are able to handle only a limited number of arguments in the given expression. Let's fix it.
Since your code is intended to perform the arithmetical addition, I think it'll be better to split the input on the plus symbol
and give a user a bit of freedom with white spaces.
For that, we need to pass the following regular expression into the split()
method:
"\\s*\\ \\s*"
- \s* - implies
0
or more white spaces; - \ - plus symbol has a special meaning in regular expressions and needs to be escaped with a back-slash.
And since there's more than one arithmetical operation (and you also might want to implement others letter on). It's better to extract your the logic for splitting the user input into a separate method:
public static double add(String expression) {
return addIteratively(expression.split("\\s*\\ \\s*"));
}
expression.split()
will return an array of numeric strings that will allow to substitute all your methods with a single method that expects a string array String[]
or varargs String... expression
(which will allow you to pass as an argument either an array of strings or arbitrary number of string values).
public static double addIteratively(String[] operands) {
double result = 0;
for (String next: operands) {
result = Double.parseDouble(next);
}
return result;
}
Now, when it's clear how to deal with this task iteratively (remember every problem and could be addressed using iteration is also eligible for recursion and vice versa) let's proceed with a quick recap on recursion.
Every recursive method consists of two parts:
- Base case - that represents a simple edge-case (condition when recursion terminates) for which the outcome is known in advance.
- Recursive case - a part of a solution where recursive calls are made and where the main logic resides.
To process the given array recursively, we can track the position in the array by passing it with each method call.
The base case will represent a situation when there's no more elements left in the array, i.e. current position is equal to the array's length. Since there's no element under the given position, the return is 0
.
In the recursive case we need to parse the number under the current position and add the result of the recursive call with position incremented by 1
to it. That will give us the return value.
The recursive implementation might look that:
public static double addAsDouble(String[] operands, int pos) {
if (pos == operands.length) { // base case
return 0;
}
// recursive case
return Double.parseDouble(operands[pos]) addAsDouble(operands, pos 1);
}
Method responsible for splitting the user input.
public static double add(String expression) {
return addAsDouble(expression.split("\\s*\\ \\s*"), 0); // recursion starts at position 0
}
main()
- here, you just need to call the add()
providing a string inter by the user and bother of what is happening inside add. That makes code cleaner and easier to read.
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
String exp = input.nextLine();
System.out.println(add(exp));
}
Output
3 4 5
12.0