以下代码模拟了迭代器的创建和使用。
先创建一个类,并定义迭代器常有的hasNext()和next()方法。
package caculator; import java.util.LinkedList; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Formula { private String str; public Formula(String str) { super(); this.str = str.trim(); } public class Iterator{ int from; String regex = "\\d+(\\.\\d+)?|[+/\\-*]"; //Matcher m = Pattern.compile(regex).matcher(str); public String next(){ Matcher m = Pattern.compile(regex).matcher(str); m.find(from); String s = m.group(); from = m.end(); return s; } public Boolean hasNext(){ return from < str.length(); } } public double caculator(){ LinkedList<Double> list1 = new LinkedList<>(); LinkedList<String> list2 = new LinkedList<>(); Iterator it = new Iterator(); while(it.hasNext()){ String s = it.next(); if(s.matches("\\d+(\\.\\d+)?")){ list1.add(Double.parseDouble(s)); }else if(s.matches("[+\\-]")){ list2.add(s); }else{ double a = list1.removeLast(); double b = Double.parseDouble(it.next()); double c = caculate(a,s,b); list1.add(c); } } while(list2.size()!=0){ double a = list1.removeFirst(); double b = list1.removeFirst(); String s = list2.removeFirst(); double c = caculate(a,s,b); list1.addFirst(c); } return list1.get(0); } private double caculate(double a, String s, double b) { double r = 0; switch (s.charAt(0)) { case ‘+‘: r = a+b; break; case ‘-‘: r=a-b; break; case ‘*‘: r=a*b; break; case ‘/‘: r=a/b; break; default: break; } return r; } }
再创建一个测试类,并引上述类的方法计算用户输入的公式。
package caculator; import java.util.Scanner; import caculator.Formula.Iterator; public class Test1 { public static void main(String[] args) { System.out.println("请输入计算公式:"); String s = new Scanner(System.in).nextLine(); Formula f = new Formula(s); Double d = f.caculator(); System.out.println(s+"="+d); } }
以上程序是实现的是根据用户输入的算式输出准确的计算结果。如输入:6+8/2+3*2,输入结果为:6+8/2+3*2=16.0
原文:http://www.cnblogs.com/fazheng/p/5084210.html