I wanted to calculate static expression in java. something is wrong so I get the wrong answer. but I can’t figure out where is the problem.
”’
public static void main(String[] args) {
String input = "3x^2+4x^3+6";
// calculate the value when x is 3
String[] expression=input.split("\\+"); //spltting the expression in 3 parts
String[] firstpart=expression[0].split(""); //splitting every part
String[] secondpart=expression[1].split("");
String[] thirdpart=expression[2].split("");
int sum3=Integer.valueOf(thirdpart[0]);
int sum1=0;
int i=0;
while(i<firstpart.length){
if("^".equals(firstpart[i])){
sum1+=(Integer.valueOf(secondpart[i-2]))*(Math.pow(3,(Integer.valueOf(secondpart[i+1]))));
//3 * 3^2
}
i++;
}
int sum2=0;
int k=0;
while(k<secondpart.length){
if("^".equals(secondpart[k])){
sum2+=(Integer.valueOf(secondpart[k-2]))*(Math.pow(3,(Integer.valueOf(secondpart[k+1]))));
// 4 * 3^3
}
k++;}
System.out.println(sum1);
System.out.println(sum2);
System.out.println(sum3);
System.out.println(sum1+sum2+sum3);
}
”’
>Solution :
while(i<firstpart.length){
if("^".equals(firstpart[i])){
sum1+=(Integer.valueOf(secondpart[i-2]))*(Math.pow(3,(Integer.valueOf(secondpart[i+1]))));
//3 * 3^2
}
i++;
}
Here you loop with firstpart but use secondpart ‘s value, so it is the problem.