[Java]分解算术表达式一

源码:

package com.hy;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

// 程序入口
public class Inlet {
    public static void main(String[] args) throws IOException{
        // 取得用户输入的表达式
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
        String rawExpression = null; 
        System.out.print("请输入算术表达式:"); 
        rawExpression = br.readLine(); 
        
        // 得到合法的算术表达式
        String expression="";    
        for(int i=0;i<rawExpression.length();i++){
            // 拿到表达式的每个字符
            char c=rawExpression.charAt(i);
            //System.out.print(c+","); 
            
            if(Character.isDigit(c) || c=='+' || c=='-' || c=='*' || c=='/' || c=='=' || c=='(' || c==')' ){
                //System.out.print(c);
                expression+=c;
            }else{
                System.out.print(" "+c+"不是合法的算术表达式字符.");
                System.exit(0);
            }
        }
        
        test(expression);
    }
    
    public static void test(String expression){
        String str="";
        for(int i=0;i<expression.length();i++){
            char c=expression.charAt(i);
            
            if(Character.isDigit(c)){
                str+=c;
            }else{
                if(str.length()>0){// 此判断是因为有+(这种符号相连的情况
                    System.out.println(str);
                    str="";
                }
                
                System.out.println(c);
            }
        }
        
        if(str.length()>0){// 此判断是因为可能表达式不是以=结尾
            System.out.println(str);
            str="";
        }

    }
}

运行结果:

请输入算术表达式:23+45+56+34+1+4+9*8
23
+
45
+
56
+
34
+
1
+
4
+
9
*
8
请输入算术表达式:(12+34)*5-66/3
(
12
+
34
)
*
5
-
66
/
3
请输入算术表达式:250*4*8/1000
250
*
4
*
8
/
1000

--End--2019年9月2日08点18分

原文地址:https://www.cnblogs.com/heyang78/p/11444570.html