Java Reference
In-Depth Information
3 import java.util.*;
4
5 public class PrefixEvaluator {
6 public static void main(String[] args) {
7
Scanner console = new Scanner(System.in);
8
System.out.println("This program evaluates prefix");
9
System.out.println("expressions that include the");
10
System.out.println("operators +, -, *, / and %");
11
System.out.print("expression? ");
12
double value = evaluate(console);
13
System.out.println("value = " + value);
14 }
15
16 // pre : input contains a legal prefix expression
17 // post: expression is consumed and the result is returned
18 public static double evaluate(Scanner input) {
19 if (input.hasNextDouble()) {
20 return input.nextDouble();
21
} else {
22
String operator = input.next();
23
double operand1 = evaluate(input);
24
double operand2 = evaluate(input);
25
return apply(operator, operand1, operand2);
26 }
27 }
28
29 // pre : operator is one of +, -, *, / or %
30 // post: returns the result of applying the given operator
31 // to the given operands
32 public static double apply(String operator, double operand1,
33 double operand2) {
34 if (operator.equals("+")) {
35 return operand1 + operand2;
36 } else if (operator.equals("-")) {
37 return operand1 - operand2;
38 } else if (operator.equals("*")) {
39 return operand1 * operand2;
40 } else if (operator.equals("/")) {
41 return operand1 / operand2;
42 } else if (operator.equals("%")) {
43 return operand1 % operand2;
44 } else {
45 throw new IllegalArgumentException("bad operator: "
46 + operator);
Search WWH ::




Custom Search