import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class CalculatorFinal {
public static void main(String[] args) {
// TODO Auto-generated method stub
float total = 0;
int operator;
float operand1, operand2;
String WELCOME="Welcome to your Postfix Calculator\n====================\n";
String[] StrArray;
String postfix ="";
System.out.print(WELCOME);
System.out.println("Enter your postfix expression, OR to exit type stop:");
StrArray = postfix.split(" ");
for ( int i = 0; i < postfix.length(); i++) {
// try {
//Scanner myfile = new Scanner(new File ("postfix.txt"));
// while (myfile.hasNext())
// {
// postfix = myfile.nextLine();
// StrArray = postfix.split(" ");
if((postfix.length() > 3) && (operand1 = floatvalueof(postfix[0]) && (operand2 = floatvalueof(postfix[1]) && (operator = floatvalueof(postfix[2])))))
{
try { // This deals with exceptions
switch(operator){
case '+':
total = operand1 + operand2;
break;
}
switch(operator){
case '-':
total = operand1 + operand2;
break;
}
switch(operator){
case '/':
total = operand1 + operand2;
break;
}
switch(operator){
case '*':
total = operand1 + operand2;
break;
}
}
catch (NumberFormatException e)
{
System.out.println("Error:- "+e.getMessage());
}
}}}}
我一直在尝试使这个后缀计算器工作,所以如果有人输入7 8 +计算器将格式化7 + 8并给出答案,但我似乎无法做到这一点。任何帮助,将不胜感激。
答案 0 :(得分:0)
您的代码存在一些问题(或者可以改进):
我强烈建议您进行调试,以便逐行查看代码正在执行的操作。
这是代码的改进/修复版本,因此它可以正常工作并正确处理上述情况:
public static void main(String[] args) throws IOException
{
Double result = 0D;
System.out.print("Welcome to your Postfix Calculator\n====================\n");
System.out.println("Enter your postfix expression, OR to exit type stop:");
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
String input = bufferRead.readLine();
if (input.toLowerCase().equals("stop"))
{
System.out.println("Received stop command.");
return;
}
String[] inputArray = input.split(" ");
if (inputArray.length == 3)
{
try
{
Double number1 = Double.parseDouble(inputArray[0]);
Double number2 = Double.parseDouble(inputArray[1]);
String operator = inputArray[2];
switch (operator)
{
case "+":
result = number1 + number2;
break;
case "-":
result = number1 - number2;
break;
case "/":
result = number1 / number2;
break;
case "*":
result = number1 * number2;
break;
default:
System.out.println("Received unsupported operator: " + operator);
break;
}
}
catch (NumberFormatException e)
{
System.err.println("Error:\n" + e.getMessage());
}
}
else
{
System.err.println("Invalid number of arguments provided.");
}
System.out.println("Result: " + result);
}