我正在研究逆向波兰记谱法程序,并且遇到了处理无效表达式的问题......如果运算符太少,我可以处理它,或者操作数,但我不能处理任何不是“(”,“+”,“ - ”,“*”和“#”)的字符。跳过行的其余部分(或强制英镑符号到输入),而不是读取整个表达如果接收到错误的字符,Java扫描仪停止读取输入
这里是下面我的代码:
public class RpnEvaluator
{
private Scanner stdin;
private Stack stack = new Stack(50);
private Queue queue = new Queue(50);
private String expression = "";
private String interValue = "";
private int numExpressions = 0;
/**
Runs the RPN Evaluator.
*/
public void run()
{
stdin = new Scanner(System.in);
while(stdin.hasNext())
{
String input = stdin.next();
if(input.charAt(0) == '(')
addOperand(input);
else if(input.equals("+") || input.equals("-") || input.equals("*"))
performOperation(input.charAt(0));
else if(input.equals("#"))
outputExpression();
else
invalidExpression(); **// Here is where I need to deal with anything that isn't above and output anything BEFORE the bad value, AND the value itself.**
}
System.out.println("Normal Termination of Program 3.");
}
例如:输入如
(2/9) B (4/3)/#
应该返回此输出:
Expression 1 is: (2/9)B
Invalid Expression
Intermediate results:
氮:不要说“磅符号”,如果你的意思是'#'(如你以前使用):作为一个英国人,否则我会认为你的意思[英镑] //www.fileformat.info/info/unicode/char/a3/index.htm)。 –
保存输入信息,以便在遇到错误字符时可以打印出导致错误字符的所有内容。尝试自己填写'invalidExpression()',看看你得到了什么。 –
因此,输入被自动解析为操作符或操作数,然后放入堆栈供以后使用,但我们不应该在堆栈中放置不好的令牌,我只是想知道如何处理它。 – liquidsystem