如何制作RPN计算器(Java) [英] How to make a RPN calculator (Java)
问题描述
我有一个作业,需要一点帮助,使用RPN格式进行多个计算时似乎出现错误.我使用下面链接中给出的示例输入.在第一个输入(16 3 7 + *)上,它给我正确的答案(160).但是,接下来的两个输入(4 32.125 13 – * 20 +)和(5 –3 * 4 2/6 3 1 –/+ +)返回错误".预先感谢您的帮助,如果您需要更多信息,请不要问.作业详细信息:详细信息
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<String> tks = new Stack<String>();
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<String> 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;
}
}
推荐答案
非常简单:) 您使用的是错误的-"号.在"else throw new Exception();"行上放置断点时,您会看到tk等于-"(长减号").将其复制到您的代码中(而不是普通的减号),或者在一个简单的文本编辑器中编辑文件.
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.
这篇关于如何制作RPN计算器(Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!