Question: Firstly, ?n this program ,I have also extend the% operation to calculate the remainder. Secondly, add an exponentiation operation(^). The result should be as follows.
Firstly, ?n this program ,I have also extend the% operation to calculate the remainder.
Secondly, add an exponentiation operation(^).
The result should be as follows. 2 * 3 ^ 3 = 54.
( 2 * 3 ) ^ 3 = 216.
Thirdly, support unary operations.
- 5 + 100 = or ( - 32 + ( - 1 ) ) =
It should be make it possible to calculate
Source code :
public class Exp {
String[] cal;
String token;
int idx;
public Exp(String[] eee,int iii) { // constructor
// formal marameter --> instance value
cal = eee;
idx = iii;
token = cal[iii];
}
int expression() { /* Expression */
char k;
int num1=term();
while ( (token.charAt(0)== '+') || (token.charAt(0) == '-') ) {
k = token.charAt(0);
token = cal[++idx];
int num2=term();
if (k == '+') { num1=num1+num2; }
else { num1=num1-num2; }
}
return num1;
}
int term() { /* Term */
char k;
int num1=factor();
while ( (token.charAt(0) == '*') || (token.charAt(0) == '/') ) {
k = token.charAt(0);
token = cal[++idx];
int num2=factor();
if (k == '*') { num1=num1*num2; }
else { num1=num1um2; }
}
return num1;
}
int factor() { /* Factor */
int num=0;
if ( (token.charAt(0)>='0') && (token.charAt(0)
num = Integer.parseInt(token); /* String --> int */
token = cal[++idx];
} else if (token.charAt(0) == '(') { /* ( expression ) */
token = cal[++idx];
num = expression();
if (token.charAt(0)!=')') System.out.println(" ) expected. ");
token = cal[++idx];
} else {
System.out.println("syntax error ");
}
return num;
}
}
Main program source code :
import java.io.*;
public class Cal {
public static void main(String[] args)throws IOException {
System.out.println("input expression with = ");
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
String s = r.readLine();
String[] token = s.split(" "); // one line --> token[] by " "
int n=token.length; // number of token
if (n
(215-2*2*2*2*2?????????????? else {
for (int i=0 ; i
System.out.print(token[i]+" ");
}
Exp exp = new Exp(token, 0); // construct instance exp
int ans = exp.expression(); // calculate expression
System.out.println(" " + ans);/* answer */
}
}
}
Note: When inputting data from the keyboard, spaces must be written between all data.
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
