Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6130355
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T16:50:55+00:00 2026-05-23T16:50:55+00:00

I have written a Java program which evaluates a mathematical expression from left to

  • 0

I have written a Java program which evaluates a mathematical expression from left to right (no precedence, just left to right). However, I’m not getting the desired output.

import java.util.*;      
public class Evaluation {              
    //private static final char[] validOperators = {'/','*','+','-'};      
    private Evaluation() 
    {
        /* Using a private contructor to prevent instantiation
           Using class as a simple static utility class
         */
    }

    private static int evaluate(String leftSide, char oper, String rightSide)
            throws IllegalArgumentException
    {
        System.out.println("Evaluating: " + leftSide +  " (" + oper + ") " + rightSide);
        int total = 0;
        int leftResult = 0;
        int rightResult = 0;
        String originalString =leftSide;
        int operatorLoc  = findOperatorLocation(leftSide);
        leftSide = leftSide.substring(0,operatorLoc);
        rightSide = originalString.substring(operatorLoc+1,operatorLoc+2);
        String remainingString = originalString.substring(operatorLoc+2,originalString.length());

        System.out.println("leftSide -->"+leftSide);
        System.out.println("rightSide -->"+rightSide);
        System.out.println("remainingString --->"+remainingString);

        try {
            leftResult = Integer.parseInt(leftSide);
        } catch(Exception e) {
            throw new IllegalArgumentException(
                "Invalid value found in portion of equation: "
                + leftSide);
        }

        try {
            rightResult = Integer.parseInt(rightSide);
        } catch(Exception e) {
            throw new IllegalArgumentException(
                "Invalid value found in portion of equation: "
                + rightSide);
        }

        System.out.println("Getting result of: " + leftResult + " " + oper + " " + rightResult);
        switch(oper)
        {
        case '/':
            total = leftResult / rightResult; break;
        case '*':
            total = leftResult * rightResult; break;
        case '+':
            total = leftResult + rightResult; break;
        case '-':
            total = leftResult - rightResult; break;
        default:
            throw new IllegalArgumentException("Unknown operator.");
        }

        System.out.println("Returning a result of: " + total);
        String totally = String.valueOf(total)+remainingString;
        return evaluate(totally,findCharacter(totally),remainingString);
    }

    private static int findOperatorLocation(String string) {
        int index = -1;         
        index = string.indexOf(string.substring(1,2));
        if(index >= 0) {
            return index;
        }
        return index;
    }

    private static char findCharacter(String string) {
        char c='\u0000';  
        int index = -1;         
        index = string.indexOf(string.substring(1,2));
        if(index >= 0){             
            c = string.charAt(index);
            return c;
        }                       
        return c;   
    }

    public static int processEquation(String equation)
        throws IllegalArgumentException
    {
        return evaluate(equation,'+',"0");
    }

    public static void main(String[] args)
    {
        //String usage = "Usage: java MathParser equation\nWhere equation is a series"
        // + " of integers separated by valid operators (+,-,/,*)";

        //if(args.length < 1 || args[0].length() == 0)
        // System.out.println(usage);
        Scanner input = new Scanner(System.in); 
        System.out.print("Enter the equation to be evaluated ");

        String equation = (String)input.next();
        int result = Evaluation.processEquation(equation);
        System.out.println("The result of your equation ("
            + equation + ") is: " + result);

        //catch(IllegalArgumentException iae)
        //{
        //  System.out.println(iae.getMessage() + "\n" + usage);
        //}
    }
}

Here is the input I’m trying to use, and what I expect:

3+5*2-5
=>8*2-5
=>16-5
=>Expected Output :11

But I’m getting this output:

Enter the equation to be evaluated 3+5*2-5
Evaluating: 3+5*2-5 (+) 0
leftSide –>3
rightSide –>5
remainingString —>*2-5
Getting result of: 3 + 5
Returning a result of: 8
Evaluating: 8*2-5 (*) *2-5
leftSide –>8
rightSide –>2
remainingString —>-5
Getting result of: 8 * 2
Returning a result of: 16
Evaluating: 16-5 (6) -5
leftSide –>1
rightSide –>-
remainingString —>5
Exception in thread “main” java.lang.IllegalArgumentException: Invalid value found in portion of equation: –
at Evaluation.evaluate(Evaluation.java:49)
at Evaluation.evaluate(Evaluation.java:70)
at Evaluation.evaluate(Evaluation.java:70)
at Evaluation.processEquation(Evaluation.java:98)
at Evaluation.main(Evaluation.java:112)

I’m unable to make my program generic for any equation entered.
I appreciate any help you can provide.
Please note this is not a homework question.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T16:50:56+00:00Added an answer on May 23, 2026 at 4:50 pm

    Your findOperatorLoc is incorrect.

    It automatically assumes that the operator is the second character.

    index = string.indexOf(string.substring(1,2));
    

    EDIT — A cleaner implementation of this might be like so. split your equation based on operators and then based on operands. You will be left with 2 arrays , one with all the operators and one with all operands.

                String[] aa = op.split("[*+-]");
                for ( String s : aa )
                        System.out.println(s);
                String[] bb = op.split("[0-9]");
                for ( String s : bb )
                        System.out.println(s);
    
                // Now loop through the operand array and apply the necessary oeprator in order
                for ( int i = 0 ; i < aa.length ; i++ ) {
                          int val = applyOperator(Integer.parseInt(aa[i]), Integer.parseInt(aa[i+1]), bb[i]);
                }
    

    This is pseudocode only .. I will leave you to implement the applyOperator method

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a program which i have myself written in java, but I want
I have written a java program named Automate.java, in which the another java program
I have written the java code below, which executes another java program named Newsworthy_RB.
I'm modifying a java program which was written in 2004 using javaw.exe from J2re1.4.2_03.
i have written a java program which currently runs as a desktop app, it
I have written a program which reads input from csv file and its working
I have a program written in Java using JOGL with which you can draw
I've written a Java program which scrapes some content from a web page. It
I have written a program in Java which creates a socket connection for a
I have written a java program which needs to process thousands of text files

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.