创建 Java 个堆栈
Create Java stacks
public static int evaluate(Scanner input)
{
if (input.hasNextInt())
{
return input.nextInt();
}
else
{
String operator = input.next();
int operand1 = evaluate(input);
int operand2 = evaluate(input);
return evaluate(operator, operand1, operand2);
}
}
// pre : operator is one of *, /, %, + or -
// post: returns the result of applying the given operator to
// the given operands
public static int evaluate(String operator, int operand1, int operand2)
{
if (operator.equals("*"))
{
return operand1 * operand2;
}
else if (operator.equals("/"))
{
return operand1 / operand2;
}
else if (operator.equals("%"))
{
return operand1 % operand2;
}
else if (operator.equals("+"))
{
return operand1 + operand2;
}
else if (operator.equals("-"))
{
return operand1 - operand2;
}
else
{
throw new RuntimeException("illegal operator " + operator);
}
}
我想使用此代码并将其转换为 2 个堆栈(一个堆栈用于运算符,另一个堆栈用于操作数),以便在带有动作侦听器的用户输入 GUI 中使用前缀表达式。我如何编写代码将此代码转换为 2 个堆栈?顺便说一下,这是家庭作业,我知道你不能直接给我答案,所以如果你能给我提供易于理解的伪代码,我将不胜感激。感谢您的帮助。
你的伪装在这里:
public static int evaluate(Scanner input)
{
if (input.hasNextInt())
{
int stack_top_value=input.nextInt();
stack_for_operand.push(stack_top_value);
return stack_top_value;
}
else
{
String operator = input.next();
stack_for_operator.push(operator);
int operand1 = evaluate(input);
int operand2 = evaluate(input);
return evaluate(operator, operand1, operand2);
}
}
public static int evaluate(Scanner input)
{
if (input.hasNextInt())
{
return input.nextInt();
}
else
{
String operator = input.next();
int operand1 = evaluate(input);
int operand2 = evaluate(input);
return evaluate(operator, operand1, operand2);
}
}
// pre : operator is one of *, /, %, + or -
// post: returns the result of applying the given operator to
// the given operands
public static int evaluate(String operator, int operand1, int operand2)
{
if (operator.equals("*"))
{
return operand1 * operand2;
}
else if (operator.equals("/"))
{
return operand1 / operand2;
}
else if (operator.equals("%"))
{
return operand1 % operand2;
}
else if (operator.equals("+"))
{
return operand1 + operand2;
}
else if (operator.equals("-"))
{
return operand1 - operand2;
}
else
{
throw new RuntimeException("illegal operator " + operator);
}
}
我想使用此代码并将其转换为 2 个堆栈(一个堆栈用于运算符,另一个堆栈用于操作数),以便在带有动作侦听器的用户输入 GUI 中使用前缀表达式。我如何编写代码将此代码转换为 2 个堆栈?顺便说一下,这是家庭作业,我知道你不能直接给我答案,所以如果你能给我提供易于理解的伪代码,我将不胜感激。感谢您的帮助。
你的伪装在这里:
public static int evaluate(Scanner input)
{
if (input.hasNextInt())
{
int stack_top_value=input.nextInt();
stack_for_operand.push(stack_top_value);
return stack_top_value;
}
else
{
String operator = input.next();
stack_for_operator.push(operator);
int operand1 = evaluate(input);
int operand2 = evaluate(input);
return evaluate(operator, operand1, operand2);
}
}