简体   繁体   English

Java 后缀表达式计算器

[英]Java Postfix Expression Evaluator

I really need help with my post-fix expression calculator.我真的需要我的修复后表达式计算器的帮助。 I don't really know what's wrong with the code that I've written, however when I run the program, it just prints whatever number is on the top.我真的不知道我写的代码有什么问题,但是当我运行程序时,它只是打印顶部的任何数字。 For example, if I input "7 2 +", the output is 2. If I input "2 7 +", the output is 7. Could somebody please point me in the right direction on how to fix this?例如,如果我输入“7 2 +”,则输出为 2。如果我输入“2 7 +”,则输出为 7。有人能指出我如何解决这个问题的正确方向吗? I think (not sure) that the problem is that my program is not able to properly detect the operands "+" and "*".我认为(不确定)问题在于我的程序无法正确检测操作数“+”和“*”。 However, I can't tell why.但是,我说不出为什么。

File #1:文件#1:

import java.io.*;
import java.util.*;

public class ProblemTwo {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        System.out.println("Enter a post value expression: ");
        String input = scan.nextLine();
        StringTokenizer st = new StringTokenizer(input);
        Stack hello = new Stack(st.countTokens());

        for (int i = 0; i <= st.countTokens(); i++) {
            String inputToken = st.nextToken();
            if (inputToken.trim().contains("+")) {
                int sum = Integer.parseInt(hello.pop() + Integer.parseInt(hello.pop()));
                System.out.println(sum);
                hello.push(Integer.toString(sum));
            }
            else if (inputToken.trim().contains("*")){
                int product = Integer.parseInt(hello.pop()) * Integer.parseInt(hello.pop());
                hello.push(Integer.toString(product));
            }
            else {
                hello.push(inputToken);
            }
        }
        System.out.println(hello.pop());
    }
}

File #2:文件#2:

public class Stack {

        private String[] stackArray;
        private int arraySize;
        private int top;

        public Stack(int capacity) {
            arraySize = capacity;
            stackArray = new String[arraySize];
            top = -1;
        }

        public void push(String i) {
            stackArray[++top] = i;
        }

        public String pop() {
            return stackArray[top--];
        }

        public boolean isEmpty() {
            return top == -1;
        }

        public boolean isFull() {
            return top == arraySize - 1;
        }
    }

Problem is you are using st.countTokens() in for loop but each subsequent call to countTokens() returns count of the number of times this tokenizer's nextToken method can be called .问题是您在for循环中使用st.countTokens()但每次对countTokens()后续调用countTokens()返回可以调用此标记生成器的nextToken方法的次数计数 From StringTokenizer 's doc:来自StringTokenizer的文档:

Calculates the number of times that this tokenizer's nextToken method can be called before it generates an exception.计算此标记生成器的 nextToken 方法在生成异常之前可以调用的次数。 The current position is not advanced.当前位置不先进。

Use another variable to capture st.countTokens() before starting loop or better use st.hasMoreTokens() for terminating loop.在开始循环之前使用另一个变量来捕获st.countTokens()或者更好地使用st.hasMoreTokens()来终止循环。 Like:像:

while (st.hasMoreElements()) {
 // same logic
}

Also modify pop() method to return stackArray[top--];同时修改pop()方法返回stackArray[top--]; . .

Your code has at least 2 problems: Your took not all inputed value in for loop and your stack has broken implementation.您的代码至少有 2 个问题:您没有在 for 循环中获取所有输入值,并且您的堆栈已破坏实现。 Here is working version.这是工作版本。

File #1:文件#1:

import java.io.*;
import java.util.*;

public class ProblemTwo {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        System.out.println("Enter a post value expression: ");
        String input = scan.nextLine();
        StringTokenizer st = new StringTokenizer(input);
        Stack hello = new Stack(st.countTokens());

        for (int i = 0; i <= st.countTokens()+1; i++) {
            String inputToken = st.nextToken();
            if (inputToken.trim().contains("+")) {
                int sum = Integer.parseInt(hello.pop()) + Integer.parseInt(hello.pop());
                System.out.println(sum);
                hello.push(Integer.toString(sum));
            }
            else if (inputToken.trim().contains("*")){
                int product = Integer.parseInt(hello.pop()) * Integer.parseInt(hello.pop());
                hello.push(Integer.toString(product));
            }
            else {
                hello.push(inputToken);
            }
        }
        System.out.println(hello.pop());
    }
} 

File #2:文件#2:

public class Stack {

    private String[] stackArray;
    private int arraySize;
    private int top;

    public Stack(int capacity) {
        arraySize = capacity;
        stackArray = new String[arraySize];
        top = -1;
    }

    public void push(String i) {
        stackArray[++top] = i;
    }

    public String pop() {
        return stackArray[top--];
    }

    public boolean isEmpty() {
        return top == -1;
    }

    public boolean isFull() {
        return top == arraySize - 1;
    }
}
import java.util.Stack;
public class Postfix_Eva {
public static void main(String[] args)
{
    String exp="231*+9-";//giving input
    System.out.println(eva(exp));//calling eva method with argument exp(String)
}

static int eva(String e)
{
    Stack stk=new Stack();//creating object for Stack
    for(int i=0;i<e.length();i++)
    {
        char c=e.charAt(i); //retriving each character from String using .charAt() method
        if(Character.isDigit(c)) //checking whether the character is digit or not
        {
            //Casting is not done
            stk.push(c-'0');

        }
        else
        {
            int a=(int) stk.pop(); //casting popped value into int
            int b=(int) stk.pop();
            switch(c)
            {
                case '+': 
                stk.push(a+b); 
                break; 

                case '-': 
                stk.push(a-b); 
                break; 

                case '/': 
                stk.push(a/b); 
                break; 

                case '*': 
                stk.push(a*b); 
                break; 
            }
        }
    }
    return (int) stk.pop();//returning int casted value of stk.pop() 
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM