Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

calculating static expression in java

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);

}
”’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading