标签:中缀 pre add yun tar stack nbsp tostring parse
参考
Mycode
1 package collection_Exe; 2 3 import java.util.*; 4 5 public class Exe16 { 6 public static void main(String[] args) { 7 Scanner input = new Scanner(System.in); 8 System.out.println("Input :"); 9 String string = input.nextLine(); 10 input.close(); 11 String[] strs = string.split(" "); 12 Set<String> set = new HashSet<>(); 13 set.add("+"); 14 set.add("-"); 15 set.add("*"); 16 set.add("/"); 17 set.add("("); 18 set.add(")"); 19 Stack<String> stack = new Stack<>(); 20 Stack<String> operator = new Stack<>(); 21 for(String str : strs) { 22 if(!set.contains(str)) { 23 stack.push(str); 24 } else { 25 switch (str) { 26 case "+": 27 case "-": 28 if(!operator.isEmpty() && 29 !operator.peek().equals("(")) { 30 stack.push(operator.pop()); 31 } 32 operator.push(str); 33 break; 34 case "*": 35 case "/": 36 if(!operator.isEmpty() && 37 (operator.peek().equals("*") || 38 operator.peek().equals("/"))) { 39 stack.push(operator.pop()); 40 } 41 operator.push(str); 42 break; 43 case "(": 44 operator.push(str); 45 break; 46 case ")": 47 while (!operator.peek().equals("(")) { 48 stack.push(operator.pop()); 49 } 50 operator.pop(); 51 break; 52 default: 53 System.out.println("Error"); 54 break; 55 } 56 } 57 } 58 while(!operator.isEmpty()) { 59 stack.push(operator.pop()); 60 } 61 System.out.println(stack.toString()); 62 } 63 }
你以为我会写注释吗?不可能的。
运行结果如下:
像我这种不拘小节的男人,是不会在意同优先级运算顺序的。
大概上,算法是没什么错误的。
再附上一个程序,同样不会写注释的。
1 package collection_Exe; 2 3 import java.util.HashSet; 4 import java.util.Scanner; 5 import java.util.Set; 6 import java.util.Stack; 7 8 public class Exe14 { 9 public static void main(String[] args) { 10 Scanner input = new Scanner(System.in); 11 System.out.println("Input:"); 12 String str = input.nextLine(); 13 input.close(); 14 String[] strs = proStr(str); 15 Stack<Integer> stack = new Stack<>(); 16 Set<String> set = new HashSet<>(); 17 set.add("+"); 18 set.add("-"); 19 set.add("*"); 20 set.add("/"); 21 for(String s : strs) { 22 if(set.contains(s)) { 23 processStack(stack, s.charAt(0)); 24 } else { 25 stack.push(Integer.parseInt(s)); 26 } 27 } 28 System.out.println("Result : " + stack.pop()); 29 } 30 31 public static void processStack(Stack<Integer> stack, Character op) { 32 Integer num2 = stack.pop(); 33 Integer num1 = stack.pop(); 34 Integer num3 = null; 35 switch (op) { 36 case ‘+‘: 37 num3 = num1 + num2; 38 break; 39 case ‘-‘: 40 num3 = num1 - num2; 41 break; 42 case ‘*‘: 43 num3 = num1 * num2; 44 break; 45 case ‘/‘: 46 num3 = num1 / num2; 47 break; 48 default: 49 System.out.println("ERROR IN processStack."); 50 break; 51 } 52 stack.push(num3); 53 } 54 55 public static String[] proStr(String str) { 56 return str.split(" "); 57 } 58 }
自己凭本事写的bug。
标签:中缀 pre add yun tar stack nbsp tostring parse
原文地址:http://www.cnblogs.com/zuosy/p/7357038.html