我有一个任务,我需要一些帮助,当使用RPN格式进行多个计算时似乎有错误。我使用下面链接中给出的示例输入。在第一个输入(16 3 7 + *)上,它给出了正确的答案(160)。但是,接下来的两个输入(4 32.125 13 - * 20 +)和(5 -3 * 4 2/6 3 1 - / + +)返回“错误”。如果您需要更多信息,请提前感谢您的帮助,不要害怕询问。作业详情:Details
到目前为止我的代码:
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;
}
}
答案 0 :(得分:1)
非常简单:) 你正在使用糟糕的“ - ”标志。当您在“else throw new Exception();”行中设置断点时,您会看到tk等于“ - ”(长“减号”符号)。将其复制到代码中而不是正常减号,或者在简单的文本编辑器中编辑文件。
答案 1 :(得分:0)
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");
}
}
}