Question

Hello, I'm having trouble with this certain part to a project of mine. Say I have two strings, String left and String right. This is part of an expression evaluation problem, and I need to have a certain piece of the expression in left and a certain piece of the expession in right. The code I have works with everything except if * or / come before + or -. No parentheses included, I have another method that deals with that. Say I have 2+3*3, using my code yoy get 11 which is correct. But if you have 3*3+2, it gives 15 (adding before multiplying). I know why it doesn't work, but I can't seem to fix it, I always end up with a stringoutofbounds exception.

So for example: 2+3*3 String left = 2 String right = 3*3 operation = +

Another example: 8*4-2 String left = 8*4 String right = 2 operation = -

Any help would be greatly apprecited

60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 string left String right char operator float result No parentheses or arrays in mind s. length i++) for int i if (i+1 s length l I i+2 s.length()) f break if (s char t (i-1) l I s charAt (i+1) left s. substring (0, i+1); right s substring (i+2, s. length operator s.charAt (i+1); break else if (s.charAt(i+1) I I S. Char (i+1) left s substring (0, i+1 right s. substring it s length s.charAt it operator break

EDIT: I solved this myself, thanks anyway if anyone was going to help.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Hi Friend, Please find my approach to solve Infix directly if it does not contains brackets.

NOTE: all operators and operands should be separated by a space.

import java.util.Scanner;

public class InfixEvaluation {

   public static double computeInfixExpr(String input) {

       String[] expr = input.split(" ");

       int i = 0;

       double operLeft = Integer.valueOf(expr[i++]);

       while (i < expr.length) {

           String operator = expr[i++];

           double operRight = Double.valueOf(expr[i++]);

           switch (operator) {

           case "*":

               operLeft = operLeft * operRight;

               break;

           case "/":

               operLeft = operLeft / operRight;

               break;

              

           case "+":  

           case "-":

               while (i < expr.length) {

                   String operator2 = expr[i++];

                   if (operator2.equals("+") || operator2.equals("-")) {

                       i--;

                       break;

                   }

                   if (operator2.equals("*")) {

                       operRight = operRight * Double.valueOf(expr[i++]);

                   }

                   if (operator2.equals("/")) {

                       operRight = operRight / Double.valueOf(expr[i++]);

                   }

               }

               if (operator.equals("+")) {

              operLeft = operLeft + operRight;

              }

              else {

              operLeft = operLeft - operRight;

              }

               break;

           }

       }

       return operLeft;

   }

  

   public static void main(String[] args) {

      

       Scanner sc = new Scanner(System.in);

       System.out.println("Enter infix : ");

       String infix = sc.nextLine();

      

       System.out.println(computeInfixExpr(infix));

   }

}

/*

Sample run:

Enter infix :

3 * 3 + 2

11.0

*/

Add a comment
Know the answer?
Add Answer to:
Hello, I'm having trouble with this certain part to a project of mine. Say I have...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • The code below accepts and evaluates an integer expression with the following operators: +, _, *,...

    The code below accepts and evaluates an integer expression with the following operators: +, _, *, and /. Your task is to modify it to include the % remainder operator that has the same precedence as * and /. No need to rewrite the entire program, just insert the needed statements. import java.util.Stack; public class EvaluateExpression { public static void main(String[] args) {     // Check number of arguments passed     if (args.length != 1) {       System.out.println(         "Usage:...

  • Programming project in Java: You are allowed to use the following methods from the Java API:...

    Programming project in Java: You are allowed to use the following methods from the Java API: class String length charAt class StringBuilder length charAt append toString class Character any method Create a class called HW2 that contains the following methods: 1. isAlphabeticalOrder takes a String as input and returns a boolean: The method returns true if all the letters of the input string are in alphabetical order, regardless of case. The method returns false otherwise. Do not use arrays to...

  • This is slice operator : [i : j] (Function) Slice : Returns the substring from i...

    This is slice operator : [i : j] (Function) Slice : Returns the substring from i to j -1 Quetion: 1) using the slice operator, print your first, then last name . 2) Print the length of your first name. 3) Assume you have two variables : s=‘s’ and p=‘p’ . Using concatenation and repetition, write an expression that produced the string mississippi. please attach your code and output

  • I need assistance with this code. Is there any way I can create this stack class (dealing with infix to postfix then postfix evaluation) without utilizing <stdio.h> and <math.h>? ________...

    I need assistance with this code. Is there any way I can create this stack class (dealing with infix to postfix then postfix evaluation) without utilizing <stdio.h> and <math.h>? ____________________________________________________________________________________________ C++ Program: #include <iostream> #include <string> #include <stdio.h> #include <math.h> using namespace std; //Stack class class STACK { private: char *str; int N; public: //Constructor STACK(int maxN) { str = new char[maxN]; N = -1; } //Function that checks for empty int empty() { return (N == -1); } //Push...

  • Im try to create a java program that checks to see if a given boolean expression...

    Im try to create a java program that checks to see if a given boolean expression is a tautology or not my code so far is as follows: public static class TreeNode    {        char data;        TreeNode left;        TreeNode right;               TreeNode(char item)        {            data = item;            left = null;            right = null;        }    } public static...

  • Please fix my code so I can get this output: Enter the first 12-digit of an...

    Please fix my code so I can get this output: Enter the first 12-digit of an ISBN number as a string: 978013213080 The ISBN number is 9780132130806 This was my output: import java.util.Scanner; public class Isbn { private static int getChecksum(String s) { // Calculate checksum int sum = 0; for (int i = 0; i < s.length(); i++) if (i % 2 == 0) sum += (s.charAt(i) - '0') * 3; else sum += s.charAt(i) - '0'; return 10...

  • Hello, I have my piece of C programming code and I have a pointer initialized to...

    Hello, I have my piece of C programming code and I have a pointer initialized to point to my array and I need help to display the contents of my array using a while loop or do-while loop. The stop condition should be when the pointer reaches '\0'. The code is below: #include <stdio.h> int main () {    char array[80]; printf("Enter a string: "); scanf("%[^\n]", &array); printf("%s\n", array); char * p;    p = array;         }

  • Please use the JAVA code attached as an input to the program that must be created...

    Please use the JAVA code attached as an input to the program that must be created IN JAVA. Instructions of the program: java code: /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * */ import java.util.Random; public class Rand_Z3_Exp { /** * @param args the command line arguments */ public static void main(String[] args) {...

  • Here is the code I have so far. I'm trying to figure out how to implement...

    Here is the code I have so far. I'm trying to figure out how to implement a boolean and use precedence. The 2nd expression should be 14 but it comes out as 28 so I'm definitely not understanding. #include <stack> #include <iostream> #include <string> using namespace std; // Function to find precedence of // operators. int precedence(char op) {    if (op == '+' || op == '-')        return 1;    if (op == '*' || op ==...

  • How can I make this program sort strings that are in a text file and not...

    How can I make this program sort strings that are in a text file and not have the user type them in? I need this done by 5:00 AM EST tommorow please. import java.util.*; public class MergeDemo { public static void main(String args[]) { Scanner input=new Scanner(System.in); System.out.print("How many lines to be sorted:"); int size=input.nextInt(); String[] lines=new String[size]; lines[0]=input.nextLine(); System.out.println("please enter lines..."); for(int i=0;i { lines[i]=input.nextLine(); } System.out.println(); System.out.println("Lines Before Sorting:"); System.out.println(Arrays.toString(lines)); mergeSort(lines); System.out.println(); System.out.println("Lines after Sorting:"); System.out.println(Arrays.toString(lines)); } public...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT