Java 波兰符号实现

Java 波兰符号实现,java,Java,我想写一个程序来计算给定算术表达式的输出。就像这样: 我的输入是:*+*+12+3 4 5 6 我的输出应该是:156 我使用堆栈数据类型编写了一个Java程序来实现这一点。 这是我的Java程序: import java.util.Scanner; import java.util.Stack; public class Main { public static void main(String args[]){ Stack stack =new Stack();

我想写一个程序来计算给定算术表达式的输出。就像这样:

我的输入是:*+*+12+3 4 5 6 我的输出应该是:156

我使用堆栈数据类型编写了一个Java程序来实现这一点。 这是我的Java程序:

import java.util.Scanner;
import java.util.Stack;


public class Main {
   public  static  void main(String args[]){
       Stack stack =new Stack();

       String input;

       String trimmedInput[];
       int output;
       int number1,number2;
       int countOfNumber,j;

       Scanner scanner = new Scanner(System.in);

       System.out.println("put your arithmetical expression. Using Space between ");
       input=scanner.nextLine();

       trimmedInput=input.split("\\s+");

//       for(String a:trimmedInput)
//           System.out.println(a);


       countOfNumber=trimmedInput.length;


       for(j=0;j<countOfNumber;j++) {

               if (isNumeric(trimmedInput[j])) {
                   stack.push(trimmedInput[j]);

               }
                if (trimmedInput[j].equals("+")) {
                   number1 = Integer.parseInt((String) stack.pop()) ;

                    number2 = Integer.parseInt((String) stack.pop()) ;

                   output = number1 + number2;

                   stack.push(output);

               }

               if(trimmedInput[j].equals("-")){
                   number1 = Integer.parseInt((String) stack.pop()) ;

                   number2 = Integer.parseInt((String) stack.pop()) ;

                   output = number1-number2;

                   stack.push(output);
               }
                if(trimmedInput[j].equals("*")){
                    number1 = Integer.parseInt((String) stack.pop()) ;

                    number2 = Integer.parseInt((String) stack.pop()) ;

                   output = number1*number2;

                   stack.push(output);
               }
               if(trimmedInput[j].equals("/")){
                   number1 = Integer.parseInt((String) stack.pop()) ;

                   number2 = Integer.parseInt((String) stack.pop()) ;

                   output = number1/number2;

                   stack.push(output);
               }

           }

       while(!stack.isEmpty())
           System.out.println(stack.pop());


   }
    public static boolean isNumeric(String str)
    {
        try
        {
            double d = Double.parseDouble(str);
        }
        catch(NumberFormatException nfe)
        {
            return false;
        }
        return true;
    }

}
这是我的41。代码处的行:

number1 = Integer.parseInt((String) stack.pop()) ;

我无法找出代码中的问题所在。我是Java新手。请帮帮我。非常感谢:)

更新的答案


你不应该把所有的操作符都放到堆栈中,然后在看到两个操作数后将其弹出吗?(当一个操作数位于堆栈顶部时,您将有两个操作数,而另一个正好进入,即
trimmedInput[j]
)。

您的代码会给您带来错误,因为您是从左到右解析的。所以它得到的第一个字符串是“*”-star。所以,它检查它是否是一颗星星,然后从堆栈中弹出。但是,堆栈是空的!!所以,你们应该从右向左遍历,当你们发现数字被推入堆栈时,当你们找到一个操作符时,执行这个操作

for (int i = trimmedInput.length-1; i >= 0; i--) {
    if (isNumeric(trimmedInput[i])) stack.push(trimmedInput[i]);

    else if (trimmedInput[i].equals("*")) {
        // here you might get StackEmptyException if your expression is invalid
        // if you want to avoid that, then use try-catch and throw your custom InvalidExpressionExceptiono
        number1 = Integer.parseInt((String)stack.pop());
        number2 = Integer.parseInt((String)stack.pop());
        output = number1*number2;
        stack.push(output);
    }
    .
    .
    . // do the same for other operators
    .
    .
}

上述问题的替代解决方案。

import java.util.Scanner;
import java.util.Stack;

public class Expression
{
   static int i = 0 ;
   static Stack stack = new Stack<>();
   public static void main(String[] args) {

    Scanner in = new Scanner(System.in);
    String input = in.next();
    input += in.nextLine();
    char expr[] = input.toCharArray();

    for(int j = expr.length-1 ; j>=0 ; j--)
    {
        stack.push(process(expr[j]));
    }
    System.out.println("Result is : " + stack.pop());
}
public static int process(char val)
{
    int res = val;
    int flag = 0;
    if(val == '+')
    {
        flag = 1 ;
        res = (Integer)stack.pop() + (Integer)stack.pop();
    }
    else if(val == '-')
    {
        flag =1 ;
        res = (Integer)stack.pop() - (Integer)stack.pop();
    }
    else if(val == '*')
    {
        flag =1 ;
        res = (Integer)stack.pop() * (Integer)stack.pop();
    }
    else if(val == '/')
    {
        flag =1 ;
        res = ((Integer)stack.pop() / (Integer)stack.pop());
    }

    if(flag == 1)
        return res;
    else
        return res-48;
}
public static void print()
{
    int k = i;
    while(--k >= 0)
    {
        System.out.print(stack.peek() + " : ");
    }
    System.out.println("\n");
}
}
import java.util.Scanner;
导入java.util.Stack;
公共类表达式
{
静态int i=0;
静态堆栈=新堆栈();
公共静态void main(字符串[]args){
扫描仪输入=新扫描仪(系统输入);
字符串输入=in.next();
input+=in.nextLine();
char expr[]=input.toCharArray();
对于(int j=expr.length-1;j>=0;j--)
{
stack.push(进程(expr[j]);
}
System.out.println(“结果是:+stack.pop());
}
公共静态int进程(char-val)
{
int res=val;
int标志=0;
如果(val=='+')
{
flag=1;
res=(整数)stack.pop()+(整数)stack.pop();
}
else if(val='-')
{
flag=1;
res=(整数)stack.pop()-(整数)stack.pop();
}
else if(val=='*')
{
flag=1;
res=(整数)stack.pop()*(整数)stack.pop();
}
else if(val=='/'))
{
flag=1;
res=((整数)stack.pop()/(整数)stack.pop());
}
如果(标志==1)
返回res;
其他的
返回res-48;
}
公共静态无效打印()
{
int k=i;
而(-k>=0)
{
System.out.print(stack.peek()+“:”);
}
System.out.println(“\n”);
}
}

这意味着您试图将元素从堆栈中取出,即使它是空的!你应该从右向左移动。看看这个前缀评估的例子:是的,我的朋友。我知道,但我不能理解我的代码给出了这个错误。我正在代码中推送堆栈。提示:您应该学习如何在代码中添加A)有用的“跟踪”语句,或B)如何使用调试器。您不需要其他人仔细观察您的代码在做什么!成为一名程序员的本质是好奇,想知道“这里到底发生了什么”。问别人是有道理的,但应该是你的最后手段。例如,您可以在每个步骤中转储整个堆栈。您的代码会给您错误,因为您正在从左到右进行解析。所以它得到的第一个字符串是“*”-star。所以,它检查它是否是一颗星星,然后从堆栈中弹出。但是,堆栈是空的!!所以,您应该从右向左遍历,当您找到数字推入堆栈时,当您找到运算符时,执行这些操作。将前三个中间输入[0]设为*,它将其推入堆栈。这永远不会发生,因为第一颗星(*)从未被推入堆栈。检查OP的状况。第一个检查字符串是否为数字。发生异常是因为程序尝试弹出2个数字,但堆栈中没有任何内容。在这个程序中,运算符永远不会被推入堆栈,而且出于充分的理由,您是对的。我在头脑中遵循逻辑,但我弄错了。我更新了上面的答案。抱歉搞混了,那也不行。通过OP的示例,您可以看到计算前缀的唯一方法是从右向左遍历。此外,不应将运算符推送到堆栈上。看看:)
import java.util.Scanner;
import java.util.Stack;

public class Expression
{
   static int i = 0 ;
   static Stack stack = new Stack<>();
   public static void main(String[] args) {

    Scanner in = new Scanner(System.in);
    String input = in.next();
    input += in.nextLine();
    char expr[] = input.toCharArray();

    for(int j = expr.length-1 ; j>=0 ; j--)
    {
        stack.push(process(expr[j]));
    }
    System.out.println("Result is : " + stack.pop());
}
public static int process(char val)
{
    int res = val;
    int flag = 0;
    if(val == '+')
    {
        flag = 1 ;
        res = (Integer)stack.pop() + (Integer)stack.pop();
    }
    else if(val == '-')
    {
        flag =1 ;
        res = (Integer)stack.pop() - (Integer)stack.pop();
    }
    else if(val == '*')
    {
        flag =1 ;
        res = (Integer)stack.pop() * (Integer)stack.pop();
    }
    else if(val == '/')
    {
        flag =1 ;
        res = ((Integer)stack.pop() / (Integer)stack.pop());
    }

    if(flag == 1)
        return res;
    else
        return res-48;
}
public static void print()
{
    int k = i;
    while(--k >= 0)
    {
        System.out.print(stack.peek() + " : ");
    }
    System.out.println("\n");
}
}