Java实现逆波兰计算器

逆波兰计算器
具体题目如下图所示:
Java实现逆波兰计算器_第1张图片
Java语言实现如下:

import java.util.Scanner;
import java.util.Stack;
public class test{
	 public static void main(String[] args) {
		 Test();
	 }
	 public static void Test(){
		 System.out.println("请输入逆波兰表达式:");
		 @SuppressWarnings("resource")
		String sc=new Scanner(System.in).nextLine();
		 String[] ss = sc.split("\\s+"); 
		 System.out.println("运算字符串组为:");
		 for(String s:ss)
			 System.out.print(s+",");
		 int result=EvaluateReversePolish(ss);
		 System.out.println("结果为:"+result);
	 }
	 public static int EvaluateReversePolish(String[] ss){
		 int result=0;//初始化结果为0
		 int num1=0,num2=0;//num2为第一运算数,num1为第二运算数
		 @SuppressWarnings("rawtypes")
		Stack<Comparable> stackNum=new Stack<Comparable>();//初始化栈 用来存储数字
		 for(int i=0;i<ss.length;i++){
			 switch(ss[i]){
			 case "+":
				 if(!stackNum.isEmpty()){//判断栈是否为空
					 num1=Integer.parseInt(stackNum.pop().toString());//将数字字符串转换为数字
					 num2=Integer.parseInt(stackNum.pop().toString());
				 }
				 result=num2+num1;//进行运算
				 stackNum.push(result);//结果入栈
				 break;//跳出循环
			 case "-":
				 if(!stackNum.isEmpty()){
					 num1=Integer.parseInt(stackNum.pop().toString());
					 num2=Integer.parseInt(stackNum.pop().toString());
				 }
				 result=num2-num1;
				 stackNum.push(result);
				 break;
			 case "*":
				 if(!stackNum.isEmpty()){
					 num1=Integer.parseInt(stackNum.pop().toString());
					 num2=Integer.parseInt(stackNum.pop().toString());
				 }
				 result=num2*num1;
				 stackNum.push(result);
				 break;
			 case "/":
				 if(!stackNum.isEmpty()){
					 num1=Integer.parseInt(stackNum.pop().toString());
					 num2=Integer.parseInt(stackNum.pop().toString());
				 }
				 result=num2/num1;
				 stackNum.push(result);
				 break;
			 default:
				 stackNum.push(ss[i]);	  
			 }
		 }
	  return result;
	  }  
}

你可能感兴趣的:(Java,题库)