The program in java is to evaluate the post-fix arithmetic expression.
I am not getting any error in my program but I am getting the wrong output.
I am trying to evaluate the expression (1*(((2+3)*(4-5))+6)) where its result is 1.
But I am getting the output as 11.
Its post-fix expression is 1 2 3 + 4 5 - * 6 + *
Looking forward for your help.
Thank you!!
public static void evaluatePostfix(String sol)
{
ArrayStack<Double> nlist = new ArrayStack<Double> ();
double op1, op2, result;
char ch;
for (int i = 0; i < sol.length(); i++)
{
if ('0' <= sol.charAt(i) && sol.charAt(i) <= '9')
nlist.push((double)(sol.charAt(i) - '0'));
else
if (sol.charAt(i)=='+'||sol.charAt(i)=='-'||sol.charAt(i)=='*'||sol.charAt(i)=='/')
{
op1 = nlist.pop();
op2 = nlist.pop();
ch = sol.charAt(i);
switch(ch){
case '+':
nlist.push(op1 + op2);
break;
case '-':
nlist.push(op1 - op2);
break;
case '*':
nlist.push(op1 * op2);
break;
case '/':
nlist.push(op1 / op2);
break;
default:nlist.push(0.000);
}
}
}
result = nlist.pop();
System.out.println(result);
}
When you pop from the stack, op2 is the element at the top and op1 is at top-1. Change it to:
op2 = nlist.pop();
op1 = nlist.pop();
To be more clear if your postfix expression is 56 - (so 5-6 in infix) your stack is
| 6 |
| 5 |
and when you get the - you are doing nlist.push(op1 - op2); which pushes 6-5 into the stack while you should push 5-6.
Related
I'm a new java coder getting into it doing a project. I coded it how i believe the system would execute it and yet it doesn't seem to be following the While loops requirements. I want it to generate random number, do a random operation, then ask the user for an answer. The answer must be not decimal and the random numbers must be below 10 to make the questions easier as its for a lower target audience. I'm kind of stuck now on this piece. Apologies if this doesn't make sense as i say it is a first attempt for me.
import java.util.Random;
import java.lang.Math;
import java.util.Scanner;
public class RandomisedQuestions{
public static void QuestionGenerator(){
Random r = new Random();
Scanner s = new Scanner(System.in);
int intA = 0;
int intB = 0;
char operator ='?';
double value = 1.2;
for (int i = 0; i < 3; i++) {
intA = (int)(10.0 * Math.random());//the (int) forces the number to be an int
intB = (int)(10.0 * Math.random());
if (intA <= 0 && intB <= 0){
intA = (int)(10.0 * Math.random());//the (int) forces the number to be an int
intB = (int)(10.0 * Math.random());
System.out.println(intA + intB);
}
while ((value % 1) !=0 && value > 1){//Runs while value is not whole
switch (r.nextInt(4)){
case 0: operator = '+';
value = intA+intB;
break;
case 1: operator = '-';
value = intA-intB;;
break;
case 2: operator = '*';
value = intA*intB;;
break;
case 3: operator = '/';
value = intA/intB;;
break;
default: operator = '?';
}
//System.out.println(operator);
}
System.out.println(intA +""+ operator +""+ intB);
System.out.println("Enter the answer");
int uGuess = s.nextInt();
if (uGuess == value){
System.out.println("Correct");
}
else{
System.out.println("Incorrect");
}
}
}
}
It's better to use ThreadLocalRandom.nextInt to generate your numbers:
// At the start of your program initialize the generator:
ThreadLocalRandom r = ThreadLocalRandom.current();
// Later use it:
do {
intA = ThreadLocalRandom.nextInt(1, 10);
intB = ThreadLocalRandom.nextInt(1, 10);
switch (r.nextInt(4)) {
case 0: operator = '+';
value = intA + intB;
break;
case 1: operator = '-';
value = intA - intB;
break;
case 2: operator = '*';
value = intA * intB;
break;
case 3: operator = '/';
value = (double)intA / intB;
break;
default: operator = '?';
}
} while (value != (int)value || value <= 1);
Also note the conversion to double in division case, otherwise the division will be performed for integer types.
I have a string like: value += 5 * 3 - (2 / 4) for example.
Now I must change all operators to their opposite, so:
+ to -
- to +
* to /
/ to *
My problem is when I use replaceAll() function
First time:
string.replaceAll("+", "-"); I become: value -= 5 * 3 - (2 / 4)
Second time:
string.replaceAll("-", "+"); I become: value += 5 * 3 + (2 / 4)
but it's need to be: value -= 5 * 3 + (2 / 4)
How can I achive that?
You could create a Map with the Characters to replace and iterate through the String like this:
public static void main(String[] args) {
Map<Character, Character> replacers = new HashMap<>();
replacers.put('+', '-');
replacers.put('-', '+');
String value = "value += 5 * 3 - (2 / 4)";
StringBuilder out = new StringBuilder();
for (char c : value.toCharArray()) {
out.append(replacers.getOrDefault(c, c));
}
System.out.println(out.toString());
}
This will print out:
value -= 5 * 3 + (2 / 4)
Why not just loop through string char-by-char and replace single letter at a time to avoid such chaos?
public String revert(String expression){
char[] temp = expression.toCharArray();
for(int i = 0; temp.length> i; i++){
switch(temp[i]){
case '/':
temp[i] = '*';
break;
case '*':
temp[i] = '/';
break;
case '-':
temp[i] = '+';
break;
case '+':
temp[i] = '-';
break;
}
}
return new String(temp);
}
You could first replace your symbols (+,-,...) to some different ones that cannot be present in your expression e.g. +->A, -->B, ... and than all As to -, Bs to +, ... .
Other option is creating array of chars from your string and than iterate this array invert your symbols in situ. and than create String again.
I think a simple loop will work;
String exp="YOUR EXPRESSION HERE";
String newStr="";
//loop through the string
for(int i=0;i<exp.length();i++)
{
char ch=exp.charAt(i);//extract a charcter
switch(ch)
{
case '+':
newExp+='-';// replace + with -
break;
case '-':
newStr+='+';// and - with +
break;
case '*';
newStr+='/'// divide with *
break;
case '/'
newStr+='*';// multiply with /
break;
default:
newStr+=ch;// leave it as it is
}
}
You are probably better off just looping through the values, perhaps in a char array.
String val = "value += 5 * 3 - (2 / 4)";
char[] cArray = val.toCharArray();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < cArray.length; i++) {
if (cArray[i] == '+') {
sb.append("-");
} else if (cArray[i] == '-') {
sb.append("+");
// repeat for others
} else {
sb.append(cArray[i]);
}
}
Output:
value -= 5 * 3 + (2 / 4)
I'm making a RPN calculator, I have done the part of converting infix to postfix, now I want to evaluate the expression in postfix.
example:
converting from ((3 + 5 1)=8) 14 to 3 5 1 +8 = 14 (I have done that). now evaluating the latter expression.
The instructions I have:
Given a postx expression v 1:::v n,
where v i is either an operand or an operator,
the following algorithm evaluates the expression. A helper string, temp2, is
used during the calculation.
i = 1
while i<= n
if v_i is an operand: Push v_i to tmp2.
if v_i is
an operator: Apply v_i to the top two elements of tmp2. Replace
these by the result in tmp2.
i = i + 1
Output result from tmp2.
My code:
static int eval(String postfix) {
int result = 0;
String temp2 = "";
int num1, num2;
char operator;
for (int i = 0; i < postfix.length(); i++) {
char M = postfix.charAt(i);
// if v_i is an operand: Push v_i to tmp2.
if (Character.isDigit(postfix.charAt(i))) {
temp2 = M + temp2;
}
/*
* if v_i is an operator: Apply v_i to the top two elements of tmp2.
* Replace these by the result in tmp2.
*/
if (postfix.charAt(i) == '+' || postfix.charAt(i) == '-' || postfix.charAt(i) == '*'
|| postfix.charAt(i) == '/') {
temp2 = M + temp2.substring(2);
num1 = Character.getNumericValue(temp2.charAt(temp2.length() - 1));
operator = postfix.charAt(i);
num2 = Character.getNumericValue(temp2.charAt(temp2.length() + i - 1));
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
}
}
}
return result;
}
I get
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
at:
num2 = Character.getNumericValue(temp2.charAt(temp2.length() + i - 1));
I have the following code to evaluate my expression tree. But the problem is it gives me wrong answer. I have tested around and found that when I code
double left = (double) Character.digit((char) evaluateTree(t.left),
10);
left value gets equal to -1 which I believe the double value of '+'. When I call root.left (which is '+') and try to get its double value with the Character.digit(char) it gives me -1. Since my tree is like :
//My infix : (2+5)*7 MyPostfix : 25+7*
*
/ \
+ 7
/ \
2 5
Evaluate method :
public double evaluateTree(TreeNode t) {
if(root == null)
return 0;
if (Character.isDigit(t.ch))
return (double)t.ch;
else {
char c = t.ch;
double left = (double) Character.digit((char) evaluateTree(t.left),
10);
double right = (double) Character.digit(
(char) evaluateTree(t.right), 10);
//checks what to do for operators for example for '+' return left+right
return evaluate(c, left, right);
}
}
Current result = -7.0
How do I fix this problem?
public double evaluate(char c, double left, double right) {
double result = 0;
switch (c) {
case '+':
result = left + right;
break;
case '-':
result = left - right;
break;
case '*':
result = left * right;
break;
case '/':
result = left / right;
break;
case '%':
result = left % right;
break;
}
return result;
}
Don't call Character.digit() on the result of evaluateTree(). evaluteTree() and evaluate() return a double, not a character that needs to be turned into a double. It's
if (Character.isDigit(t.ch))
return (double)t.ch;
where you need the Character.digit() call.
I have a program where the user inputs 6 doubles, and the program outputs every combination of operators that can go in-between the doubles as 1024 separate strings. Here are the first two results if the user inputed 14,17,200,1,5, and 118:
"14.0+17.0+200.0+1.0+5.0+118.0"
"14.0+17.0+200.0+1.0+5.0-118.0"
What I want to do is perform the arithmetic according to the order of operations. Each double is stored as a variable a through f and each operator in-between these variables is stored as a char a_b through e_f. So:
double a, b, c, d, e, f;
char a_b, b_c, c_d, d_e, e_f;
My first thought was to write the code like this:
public double operateGroup() {
value = 0;
switch (a_b) {
case '+':
value += a + b;
break;
case '-':
value += a - b;
break;
case '*':
value += a * b;
break;
case '/':
value += a / b;
break;
default:
break;
}
switch (b_c) {
case '+':
value += c;
break;
case '-':
value += -c;
break;
case '*':
value *= c;
break;
case '/':
value /= c;
break;
default:
break;
}
switch (c_d) {
case '+':
value += d;
break;
case '-':
value += -d;
break;
case '*':
value *= d;
break;
case '/':
value /= d;
break;
default:
break;
}
switch (d_e) {
case '+':
value += e;
break;
case '-':
value += -e;
break;
case '*':
value *= e;
break;
case '/':
value /= e;
break;
default:
break;
}
switch (e_f) {
case '+':
value += f;
break;
case '-':
value += -f;
break;
case '*':
value *= f;
break;
case '/':
value /= f;
break;
default:
break;
}
return value;
}
But this doesn't work because it is the same as doing (a O b) O c) O d) O e) where O is any arbitrary operator. Any tips?
Since there are no parentheses, a trivial approach will work:
Go through the list once to process multiplications and divisions
When an operator between X and Y is * or /, replace X by X*Y or X/Y, and remove Y; also remove the operator
Now go through the list again, this time processing additions and subtractions in sequence.
To implement this approach, define two lists - the list of N Doubles, and N-1 operators, and implement the calculation as follows:
ArrayList<Double> vals = ...
ArrayList<Integer> ops = ... // 1=+, 2=-, 3=*, 4=/
for (int i = 0 ; i < ops.Count ; i++) {
int op = ops.get(i);
if (op == 3 || op == 4) {
if (op == 3) {
vals.set(i, vals.get(i) * vals.get(i+1));
} else {
vals.set(i, vals.get(i) / vals.get(i+1));
}
ops.remove(i);
vals.remove(i+1);
i--;
}
}
double res = vals.get(0);
for (int i = 0 ; i != ops.Count ; i++) {
if (op == 1) {
res += vals.get(i);
} else {
res -= vals.get(i);
}
}
If you need the operators' and operands' information, you should build a Parse Tree (this has been asked before).
If you are only interested in the result, you can evaluate the String directly:
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
public class Eval {
public static void main(String[] args) throws Exception {
ScriptEngineManager s = new ScriptEngineManager();
ScriptEngine engine = s.getEngineByName("JavaScript");
String exp = "14.0+17.0+200.0+1.0+5.0-118.0";
System.out.println(engine.eval(exp));
}
}
Output:
119.0
I would say you should parse it into a tree and then walk the tree to evaluate. Numbers are leaf nodes and operators are parents.