20155237 第十一周java课堂程序

内容一:后缀表达式

abcde/-f+

内容二:实现Linux下dc的功能,计算后缀表达式的值

填充下列代码:

import java.util.Scanner;

           public class MyDCTester  {

            public static void main (String[] args) {

            String expression, again;

             int result;

             try
{
Scanner in = new Scanner(System.in); do
{
MyDC evaluator = new MyDC();
System.out.println ("Enter a valid postfix expression: ");
expression = in.nextLine(); result = evaluator.evaluate (expression);
System.out.println();
System.out.println ("That expression equals " + result); System.out.print ("Evaluate another expression [Y/N]? ");
again = in.nextLine();
System.out.println();
}
while (again.equalsIgnoreCase("y"));
}
catch (Exception IOException)
{
System.out.println("Input exception reported");
}
}
}
import java.util.StringTokenizer;
import java.util.Stack;
public class MyDC
{
/** constant for addition symbol */
private final char ADD = '+';
/** constant for subtraction symbol */
private final char SUBTRACT = '-';
/** constant for multiplication symbol */
private final char MULTIPLY = '*';
/** constant for division symbol */
private final char DIVIDE = '/';
/** the stack */
private Stack<Integer> stack; public MyDC() {
stack = new Stack<Integer>();
} public int evaluate (String expr)
{
int op1, op2, result = 0;
String token;
StringTokenizer tokenizer = new StringTokenizer (expr); while (tokenizer.hasMoreTokens())
{
token = tokenizer.nextToken(); **//如果是运算符,调用isOperator
if ()
{
//从栈中弹出操作数2
//从栈中弹出操作数1
//根据运算符和两个操作数调用evalSingleOp计算result;
//计算result入栈;
}
else//如果是操作数
//操作数入栈;
}** return result;
} private boolean isOperator (String token)
{
return ( token.equals("+") || token.equals("-") ||
token.equals("*") || token.equals("/") );
} private int evalSingleOp (char operation, int op1, int op2)
{
int result = 0; switch (operation)
{
case ADD:
result = op1 + op2;
break;
case SUBTRACT:
result = op1 - op2;
break;
case MULTIPLY:
result = op1 * op2;
break;
case DIVIDE:
result = op1 / op2;
} return result;
}
}

填写的代码是:

//如果是运算符,调用isOperator

if ()

{

//从栈中弹出操作数2

//从栈中弹出操作数1

//根据运算符和两个操作数调用evalSingleOp计算result;

//计算result入栈;

}

else//如果是操作数

//操作数入栈;

}

//当输入是运算符

调用isOperator方法片段所输入的是否为运算符,是运算符则为true,不是则为false,当是运算符的时候进行出栈、运算、将结果进栈的操作

根据提示信息和栈的基础操作,从栈中弹出一个数字为stack.pop(),并将此值赋给int a,

根据所给的evalSingleOp对前两个操作数进行加减乘除,并用charAt(0)方法取得字符串的运算符号,进行相应的运算。

20155237 第十一周java课堂程序-LMLPHP

码云链接

05-08 15:38