问题描述
我希望这个问题很容易回答,但是我在制作 rpn 计算器时遇到了问题,我希望程序每次进行计算时都打印出“答案”,而不必指定结束文件 (Ctrl + Z) 以查看计算结果。对于上下文,这是我正在使用的代码:
import java.util.Scanner;
public class McIntyreJLab3 {
public static void main (String args[]) {
processInput rpninput = new processinput();
}
}//McIntyreJLab1
class processInput {
processinput() {
double doubleval = 0;
int charval = 0;
String ident = "";
Stack stack = new Stack();
Scanner in = new Scanner (system.in);
System.out.println("Please enter your input into the command line,then once you have submitted your input,please type Ctrl + Z signify you have finished your input.");
while (in.hasNext()) {
if (in.hasNextDouble()) {
doubleval = in.nextDouble();
System.out.println(doubleval + ": Double");
stack.push(doubleval);
} else {//if there is a double at the current placeholder on the input
ident = in.next();
charval = (int) ident.charat(0);
if(charval == 42|| charval == 43 || charval == 45 || charval == 47) {
System.out.println(ident + ": Operator");
double v1 = stack.pop();
double v2 = stack.pop();
switch (charval) {
case 42:
v2 = v2 * v1;
stack.push(v2);
break;
case 43:
v2 = v2 + v1;
stack.push(v2);
break;
case 45:
v2 = v2 - v1;
stack.push(v2);
break;
case 47:
v2 = v2 / v1;
stack.push(v2);
break;
default:
System.out.println("That is not an acceptable operator");
break;
}
} else { //checking for operators
System.out.println(ident + ": Identifier");
}//since no operator was found,it is an identifier
}//else statement for operators
}//loop for taking in the input and categorizing it into: identifier,operator,or double.
System.out.println("End of Line Reached");
double result = stack.pop();
if (!stack.isEmpty()) {
System.out.println("Too many operators or doubles");
System.exit(0);
} else {
System.out.println(result);
}
}//processInput method
}//processInput class
class Stack {
private int stack_capacity = 100;
private int tos = -1;
private double[] my_stack = new double[stack_capacity];
public void push(double item_to_push) {
if (tos + 1 >= stack_capacity) {
System.out.println("Exceeded Capacity");
System.exit(0);
}//checking if the stack will overflow
tos++;
my_stack[tos] = item_to_push;
}//pushing doubles into the stack
public double pop() throws NullPointerException {
if (tos < 0) {
System.out.println("Stack is empty");
System.exit(0);
}//if the stack is empty
double v = my_stack[tos];
tos--;
return v;
}//pop a value
public boolean isEmpty(){
return tos == -1;
}
}//Stack
为了快速总结一下这段代码目前的作用(你也可以自己尝试),它本质上要求值和运算符以反向波兰符号格式执行计算,问题是,在为了获得答案,您必须按 Ctrl + Z,然后输入以指定文件结尾,该文件将显示答案,但也会阻止用户输入更多值。假设用户想要继续计算已经输入的内容,我需要做什么才能允许用户继续输入值和运算符?如果有人可以帮助我,那就太好了!
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)