【java数据结构与算法学习】逆波兰计算器
逆波兰表达式也叫后缀表达式,采用逆波兰表达式无需考虑运算符的优先级,逆波兰表达式的计算是使用栈来实现的
下面是我写的逆波兰的计算,本人是个小菜鸟,希望各位大牛多指点指点。
主要的思想就是:当我们遇到操作符的时候,就出栈两个元素进行计算,然后将计算结果压入栈中;遇到数字的时候就进行压栈操作
import java.util.Arrays;
import java.util.Scanner;
public class NiBoLan {
//逆波兰计算器是由栈来实现的,首先要定义栈
private Object[] objects;
private int top;
private int maxSize;
public NiBoLan(){
maxSize = 20;
objects = new Object[maxSize];//定义栈的大小为20
top = -1;
}
public boolean push(Object o){
if (top == maxSize-1){
objects = Arrays.copyOf(objects,maxSize+maxSize/2);
maxSize = maxSize+maxSize/2;
}
objects[++top] = o;
return true;
}
public Object pop(){
if (top < 0){
return null;
}
return objects[top--];
}
public static void main(String[] args) {
NiBoLan niBoLan = new NiBoLan();
//首先获得用户输入的字符串,格式是用空格分隔
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String[] chs = input.split(" ");
//当遇到操作符的时候,进行计算,并将结果压入栈中,这里我们也可以使用switch来实现
for (String str :
chs) {
if (str.equals("+")){
String first = (String) niBoLan.pop();
String second = (String) niBoLan.pop();
niBoLan.push(Integer.parseInt(second) + Integer.parseInt(first)+"");
}else if (str.equals("-")){
String first = (String) niBoLan.pop();
String second = (String) niBoLan.pop();
niBoLan.push(Integer.parseInt(second) - Integer.parseInt(first)+"");
}else if (str.equals("*")){
String first = (String) niBoLan.pop();
String second = (String) niBoLan.pop();
niBoLan.push(Integer.parseInt(second) * Integer.parseInt(first)+"");
}else if (str.equals("/")){
String first = (String) niBoLan.pop();
String second = (String) niBoLan.pop();
niBoLan.push(Integer.parseInt(second) / Integer.parseInt(first)+"");
}else {
niBoLan.push(str);
}
}
//最终结果出栈
String result = (String) niBoLan.pop();
System.out.println(result);//1 + 2 * 6 / 4 = 4 1 2 6 * 4 / +
}
}
还没有评论,来说两句吧...