java中rpn,如何制作RPN计算器(Java)

I have an assignment and I need a bit of help, there seems to be an error when doing more than one calculation using RPN format. I use the example input as given in the link below. On the first input (16 3 7 + *) it gives me the correct answer (160). But, the next two inputs (4 32.125 13 – * 20 +) and (5 –3 * 4 2 / 6 3 1 – / + +) return "error." Thanks for your help in advance, if you need some more information don't be afraid to ask. The assignment details: Details

My code so far:

import java.io.*;

import java.util.*;

public class RPNcalculator {

public static void main(String[] args) {

String fileName="RPNInput.txt";

String fileName2="RPNOutput.txt";

Scanner inputStream = null;

PrintWriter outputStream = null;

//read

try{

inputStream = new Scanner(new File(fileName)); //try to open the file

}

catch(Exception e){

System.out.println("Could not open the file named "+ fileName); // if it doesn't find it, tell them

System.exit(0); // and then exit.

}

//write

try{

outputStream = new PrintWriter(new FileOutputStream(fileName2,true)); //try to create the file

}

catch(Exception e){

System.out.println("Could not open the file named "+ fileName2); // if it doesn't find it, tell them

System.exit(0); // and then exit.

}

while(inputStream.hasNextLine()){

String equation = inputStream.nextLine();

if (equation==null) break;

Stack tks = new Stack();

tks.addAll(Arrays.asList(equation.trim().split("[ \t]+"))); //remove spaces and split into list.

if (tks.peek().equals("")) continue; //if tks equals nothing

try {

double r = evaluaterpn(tks); //set the variable r to the equation answer.

if (!tks.empty()) throw new Exception(); //if the list is not empty, print out answer.

System.out.println(r);

}

catch (Exception e) {System.out.println("error");}

}

}

private static double evaluaterpn(Stack tks) throws Exception {

String tk = tks.pop();

double x,y;

try {x = Double.parseDouble(tk);}

catch (Exception e) {

y = evaluaterpn(tks); x = evaluaterpn(tks);

if (tk.equals("+")) x += y;

else if (tk.equals("-")) x -= y;

else if (tk.equals("*")) x *= y;

else if (tk.equals("/")) x /= y;

else throw new Exception();

}

return x;

}

}

解决方案

Very simple :)

you're using the bad "-" sign. When you put a breakpoint at the line "else throw new Exception();", you see that tk is equal to "--" (long "minus" sign). Either copy it into your code instead of normal minus sign or edit your file in a simple text editor.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值