Posted: Sat Nov 01, 2014 11:51 am Post subject: RE:java.lang.StackOverflowError?
oh i see, and im not allowed to use stacks, i have to replace stacks with recursion. The only thing is that numIndex and operIndex doesnt control what char to look at. My program keeps skipping the math operation char and the ) char no matter what expression i input. I modified the function again, this time, it recognises the ) but it skips the 2nd number and the operator.
code:
public static double evaluate(String s, int i, int charIndex)
{
double[] numbers = new double[3] ;
Character[] operations = new Character[1];
String next = "";
int length = s.length();
char first;
int numIndex = i;
if (charIndex < length)
{
System.out.println(" Index: " + charIndex);
if (Character.isDigit(s.charAt(charIndex)) || s.charAt(charIndex) == '.' ){
next = ""+ next + "" + s.charAt(charIndex);
System.out.println("Char" + next + " Index: " + charIndex);
if (Character.isDigit(s.charAt(++charIndex)) || s.charAt(++charIndex) == '.'){
evaluate(s, numIndex, ++charIndex);
}
numbers[numIndex]=(Double.parseDouble(next));
++numIndex;
}else{
first = s.charAt(charIndex);
System.out.println("Char" + first + " Index: " + charIndex);
switch (first)
{
case '+': // Addition
case '-': // Subtraction
case '*': // Multiplication
case '/': // Division
operations[0] = first;
System.out.println("operation");
break;
case ')': // Right parenthesis
System.out.println("end");
numbers[2] = evaluateStackTops(numbers, operations);
break;
case '(': // Left parenthesis
break;
default : // Illegal character
throw new IllegalArgumentException("Illegal character");
}
}
evaluate(s, numIndex, ++charIndex);
}
if (numbers.length != 3)
throw new IllegalArgumentException("Illegal input expression");
return numbers[2];
}
Sponsor Sponsor
C14
Posted: Sat Nov 01, 2014 12:23 pm Post subject: RE:java.lang.StackOverflowError?
evaluate(s, numIndex, ++charIndex);
reduce it down to one recursive call. Recursion has an
'unwinding' effect.
The number is complete when you hit an operator or a right
parenthesis. That's when the number should be stored.
Usually loops are replaced with recursion.
a22asin
Posted: Sat Nov 01, 2014 12:29 pm Post subject: Re: RE:java.lang.StackOverflowError?
C14 @ Sat Nov 01, 2014 12:23 pm wrote:
evaluate(s, numIndex, ++charIndex);
reduce it down to one recursive call. Recursion has an
'unwinding' effect.
The number is complete when you hit an operator or a right
parenthesis. That's when the number should be stored.
.