哪个高手能提供一段验证数学表达式的正确性,并提供一些值可计算得出结果的啊?
注:在计算时最好也进行验证计算是否错误!
[email protected]

解决方案 »

  1.   

    import java.util.Stack;
    public class Check{
    private String reg=null;
    public Check(String reg){
     this.reg=reg;
    }

    public void validate(){
    Stack<Character> st=new Stack<Character>();
    char ch;
    for(int i=0;i<reg.length();i++){
     ch=reg.charAt(i);
          if(i==reg.length()-1){
           if(!st.isEmpty()||!(ch>=48&&ch<=57)){
            System.out.println ("表达式错误!");
           return;
            }
          
           }
          if(ch>=48&&ch<=57){
            continue;
           }
             else if(ch=='('||ch=='['||ch=='{'){
            st.push(ch);
             }
        
         else if(ch==')'||ch==']'||ch=='}'){
         char ch1=st.pop();
           if(ch1=='('&&ch==')'){}
           else if(ch1=='['&&ch==']'){}
           else if(ch1=='{'&&ch=='}'){}
           else{
            System.out.println ("表达是错误!");
            return ;
            }
         }
         else if(ch=='+'||ch=='-'||ch=='*'||ch=='/'){
           if(i==0||i==reg.length()-1){
            System.out.println ("表达是错误!");
            return ;
            }
         }
           else{
            System.out.println ("表达是错误!");
            return;
            }
    }
    System.out.println ("表达是正确!");
    }
    public static void main (String[] args) {
    Check c=new Check("(1+2)*(2[+3)/2");
    c.validate();
                 }
    }
      

  2.   


    package com.ricky.www;import java.util.regex.Matcher;
    import java.util.regex.Pattern;public class Test{
    public static void main(String[] args){
    String expression1 = " 2 + 6 +5 * 4";
    String expression2 = " 2 + 6 /  ";
    isVaild(expression1);
    isVaild(expression2);
    } public static boolean isVaild(String expression){
    String temp = expression.replaceAll("\\s","");
    String regex = "(\\d+[-+*/])*\\d+";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(temp);
    boolean result = matcher.matches();
    if(result){
    System.out.println(expression + " is a valid match expression.");
    }else{
    System.out.println(expression + " is not a valid match expression.");
    }
    return result;
    }
    }这是一个最简单的验证(不涉及括号的验证的)。至于表达式的运算的话可以上网搜索下堆栈数据结构。