import java.util.NoSuchElementException;
import java.util.Scanner;
import Jobday11_1.Formual.DieDaiQi;
public class Test1 {
public static void main(String[] args) {
while(true){
try {
System.out.println("输入算式:");
String s = new Scanner(System.in).nextLine();
Formual f = new Formual(s);
DieDaiQi it = f.iterator();
while(it.hasNext()){
String s2 = it.next();
}
double d =f.eval();
System.out.println(s+"="+d);
return ;
}catch(IndexOutOfBoundsException e){
System.out.println("不能输入为空");
}catch(ArithmeticException e){
System.out.println("不能除0");
} catch (NoSuchElementException e) {
System.out.println("你输入的算式,缺少数字");
} catch(IllegalStateException e){
System.out.println("你输入的信息有误,只能输入数字和运算符+-*/,请重新输入");
}
}
}
}
package Jobday11_1;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.LinkedList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Formual {
private String f;
public Formual(String f) {
super();
//trim()去除两端得到空白字符, 一般用于用户处理
this.f = f.trim();
String[] f3 = f.split(".");
String f1 = f.replaceAll("\\d+(\\.\\d+)?|[/*\\-+]", "1");
String[] f2 = f1.split("[1]");
if(f3.length != f2.length){
IllegalStateException e = new IllegalStateException();
throw e;
}
}
public DieDaiQi iterator(){
return new DieDaiQi();
}
class DieDaiQi{
int start;
Matcher m =Pattern.compile("\\d+(\\.\\d+)?|[/*\\-+]")
.matcher(f);
public String next(){
m.find(start);
String s = m.group();
start = m.end();
return s;
}
public boolean hasNext(){
return start<f.length();
}
}
public double eval(){
LinkedList<Double> list1 = new LinkedList<>();
LinkedList<Character> list2 = new LinkedList<>();
DieDaiQi it = new DieDaiQi();
while(it.hasNext()){
String s = it.next();
if(s.matches("\\d+(\\.\\d)?")){
list1.add(Double.parseDouble(s));
}else if(s.matches("[+\\-]")){
list2.add(s.charAt(0));
}else {
double a = list1.removeLast();
double b = Double.parseDouble(it.next());
if(b == 0){
ArithmeticException e = new ArithmeticException("/ by zero");
throw e; //把异常抛到调用位置
}
double c = jiSuan(BigDecimal.valueOf(a),s.charAt(0),BigDecimal.valueOf(b)).doubleValue();
list1.add(c);
}
}
while(list2.size() !=0){
double a = list1.removeFirst();
double b = list1.removeFirst();
char op = list2.removeFirst();
double c = jiSuan(BigDecimal.valueOf(a),op,BigDecimal.valueOf(b)).doubleValue();
list1.addFirst(c);
}
return list1.get(0);
}
private BigDecimal jiSuan(BigDecimal a, char op, BigDecimal b) {
if(op =='+'){return a.add(b);}
else if(op =='-'){return a.subtract(b);}
else if(op =='*'){return a.multiply(b);}
else{ return a.divide(b,10); }
}
}