如何制作RPN计算器(Java)
我有一个作业,我需要一些帮助,当使用RPN格式进行多个计算时,似乎出现了错误。我使用下面链接中给出的示例输入。在第一次输入(1637+*)时,它给出了正确的答案(160)。但是,接下来的两个输入(4 32.125 13–*20+)和(5–3*4 2/6 3 1–/++)返回“错误”。提前感谢您的帮助,如果您需要更多信息,请不要害怕询问。任务详情: 到目前为止,我的代码是:如何制作RPN计算器(Java),java,calculator,rpn,Java,Calculator,Rpn,我有一个作业,我需要一些帮助,当使用RPN格式进行多个计算时,似乎出现了错误。我使用下面链接中给出的示例输入。在第一次输入(1637+*)时,它给出了正确的答案(160)。但是,接下来的两个输入(4 32.125 13–*20+)和(5–3*4 2/6 3 1–/++)返回“错误”。提前感谢您的帮助,如果您需要更多信息,请不要害怕询问。任务详情: 到目前为止,我的代码是: import java.io.*; import java.util.*; public class RPNcalcula
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;
}
}
import java.io.*;
导入java.util.*;
公共类RPN计算器{
公共静态void main(字符串[]args){
字符串fileName=“RPNInput.txt”;
字符串fileName2=“RPNOutput.txt”;
扫描仪输入流=空;
PrintWriter outputStream=null;
//阅读
试一试{
inputStream=新扫描仪(新文件(文件名));//尝试打开该文件
}
捕获(例外e){
System.out.println(“无法打开名为“+fileName”的文件);//如果找不到,请告诉他们
System.exit(0);//然后退出。
}
//写
试一试{
outputStream=new PrintWriter(new FileOutputStream(fileName2,true));//尝试创建文件
}
捕获(例外e){
System.out.println(“无法打开名为“+fileName2”的文件);//如果找不到,请告诉他们
System.exit(0);//然后退出。
}
while(inputStream.hasNextLine()){
字符串方程=inputStream.nextLine();
如果(方程式==null)中断;
堆栈tks=新堆栈();
tks.addAll(Arrays.asList(equation.trim().split([\t]+”);//删除空格并拆分为列表。
if(tks.peek().equals(“”)continue;//如果tks等于零
试一试{
double r=evaluaterpn(tks);//将变量r设置为方程的答案。
如果(!tks.empty())抛出新异常();//如果列表不是空的,请打印出答案。
系统输出println(r);
}
catch(异常e){System.out.println(“错误”);}
}
}
私有静态双计算器PN(堆栈tks)引发异常{
字符串tk=tks.pop();
双x,y;
试试{x=Double.parseDouble(tk);}
捕获(例外e){
y=评估器PN(tks);x=评估器PN(tks);
如果(tk.等于(“+”)x+=y;
如果(tk.等于(“-”)x-=y;
如果(tk.等于(“*”)x*=y;
如果(tk.等于(“/”)x/=y;
else抛出新异常();
}
返回x;
}
}
非常简单:)
你用的是坏的“-”号。当您在“else throw new Exception();”行放置断点时,您会看到tk等于“-”(长的“减号”)。要么将其复制到代码中,而不是普通的减号,要么在简单的文本编辑器中编辑文件。非常简单:)
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import java.util.Stack;
public class Rpncalculator
{
static final HashMap<String, Integer> prec;
static
{
prec = new HashMap<>();
prec.put("^", 3);
prec.put("%", 2);
prec.put("*", 2);
prec.put("/", 2);
prec.put("+", 1);
prec.put("-", 1);
}
public static void main(String[] args)
{
Queue<String> infixQueue = new LinkedList<>(); //Standard Queue class provided by Java Framework.
Scanner sc = new Scanner(System.in);
Double number = 0.0;
Character c, cNext = ' ';
String input;
String multiDigit = "";
do
{
System.out.println("Enter your INFIX expression or 'quit' to exit: ");
input = sc.nextLine();
input = input.replaceAll(" ", ""); //ignore spaces in input infix expression
if (input.equals("quit"))
{
System.exit(0);
}
for (int i = 0; i < input.length(); i++)
{
c = input.charAt(i);
if (i + 1 < input.length())
{
cNext = input.charAt(i + 1);
}
if (c.equals('(') || c.equals(')'))
{
if (c.equals('(') && cNext.equals('-'))
{
System.out.println("NEGATIVE Numbers not allowed");
main(args);
} else
{
infixQueue.add(c.toString());
}
} else if (!Character.isDigit(c))
{
if (infixQueue.isEmpty() && c.equals('-'))
{
System.out.println("NEGATIVE Numbers not allowed");
main(args);
} else if (cNext.equals('-'))
{
System.out.println("NEGATIVE Numbers not allowed");
main(args);
} else
{
infixQueue.add(c.toString());
}
} else if (Character.isDigit(c))
{
if (i + 1 < input.length() && input.charAt(i + 1) == '.') //to handle decimal
{
int j = i + 1;
multiDigit = c.toString() + input.charAt(j); //to handle multidigit
while (j + 1 <= input.length() - 1 && Character.isDigit(input.charAt(j + 1)))
{
multiDigit = multiDigit + input.charAt(j + 1);
j++;
}
i = j;
infixQueue.add(multiDigit);
multiDigit = "";
} else if (i + 1 <= input.length() - 1 && Character.isDigit(input.charAt(i + 1)))
{
int j = i;
//multiDigit=c.toString()+input.charAt(i);
while (j <= input.length() - 1 && Character.isDigit(input.charAt(j)))
{
multiDigit = multiDigit + input.charAt(j);
j++;
}
i = j - 1;
infixQueue.add(multiDigit);
multiDigit = "";
} else
{
infixQueue.add(c.toString());
}
}
}
infixToPostfix(infixQueue);
} while (!input.equals("quit"));
}
//method to convert from infix to postfix
public static void infixToPostfix(Queue<String> infixQueue)
{
Stack operatorStack = new Stack();
Queue<String> postQueue = new LinkedList<>();
String t;
while (!infixQueue.isEmpty())
{
t = infixQueue.poll();
try
{
double num = Double.parseDouble(t);
postQueue.add(t);
} catch (NumberFormatException nfe)
{
if (operatorStack.isEmpty())
{
operatorStack.add(t);
} else if (t.equals("("))
{
operatorStack.add(t);
} else if (t.equals(")"))
{
while (!operatorStack.peek().toString().equals("("))
{
postQueue.add(operatorStack.peek().toString());
operatorStack.pop();
}
operatorStack.pop();
} else
{
while (!operatorStack.empty() && !operatorStack.peek().toString().equals("(") && prec.get(t) <= prec.get(operatorStack.peek().toString()))
{
postQueue.add(operatorStack.peek().toString());
operatorStack.pop();
}
operatorStack.push(t);
}
}
}
while (!operatorStack.empty())
{
postQueue.add(operatorStack.peek().toString());
operatorStack.pop();
}
System.out.println();
System.out.println("Your POSTFIX expression is: ");
//numbers and operators all seperated by 1 space.
for (String val : postQueue)
{
System.out.print(val + " ");
}
postfixEvaluation(postQueue);
}
//method to calculate the reuslt of postfix expression.
public static void postfixEvaluation(Queue<String> postQueue)
{
Stack<String> eval = new Stack<>(); //Standard Stack class provided by Java Framework.
String t;
Double headNumber, nextNumber, result = 0.0;
while (!postQueue.isEmpty())
{
t = postQueue.poll();
try
{
double num = Double.parseDouble(t);
eval.add(t);
} catch (NumberFormatException nfe)
{
headNumber = Double.parseDouble(eval.peek());
eval.pop();
nextNumber = Double.parseDouble(eval.peek());
eval.pop();
switch (t)
{
case "+":
result = nextNumber + headNumber;
break;
case "-":
result = nextNumber - headNumber;
break;
case "*":
result = nextNumber * headNumber;
break;
case "/":
//in java, there is no exception generated when divided by zero and thus checking
//for
if (headNumber == 0)
{
System.out.println("\nERROR: Cannot Divide by zero!\n");
return;
} else
{
result = nextNumber / headNumber;
break;
}
case "%":
result = nextNumber % headNumber;
break;
case "^":
result = Math.pow(nextNumber, headNumber);
break;
}
eval.push(result.toString());
}
}
//Outputing the result in this function to verify that the o/p is a result of postfix expression.
//Outputing the result to 3 decimal places
System.out.println("\nRESULT is: ");
DecimalFormat df = new DecimalFormat("0.000");
for (String val : eval)
{
System.out.println(df.format(Double.parseDouble(val)) + "\n");
}
}
}
你用的是坏的“-”号。当您在“else throw new Exception();”行放置断点时,您会看到tk等于“-”(长的“减号”)。将其复制到代码中,而不是普通的减号,或者在简单的文本编辑器中编辑文件。import java.text.DecimalFormat;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import java.util.Stack;
public class Rpncalculator
{
static final HashMap<String, Integer> prec;
static
{
prec = new HashMap<>();
prec.put("^", 3);
prec.put("%", 2);
prec.put("*", 2);
prec.put("/", 2);
prec.put("+", 1);
prec.put("-", 1);
}
public static void main(String[] args)
{
Queue<String> infixQueue = new LinkedList<>(); //Standard Queue class provided by Java Framework.
Scanner sc = new Scanner(System.in);
Double number = 0.0;
Character c, cNext = ' ';
String input;
String multiDigit = "";
do
{
System.out.println("Enter your INFIX expression or 'quit' to exit: ");
input = sc.nextLine();
input = input.replaceAll(" ", ""); //ignore spaces in input infix expression
if (input.equals("quit"))
{
System.exit(0);
}
for (int i = 0; i < input.length(); i++)
{
c = input.charAt(i);
if (i + 1 < input.length())
{
cNext = input.charAt(i + 1);
}
if (c.equals('(') || c.equals(')'))
{
if (c.equals('(') && cNext.equals('-'))
{
System.out.println("NEGATIVE Numbers not allowed");
main(args);
} else
{
infixQueue.add(c.toString());
}
} else if (!Character.isDigit(c))
{
if (infixQueue.isEmpty() && c.equals('-'))
{
System.out.println("NEGATIVE Numbers not allowed");
main(args);
} else if (cNext.equals('-'))
{
System.out.println("NEGATIVE Numbers not allowed");
main(args);
} else
{
infixQueue.add(c.toString());
}
} else if (Character.isDigit(c))
{
if (i + 1 < input.length() && input.charAt(i + 1) == '.') //to handle decimal
{
int j = i + 1;
multiDigit = c.toString() + input.charAt(j); //to handle multidigit
while (j + 1 <= input.length() - 1 && Character.isDigit(input.charAt(j + 1)))
{
multiDigit = multiDigit + input.charAt(j + 1);
j++;
}
i = j;
infixQueue.add(multiDigit);
multiDigit = "";
} else if (i + 1 <= input.length() - 1 && Character.isDigit(input.charAt(i + 1)))
{
int j = i;
//multiDigit=c.toString()+input.charAt(i);
while (j <= input.length() - 1 && Character.isDigit(input.charAt(j)))
{
multiDigit = multiDigit + input.charAt(j);
j++;
}
i = j - 1;
infixQueue.add(multiDigit);
multiDigit = "";
} else
{
infixQueue.add(c.toString());
}
}
}
infixToPostfix(infixQueue);
} while (!input.equals("quit"));
}
//method to convert from infix to postfix
public static void infixToPostfix(Queue<String> infixQueue)
{
Stack operatorStack = new Stack();
Queue<String> postQueue = new LinkedList<>();
String t;
while (!infixQueue.isEmpty())
{
t = infixQueue.poll();
try
{
double num = Double.parseDouble(t);
postQueue.add(t);
} catch (NumberFormatException nfe)
{
if (operatorStack.isEmpty())
{
operatorStack.add(t);
} else if (t.equals("("))
{
operatorStack.add(t);
} else if (t.equals(")"))
{
while (!operatorStack.peek().toString().equals("("))
{
postQueue.add(operatorStack.peek().toString());
operatorStack.pop();
}
operatorStack.pop();
} else
{
while (!operatorStack.empty() && !operatorStack.peek().toString().equals("(") && prec.get(t) <= prec.get(operatorStack.peek().toString()))
{
postQueue.add(operatorStack.peek().toString());
operatorStack.pop();
}
operatorStack.push(t);
}
}
}
while (!operatorStack.empty())
{
postQueue.add(operatorStack.peek().toString());
operatorStack.pop();
}
System.out.println();
System.out.println("Your POSTFIX expression is: ");
//numbers and operators all seperated by 1 space.
for (String val : postQueue)
{
System.out.print(val + " ");
}
postfixEvaluation(postQueue);
}
//method to calculate the reuslt of postfix expression.
public static void postfixEvaluation(Queue<String> postQueue)
{
Stack<String> eval = new Stack<>(); //Standard Stack class provided by Java Framework.
String t;
Double headNumber, nextNumber, result = 0.0;
while (!postQueue.isEmpty())
{
t = postQueue.poll();
try
{
double num = Double.parseDouble(t);
eval.add(t);
} catch (NumberFormatException nfe)
{
headNumber = Double.parseDouble(eval.peek());
eval.pop();
nextNumber = Double.parseDouble(eval.peek());
eval.pop();
switch (t)
{
case "+":
result = nextNumber + headNumber;
break;
case "-":
result = nextNumber - headNumber;
break;
case "*":
result = nextNumber * headNumber;
break;
case "/":
//in java, there is no exception generated when divided by zero and thus checking
//for
if (headNumber == 0)
{
System.out.println("\nERROR: Cannot Divide by zero!\n");
return;
} else
{
result = nextNumber / headNumber;
break;
}
case "%":
result = nextNumber % headNumber;
break;
case "^":
result = Math.pow(nextNumber, headNumber);
break;
}
eval.push(result.toString());
}
}
//Outputing the result in this function to verify that the o/p is a result of postfix expression.
//Outputing the result to 3 decimal places
System.out.println("\nRESULT is: ");
DecimalFormat df = new DecimalFormat("0.000");
for (String val : eval)
{
System.out.println(df.format(Double.parseDouble(val)) + "\n");
}
}
}
导入java.util.HashMap;
导入java.util.LinkedList;
导入java.util.Queue;
导入java.util.Scanner;
导入java.util.Stack;
公共类RPN计算器
{
静态最终HashMap prec;
静止的
{
prec=新的HashMap();
预告付诸表决(“^”,3);
预售价(“%”,2);
预制件(“*”,2);
预制件(“/”,2);
预放置(“+”,1);
预制件(以“-”号填列,1);
}
公共静态void main(字符串[]args)
{
Queue infixQueue=new LinkedList();//Java框架提供的标准队列类。
扫描仪sc=新的扫描仪(System.in);
双倍数=0.0;
字符c,cNext='';
字符串输入;
字符串多位数=”;
做
{
System.out.println(“输入中缀表达式或“退出”退出:”);
输入=sc.nextLine();
input=input.replaceAll(“,”);//忽略输入中缀表达式中的空格
if(input.equals(“quit”))
{
系统出口(0);
}
对于(int i=0;iimport java.text.DecimalFormat;
导入java.util.HashMap;
导入java.util.LinkedList;
导入java.util.Queue;
导入java.util.Scanner;
导入java.util.Stack;
公共类RPN计算器
{
静态最终HashMap prec;
静止的
{
prec=新