Hello, I\'m having trouble with this certain part to a project of mine. Say I ha
ID: 3864521 • Letter: H
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
EDIT: I solved this myself, thanks anyway if anyone was going to help.
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 breakExplanation / Answer
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
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.