荣耀计算器

                                          ## 荣耀自制计算器

登录界面

package wangrongchang;
import java.awt.Image;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Font;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
public class Login //extends JFrame
{
	private static  JButton bt1;//注册按钮
	private static  JButton bt2;//登陆按钮
	private static  JButton bt3;//退出按钮
	private static  JLabel jl1;//登陆的版面
	private static  JFrame jf1;//登录的框架
	private static  JTextField jt1;//id
	private static  JPasswordField jt2;//密码
	private static  JLabel jl_id;//id标签
	private static  JLabel jl_password;//密码标签
    private static String t1,t2;
    private static int pd=0;
	public Login() 
	{
		Font font=new Font("楷体",Font.PLAIN,20);
		jf1=new JFrame("欢迎登录计算器小程序");
		jf1.setSize(500,500);
		//给登录界面添加背景图片
		ImageIcon bgim = new ImageIcon(Login.class.getResource("tt.jpg")) ;//背景图案
		bgim.setImage(bgim.getImage().
		getScaledInstance(bgim.getIconWidth(),
				bgim.getIconHeight(),Image.SCALE_DEFAULT));
	    jl1=new JLabel();
	    jl1.setIcon(bgim);
	    //账号栏
	    jl_id=new JLabel("账号:");
	    jl_id.setBounds(40,60,60,30);
	    jl_id.setFont(font);
        //密码栏
	    jl_password=new JLabel("密码:");
	    jl_password.setBounds(40,120,60,30);
	    jl_password.setFont(font);
	    //注册按钮
	    bt1=new JButton("注册");
	    bt1.setBounds(40, 250, 100,50);
	    bt1.setFont(font);
	    //登录按钮
	    bt2=new JButton("登录");
	    bt2.setBounds(170, 250, 100,50);
	    bt2.setFont(font);
	    //退出按钮
	    bt3=new JButton("退出");
	    bt3.setBounds(300, 250, 100,50);
	    bt3.setFont(font);
	    //加入文本框
	    jt1=new JTextField();
	    jt1.setBounds(150,50,250,50);
	    jt1.setFont(font);
	    jt2=new JPasswordField();
	    jt2.setBounds(150,120,250,50);
	    jt2.setFont(font);
	    jl1.add(jt1);
	    jl1.add(jt2);
	    jl1.add(jl_id);
	    jl1.add(jl_password);
	    jl1.add(bt1);
	    jl1.add(bt2);
	    jl1.add(bt3);
	    jf1.add(jl1);
	    jf1.setVisible(true);
	    jf1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	    jf1.setLocation(400,200);
	    //注册
	    bt1.addActionListener(new ActionListener() {
	    	@SuppressWarnings("deprecation")
	    	public void actionPerformed(ActionEvent e){
	    		pd=1;
	    		t1=jt1.getText();
	    		t2=jt2.getText();
	    		String filename="users.txt";
	    		try {
	    	FileWriter writer=new FileWriter(filename);
	    	BufferedWriter bw=new BufferedWriter(writer);
	    	bw.write("id:"+t1+"&&"+"Password:"+t2);
	    	bw.newLine();
	    	bw.close();
	    	writer.close();
	   }catch(IOException ex) {ex.printStackTrace();}
	   jt1.setText("");
	   jt2.setText("");
	   JOptionPane.showMessageDialog(null,"注册成功!你的账号是:"+t1+"密码是:"+t2);
	   }
	    });
	  //登录事件
	  bt2.addActionListener(new ActionListener() {
		  @SuppressWarnings("deprecation")
		  public void actionPerformed(ActionEvent e) {
			  if(pd==1||pd==0) 
			  {
				  File filename=new File("users.txt");
				  try {
					  FileReader inone=new FileReader(filename);
					  BufferedReader intwo=new BufferedReader(inone);
					  String s=null;
					  int b=1;
					  while((s=intwo.readLine())!=null) {
						  StringBuilder stringBuilder=new StringBuilder();
						  stringBuilder.append("id:");
						  stringBuilder.append(jt1.getText());
						  stringBuilder.append("&&");
						  stringBuilder.append("Password:");
						  stringBuilder.append(jt2.getText());
					     String ak=stringBuilder.toString();
					  if(s.equals(ak)) {
						  JOptionPane.showMessageDialog(null,"登录成功!");
						  jt1.setText("");
						  jt2.setText("");
						  //new Calculator().init();
						  new User();
						  jf1.dispose();
						  b=0;
						  break;
					  }
					  }
					  intwo.close();
					  inone.close();
					  if(b==1) {JOptionPane.showMessageDialog(null,"登陆失败!检查账号密码是否正确或请注册后登录",null,JOptionPane.ERROR_MESSAGE, null);
					 jt1.setText("");
					 jt2.setText("");
					  }
					  if(b==0) {//dispose();
					  return ;}
				  }catch(IOException ex) {ex.printStackTrace();}
			  }
		  }
	  });
	bt3.addActionListener(new ActionListener() {
		//@SuppressWarnings("deprecation")
    	public void actionPerformed(ActionEvent e){System.exit(0);}
	});}
	public static void main(String[] args) {
      new Login();
	}	
}

计算机界面

package wangrongchang;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.BevelBorder;
import javax.swing.JTextField;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.SystemColor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
import java.util.regex.Pattern;
public class User 
{
	//定义组件
	String key[]={"MC","MR","MS","M+","M-","sin","cos","tan","log","π","1", "2", "3", "+", "x²", "4", "5", "6", "-", "√", "7", "8", "9", "*", "1/x", "0", "(",
            ")", "÷", "n!", ".","%", "←", "c", "="};
	private JMenuBar jmb=new JMenuBar();
    private	JMenu []jm=new JMenu[3];
	JMenuItem[] jmi=new JMenuItem[6];
	JTextField[] jtf=new JTextField[3];//创建方框;
	JButton[] jb=new JButton[key.length];
	private JPanel jps=new JPanel();
	private JPanel jpb=new JPanel();
	private JFrame jf=new JFrame();
	//操作变量
	private String result=" ";
     private	String store="";//缓存字符串
	private String jtf2str;//给第三个文本框存放操作数
	boolean newDigital=true;//是否输入新的数的状态
	double d;//一元运算变量;
	double d1;//二元运算的前操作的数
	double d2;//二元运算的后操作数
	public User() 
	{
		//创建组件
		jm[0]=new JMenu("查看(V)");
	    jm[1]=new JMenu("编辑(E)");
	    jm[2]=new JMenu("帮助(H)");
	   
	    jmi[0]=new JMenuItem("二进制转换");
	    jmi[1]=new JMenuItem("八进制转换");
	    jmi[2]=new JMenuItem("十六进制转换");
	    jmi[3]=new JMenuItem("复制(C)");
	    jmi[4]=new JMenuItem("粘贴(P)");
	    jmi[5]=new JMenuItem("关于计算器(A)");
	    
	    for(int i=0;i<6;i++) 
	    jmi[i].addActionListener(new ButtonListener()); 
	    for(int i=0;i<key.length;i++) {
	    	jb[i]=new JButton(key[i]);
	    	jb[i].setContentAreaFilled(false);
	    	jb[i].setFocusable(false);
	    	jb[i].addActionListener(new ButtonListener());//给每个按钮添加监听处理  
	        jpb.add(jb[i]);
	    }
	    initGUI();//设置布局
	     jf.setTitle("欢迎使用计算器");
	    jf.setIconImage(new ImageIcon("t4.jpg").getImage());//设置背景
	    jf.setSize(500,500);//设置大小
	    jf.setLocation(200,200);//设置初始位置
	    jf.setVisible(true);//显示
	    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置默认到关闭操作
	}
	//设置布局
	public void initGUI() 
	{
		jf.setJMenuBar(jmb);
		jmb.add(jm[0]);
		jmb.add(jm[1]);
		jmb.add(jm[2]);
		jm[0].add(jmi[0]);
		jm[0].add(jmi[1]);
		jm[0].add(jmi[2]);
		jm[1].add(jmi[3]);
		jm[1].add(jmi[4]);
		jm[2].add(jmi[5]);
		//显示记忆索引值的文本框
		jtf[0]=new JTextField();
		jtf[0].setEditable(false);
		jtf[0].setHorizontalAlignment(JTextField.RIGHT);
		//显示M
		jtf[1]=new JTextField();
		jtf[1].setEditable(false);
		jtf[1].setHorizontalAlignment(JTextField.RIGHT);
		//显示输出结果
		jtf[2]=new JTextField("0");
		jtf[2].setEditable(false);
		jtf[2].setHorizontalAlignment(JTextField.RIGHT);
		jtf[2].setFont(new Font("arial",Font.BOLD,22));
		jtf[2].setForeground(Color.BLUE);
		jps.setLayout(new BorderLayout());
		jpb.setLayout(new GridLayout(7,5,4,4));
		jpb.setBorder(
	     new BevelBorder(BevelBorder.RAISED,new Color(180,180,180),null,SystemColor.scrollbar,null));
	//按键
	   	jps.add(jtf[0],BorderLayout.NORTH);
	   	jps.add(jtf[1],BorderLayout.CENTER);
	   	jps.add(jtf[2],BorderLayout.AFTER_LAST_LINE);
	   	jf.add(jpb,BorderLayout.CENTER);
	   	jf.add(jps,BorderLayout.NORTH);
	   	
	}
    /**
     * 事件处理
     *
     * @author
     *
     */
    public class ButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
        	String s1=e.getActionCommand();
            String content = String.valueOf(s1);
            boolean flag1 = jtf[0].getText().contains("=");
            // 输入处理的结果赋值给result
            result= parseInputStr(result,content);
            
            jtf[0].setText(result);
            // 控制计算结果后继续输入
              //store=result;
    		jtf2str=jtf[2].getText();//获取文本框中的字符串
    		if(e.getSource()==jmi[0]) {//二进制转换
    			int n=Integer.parseInt(jtf2str);
     		   jtf[2].setText(Integer.toBinaryString(n));
    		}
    		if(e.getSource()==jmi[1]){//八进制转换
    			int n=Integer.parseInt(jtf2str);
    			jtf[2].setText(Integer.toOctalString(n));
    		}
    		if(e.getSource()==jmi[2]) {//十六进制转换
    			int n=Integer.parseInt(jtf2str);
    			jtf[2].setText(Integer.toHexString(n));
    		}
    		if(e.getSource()==jmi[3]) {//复制
    			store=jtf2str;
    		}
    		if(e.getSource()==jmi[4]) {//粘贴
    			 jtf2str=store;
    			if(jtf2str=="")
    			jtf[2].setText("0");
    			else
    			jtf[2].setText(jtf2str);
    		}
    		if(e.getSource()==jmi[5])//关于计算器 
    		{
    			JOptionPane.showMessageDialog(null,"!!-_-!!王荣昌制作!!-_-!!");
    		}
    		if(s1.equals("MC"))
    			jtf[1].setText("");
    		if(s1.equals("MR")) 
    			jtf[2].setText(store);
    		if(s1.equals("MS")) {
    			jtf[1].setText("M");
    			result=jtf2str;
    		}
    		if(s1.equals("M+")) {
    			d1=Double.parseDouble(store);
    			d2=Double.parseDouble(jtf2str);
    			result=String.valueOf(d1+d2);
    		}
    		if(s1.equals("M-")) {
    			d1=Double.parseDouble(store);
    			d2=Double.parseDouble(jtf2str);
    			result=String.valueOf(d1-d2);
    		}	
            if (flag1 && content.matches("^\\d")) {
            	result= content;
                jtf[0].setText(result);
                jtf[2].setText("0");
            }
            if (content.equals("←"))
                backSpace();// 后退

            if (content.equals("c"))
                clear();// 清屏

            if (result.endsWith("=")) {
                String str = jtf[0].getText();
                // 如果(大于)数,报错“缺少)”
                if (countsOfSubstringInString(result, "(") > countsOfSubstringInString(result, ")")) {
                    jtf[2].setText("')' is missing!");
                    result= result.substring(0,result.length() - 1);

                }
                else if (result.contains("!")) {
                    int index = indexOfNumberStart(result.substring(0,result.indexOf('!')));
                    String s = result.substring(index,result.indexOf('!'));
                    if (parse(s) > 100)
                        jtf[2].setText("the argument for factorial is too large!");
                    else
                        calculate();
                }
                // 如果出现根号下负数,报错“负数没有平方根”
                else if (str.indexOf("sqt") != -1) {
                    int index = indexOfOpecifiedMirrorBracket(str, '(',
                            str.indexOf("sqt") + 3);
                    String s = str.substring(str.indexOf("sqt") + 4, index);
                    if (parse(s) < 0.0) {
                        jtf[2].setText("negative number do not have a square root!");
                    } else
                        calculate();
                }
                //如果出现log下的负数,报错"真数要大于0"
                else if(str.indexOf("log")!=-1) {
                	int index = indexOfOpecifiedMirrorBracket(str, '(',
                            str.indexOf("log") + 3);
                    String s = str.substring(str.indexOf("log") + 4, index);
                    if (parse(s) <=0.0) {
                        jtf[2].setText("The true number should be greater than 0!");
                    } else
                        calculate();
                }
                // 如果出现/0.0报错“0不能作为被除数”
                else if (jtf[0].getText().indexOf("/") != -1) {
                    String s = "";
                    int indexofdiv = indexOfNumberEnd(str, str.indexOf("/"));
                    s = str.substring(str.indexOf("/") + 1, indexofdiv);
                    if (parse(s) == Double.parseDouble("0")) {// 如果s=0
                        jtf[2].setText("0 can not be the dividend!");
                        result=result.substring(0,result.length() - 1);
                    } else
                        calculate();
                } else
                    calculate();
            }
        }
    }
    public static void main(String[] args) {
    	new User();
    }
//结果格式化
    public void calculate() {
    	result= String.valueOf(parse(result.substring(0,result.length() - 1)));
        jtf[2].setText(formatResult(result));
    }
    // 处理显示结果
    public String formatResult(String result) {
        String finalResult = "";
        Double d = Double.valueOf(result);
        NumberFormat nf = NumberFormat.getInstance();
        nf.setGroupingUsed(false);
        if (Math.abs(d) >= 1 || Math.abs(d) == 0)
            finalResult = nf.format(d);
        else
            finalResult = d.toString();
        return finalResult;
    }
    /**
     * 后退处理
     */
    public void backSpace() {
        if (result.length() == 1 ||result.equals("")) {
        	result= " ";
            jtf[0].setText(result);
        } else {
        	result=result.substring(0, result.length() - 1);
            if (result.endsWith(" "))
            	result= result.substring(0,result.length() - 1);
            jtf[0].setText(result);
        }
        jtf[2].setText(" ");
    }
    /**
     * 清屏处理
     *
     * @param content
     */
    public void clear() {
        jtf[2].setText(" ");
        jtf[0].setText(" ");
        result=" ";
        jtf[2].setText("0");
    }
    /**
     * 输入处理
     *
     * @param result
     * @param content
     * @return
     */
    public static String parseInputStr(String result, String content) {

        // 刚开始输入只能输入数字、π、-或者(
        if (result.equals(" ") || result.equals("")) {
            if (content.matches("\\d+|π|\\-|\\(*")) {
                result = "".concat(content);
            }
        }

        // 左括号数大于右括号数才能输入右括号
        else if (content.equals(")")) {
            boolean b = result.matches(".*\\d$|.*\\)$");// result以数字结尾或者右括号结尾
            if (countsOfSubstringInString(result, "(") > countsOfSubstringInString(result, ")") && b)
                result = result.concat(content);
            else
                result = result.concat("");
        }
        // 以数字结尾
        else if (Pattern.matches(".*\\d$|.*π$", result)) {
            // 不可输入00
            if (lastNumberOfStr(result).matches("^0+")
                    && /* !content.equals(".") &&!content.equals("=") && */ !content.matches("\\+|\\-|\\*|÷|\\.|="))
                result = result + "";
                // 数字后面跟x²,1/x,√
            else if (content.matches("x²|1/x|sin|cos|tan|log|√|n!")) {
                result = parseDigitEndWithFuncthion(result, content);
            }
            // x.y后不能接小数点,如2.1后不能输入点,不能出现2.1.2
            else if (Pattern.matches(".*\\.\\d+$", result)) {// 结果以.数字结尾
                result = result.concat(content.matches("\\d*|\\+|\\-|\\*|\\%|÷|\\)|=") ? content : "");
            }
            // 数字或小数点
            else if (content.matches("\\d|\\."))
                result = result.concat(content);
            else
                result = result.concat(content.matches("\\+|\\-|\\*|\\%|÷|\\)|=") ? " " + content : "");
        }
        // 以小数点结尾
        else if (Pattern.matches(".*\\.$", result) && Pattern.matches("^\\d", content)) {
            result = result.concat(content);
        }
        // 以左括号结尾
        else if ((result).matches(".*\\($")) {
            result = result.concat(content.matches("\\d*|π|\\-|\\(") ? content : "");
        }
        // 以右括号结尾
        else if (Pattern.matches(".*\\)$", result)) {
            if (content.matches("\\+|\\-|\\*|\\%|÷|=")) {
                result = result + " " + content;
            }
            if (content.matches("\\)")) {
                result = result + content;
            }
            if (content.matches("x²|√|1/x|sin|cos|tan|log")) {
                result = parseBrackets(result, content);
            }
        }
        // 以加减乘除结尾
        else if (result.matches(".*\\+$|.*\\-$|.*\\*$|.*÷$|.*/$|.*\\%$")) {
            result = result.replaceAll("÷", "/");
            if (result.matches(".*\\-$")) {// 以减号结尾
                if (result.length() == 1)
                    result = result + (content.matches("\\(|\\d|π") ? content : "");// 负号
                else if (result.length() > 1) {// 减号或左括号负号
                    boolean b = result.charAt(result.length() - 2) == '(';
                    if (b)
                        result = result + (content.matches("\\(|\\d|π") ? content : "");// 左括号负号
                    else
                        result = result + (content.matches("\\(|\\d|π") ? " " + content : "");// 减号
                }
            } else
                result = result + (content.matches("\\(|\\d|π") ? " " + content : "");
        }
        // 以!结尾
        else if (Pattern.matches(".*!$", result)) {
            result = result + (content.matches("\\+|\\-|\\%|\\*|/|=|\\)") ? content : "");
        }
        return result;
    }
    /**
     * 计算处理
     *
     * @param content
     * @return
     */
    public static double parse(String content) {
        // 处理π
        if (content.contains("π"))
            content =content.replace("π",""+Math.PI);
        if (content.contains("1/x"))
            content = content.replace("1/x", "rec");
        // 处理乘以负数*-
        if (content.contains("*-") || content.matches(".*(\\*\\s\\-).*")) {
            content = content.replaceAll("\\*\\s\\-", "*-");
            content = multiplicationAndDivisionOfNegative(content, "*");
        }
        // 处理除以负数/-
        if (content.contains("/-") || content.matches(".*(/\\s\\-).*")) {
            content = content.replaceAll("/\\s\\-", "/-");
            content = multiplicationAndDivisionOfNegative(content, "/");
        }
        // --转成+
        if (content.contains("--") || content.matches(".*(\\-\\s\\-).*")) {
            content = content.replaceAll("\\-\\s\\-", "+");
            content = content.replaceAll("\\-\\-", "+");
        }

        // 处理平方
        int index = content.indexOf("sqr");
        if (index != -1) {
            int endindex = indexOfOpecifiedMirrorBracket(content, '(', index + 3);
            String d = "(" + content.substring(index + 3, endindex + 1) + "*"
                    + content.substring(index + 3, endindex + 1) + ")";
            return parse(content.substring(0, index) + d + content.substring(endindex + 1));
        }
        //处理sin
        index=content.indexOf("sin");
        if (index != -1) {
            int endindex = indexOfOpecifiedMirrorBracket(content, '(', index + 3);
            double d=Math.sin(parse(content.substring(index+3,endindex+1)));
            return parse(content.substring(0, index) + d + content.substring(endindex + 1));
        }
        //处理cos
        index=content.indexOf("cos");
        if (index != -1) {
            int endindex = indexOfOpecifiedMirrorBracket(content, '(', index + 3);
            double d=Math.cos(parse(content.substring(index+3,endindex+1)));
            return parse(content.substring(0, index) + d + content.substring(endindex + 1));
        }
        //处理tan
        index=content.indexOf("tan");
        if (index != -1) {
            int endindex = indexOfOpecifiedMirrorBracket(content, '(', index + 3);
            double d=Math.tan(parse(content.substring(index+3,endindex+1)));
            return parse(content.substring(0, index) + d + content.substring(endindex + 1));
        }
        //处理log
        index=content.indexOf("log");
        if (index != -1) {
            int endindex = indexOfOpecifiedMirrorBracket(content, '(', index + 3);
            double d=Math.log(parse(content.substring(index+3,endindex+1)));
            return parse(content.substring(0, index) + d + content.substring(endindex + 1));
        }
        // 处理开方
        index = content.indexOf("sqt");
        if (index != -1) {
            int endindex = indexOfOpecifiedMirrorBracket(content, '(', index + 3);
            double d = Math.sqrt(parse(content.substring(index + 3, endindex + 1)));
            return parse(content.substring(0, index) + d + content.substring(endindex + 1));
        }
        // 处理求倒
        index = content.indexOf("rec");
        if (index != -1) {
            int endindex = indexOfOpecifiedMirrorBracket(content, '(', index + 3);
            double d = parse("1/" + content.substring(index + 3, endindex + 1));
            return parse(content.substring(0, index) + d + content.substring(endindex + 1));
        }
        // 处理括号
        int startindex = content.indexOf("(");
        boolean b = countsOfSubstringInString(content, "(") == countsOfSubstringInString(content, ")");
        if (startindex != -1 && b) {
            int endindex = indexOfFirstMirrorBracket(content, '(');
            double d = parse(content.substring(startindex + 1, endindex));
            return parse(content.substring(0, startindex) + d + content.substring(endindex + 1));
        }
        // 处理阶乘,由于阶乘很容易越界,故不考虑括号阶乘了
        index = content.indexOf("!");
        if (index != -1) {
            double d = factorial(parse(content.substring(indexOfLeftOperator(content, index) + 1, index)));
            return parse(
                    content.substring(0, indexOfLeftOperator(content, index) + 1) + d + content.substring(index + 1));
        }
        // 处理加法
        index = content.indexOf("+");
        if (index != -1) {
            return parse(content.substring(0, index)) + parse(content.substring(index + 1));
        }
        // 处理减法
        index = content.lastIndexOf("-");
        if (index != -1) {
            return parse(content.substring(0, index)) - parse(content.substring(index + 1));
        }
        //处理求模
        index=content.indexOf("%");
        if(index!=-1)
        return parse(content.substring(0,index)) % parse(content.substring(index+1));
        // 处理乘法
        index = content.indexOf("*");
        if (index != -1) {
            return parse(content.substring(0, index)) * parse(content.substring(index + 1));
        }
        // 处理除法
        index = content.lastIndexOf("/");
        if (index != -1) {
            return parse(content.substring(0, index)) / parse(content.substring(index + 1));
        }
        // 处理空格
        if (content.equals("") || content.equals(" "))
            content = "0";
        // 最后结果
        return Double.parseDouble(content);
    }
    /**
     * 阶乘实现
     */
    public static double factorial(double d) {
        return (d == 0.0 ? 1 : d * factorial(d - 1));
    }

    /**
     * 字符串中某子字符串的数量
     */
    public static int countsOfSubstringInString(String string, String substring) {
        int sum = 0;
        String subStrHead = "";
        String subStrTrail = "";
        while (string.contains(substring)) {
            sum++;
            subStrHead = string.substring(0, string.indexOf(substring));
            subStrTrail = string.substring(subStrHead.length() + substring.length());
            string = subStrHead + subStrTrail;
        }
        return sum;
    }

    /**
     * 找最左边的左括号的镜像括号的位置,或者最右边的右括号的镜像括号的位置
     */
    public static int indexOfFirstMirrorBracket(String s, char c) {
        int indexresult = -1;
        int sum = 0;
        if (countsOfSubstringInString(s, "(") == countsOfSubstringInString(s, ")")) {
            if (c == '(') {
                int index = s.indexOf(c) - 1;
                do {
                    index++;
                    if (s.charAt(index) == '(')
                        sum++;
                    if (s.charAt(index) == ')')
                        sum--;
                } while (sum != 0 && index < s.length());
                indexresult = index - 1;
            }
            if (c == ')') {
                int index = s.lastIndexOf(c);
                do {
                    if (s.charAt(index) == ')') {
                        sum++;
                    }
                    if (s.charAt(index) == '(')
                        sum--;
                    index--;
                } while (sum != 0 && index >= 0);
                indexresult = index;
            }
        }
        return indexresult + 1;
    }
    /**
     * 指定位置的括号的镜像括号
     */
    public static int indexOfOpecifiedMirrorBracket(String s, char c, int index) {
        int indexresult = -1;
        int sum = 0;
        int startIndex = -1;
        int endIndex = -1;
        StringBuffer sb = new StringBuffer(s);
        if (countsOfSubstringInString(s, "(") == countsOfSubstringInString(s, ")")) {
            if (index == 0 || index == s.length() - 1)
                return indexOfFirstMirrorBracket(s, c);
            else if (c == '(') {
                sum = countsOfSubstringInString(s.substring(0, index), String.valueOf(c));
                while (sum != 0) {
                    startIndex = sb.indexOf("(");
                    endIndex = indexOfFirstMirrorBracket(sb.toString(), c);
                    sb = sb.replace(startIndex, startIndex + 1, "a").replace(endIndex, endIndex + 1, "a");
                    sum--;
                }
                indexresult = indexOfFirstMirrorBracket(sb.toString(), c);
            } else if (c == ')') {
                sum = countsOfSubstringInString(s.substring(index + 1), String.valueOf(c));
                while (sum != 0) {
                    startIndex = sb.indexOf(")");
                    endIndex = indexOfFirstMirrorBracket(sb.toString(), c);
                    sb = sb.replace(startIndex, startIndex + 1, "a").replace(endIndex, endIndex + 1, "a");
                    sum--;
                }
                indexresult = indexOfFirstMirrorBracket(sb.toString(), c);
            }
        }
        return indexresult;
    }

    /**
     * 某个位置前面最近一个算术运算符的位置
     *
     * @param s
     * @param specifiedIndex
     * @return
     */
    public static int indexOfLeftOperator(String s, int specifiedIndex) {
        int temp = -1;
        if (specifiedIndex >= 1 && s.substring(0, specifiedIndex).matches(".*(\\-|\\+|\\%|\\*|/).*")) {
            do {
                specifiedIndex--;
            } while (!String.valueOf(s.charAt(specifiedIndex)).matches("\\+|\\-|\\%|\\*|/"));
            temp = specifiedIndex;
        }
        return temp;
    }

    /**
     * 某个位置后面最近一个算术运算符的位置
     */
    public static int indexOfRightOperator(String s, int specifiedIndex) {
        int temp = -1;
        boolean b = specifiedIndex >= 0 && specifiedIndex <= s.length() - 1
                && s.substring(specifiedIndex + 1).matches(".*(\\+|\\-|\\%|\\*|/).*");
        if (b) {
            while (!String.valueOf(s.charAt(specifiedIndex + 1)).matches("\\+|\\-|\\%|\\*|/")) {
                specifiedIndex++;
            }
            temp = specifiedIndex + 1;
        }
        return temp;
    }

    /**
     * 处理算式中的*-和/-
     */
    public static String multiplicationAndDivisionOfNegative(String content, String operator) {
        int indexofoperator = content.indexOf(operator);
        int startindex = indexOfLeftOperator(content, indexofoperator);// indexofoperator左边最近的运算符+-*/的位置
        if (startindex == -1) {
            content = "-" + content.substring(0, content.indexOf(operator) + 1)
                    + content.substring(content.indexOf(operator) + 2);
        }
        if (startindex != -1) {
            if (content.substring(indexofoperator, indexofoperator + 2).equals(operator + "-")) {
                String tempstr = "-" + content.substring(startindex + 1, indexofoperator + 1);
                content = content.substring(0, startindex + 1) + tempstr + content.substring(indexofoperator + 2);
            }
        }
        return content;
    }

    /**
     * 找数字结尾的字符串结束位置开始往前的一个完整数字的位置
     *
     * @param result
     * @return
     */
    public static int indexOfNumberStart(String result) {
        int resultIndex = -1;
        int indexOfOperator = indexOfLeftOperator(result, result.length() - 1);// 该位置前面第一个运算符位置
        if (indexOfOperator == -1) {//前面没有运算符
            indexOfOperator = result.lastIndexOf('(');
            if (indexOfOperator == -1)
                resultIndex = 0;
            else
                resultIndex = indexOfOperator + 1;
        } else {
            if(result.charAt(indexOfOperator) == '-' && result.charAt(indexOfOperator + 1) != ' ')
                resultIndex = indexOfOperator;
            else{
                while (result.charAt(indexOfOperator + 1) == '(' || result.charAt(indexOfOperator + 1) == ' ')
                    indexOfOperator++;
                resultIndex = indexOfOperator + 1;
            }
        }
        return resultIndex;
    }

    /**
     * 找运算符位置往后完整数字的位置
     *
     * @param result
     * @param index
     * @return
     */
    public static int indexOfNumberEnd(String result, int index) {
        int resultIndex = -1;
        int indexOfOperator = indexOfRightOperator(result, index + 1);
        String subStrStart = result.substring(0, index + 1);
        String subStrEnd = result.substring(index + 1);
        if (indexOfOperator == -1) {// 没有运算符
            if (result.substring(index + 1).contains("(")) {
                int startIndex = subStrStart.length() + subStrEnd.indexOf('(');
                int endIndex = indexOfOpecifiedMirrorBracket(result, '(', startIndex);
                resultIndex = endIndex + 1;
            } else if (indexOfOperator == -1) {
                while (index < result.length() && String.valueOf(result.charAt(index + 1)).matches("\\s|\\d|\\."))
                    index++;
                resultIndex = index + 1;
            }
        } else {
            if (result.substring(index + 1, indexOfOperator).contains("(")) {
                int startIndex = subStrStart.length() + subStrEnd.indexOf('(');
                int endIndex = indexOfOpecifiedMirrorBracket(result, '(', startIndex);
                resultIndex = endIndex + 1;
            } else
                resultIndex = indexOfOperator;
        }
        return resultIndex;
    }

    /**
     * 以数字结尾的字符串的最后一个完整的数字字符串
     *
     * @param result
     * @return
     */
    public static String lastNumberOfStr(String result) {
        int indexTemp = indexOfLeftOperator(result, result.length() - 1);
        boolean b = String.valueOf(result.charAt(result.length() - 1)).matches("\\d");
        if (indexTemp <= result.length() - 1 && b) {
            while (!String.valueOf(result.charAt(indexTemp + 1)).matches("\\d"))
                indexTemp++;
            return result.substring(indexTemp + 1);
        } else
            return "";
    }

    /**
     * 右括号后面跟平方、求倒、开方
     *
     * @param result
     * @param content
     * @return
     */
    public static String parseBrackets(String result, String content) {
        String temp = "";
        int startIndex = indexOfFirstMirrorBracket(result, ')');
        int indexOfOperator = indexOfLeftOperator(result, startIndex);
        String substrhead = "";
        String substrtrail = "";
        if (indexOfOperator == -1)
            substrtrail = result;
        else {
            substrhead = result.substring(0, indexOfOperator + 2);
            substrtrail = result.substring(indexOfOperator + 2);
        }
        if (content.equals("√")) {
            if (substrtrail.startsWith("(") && substrtrail.endsWith(")")
                    && indexOfFirstMirrorBracket(substrtrail, '(') == substrtrail.length() - 1)
                temp = substrhead + "sqt" + substrtrail;
            else
                temp = substrhead + "sqt(" + substrtrail + ")";
        }
        if (content.equals("x²")) {
            if (substrtrail.startsWith("(") && substrtrail.endsWith(")")
                    && indexOfFirstMirrorBracket(substrtrail, '(') == substrtrail.length() - 1)
                temp = substrhead + "sqr" + substrtrail;
            else
                temp = substrhead + "sqr(" + substrtrail + ")";
        }
        if (content.equals("1/x")) {
            if (substrtrail.startsWith("(") && substrtrail.endsWith(")")
                    && indexOfFirstMirrorBracket(substrtrail, '(') == substrtrail.length() - 1)
                temp = substrhead + "rec" + substrtrail;
            else
                temp = substrhead + "rec(" + substrtrail + ")";
        }
        if (content.equals("sin")) {
            if (substrtrail.startsWith("(") && substrtrail.endsWith(")")
                    && indexOfFirstMirrorBracket(substrtrail, '(') == substrtrail.length() - 1)
                temp = substrhead + "sin" + substrtrail;
            else
                temp = substrhead + "sin(" + substrtrail + ")";
        }
        if (content.equals("cos")) {
            if (substrtrail.startsWith("(") && substrtrail.endsWith(")")
                    && indexOfFirstMirrorBracket(substrtrail, '(') == substrtrail.length() - 1)
                temp = substrhead + "cos" + substrtrail;
            else
                temp = substrhead + "cos(" + substrtrail + ")";
        }
        if (content.equals("tan")) {
            if (substrtrail.startsWith("(") && substrtrail.endsWith(")")
                    && indexOfFirstMirrorBracket(substrtrail, '(') == substrtrail.length() - 1)
                temp = substrhead + "tan" + substrtrail;
            else
                temp = substrhead + "tan(" + substrtrail + ")";
        }
        if (content.equals("log")) {
            if (substrtrail.startsWith("(") && substrtrail.endsWith(")")
                    && indexOfFirstMirrorBracket(substrtrail, '(') == substrtrail.length() - 1)
                temp = substrhead + "log" + substrtrail;
            else
                temp = substrhead + "log(" + substrtrail + ")";
        }
        if (temp.startsWith("(") && temp.endsWith(")") && indexOfFirstMirrorBracket(temp, '(') == temp.length() - 1)
            temp = temp.substring(1, temp.length() - 1);

        return temp;
    }

    /**
     * 数字结尾后面跟平方、求倒、开方
     *
     * @param result
     * @param content
     * @return
     */
    public static String parseDigitEndWithFuncthion(String result, String content) {
        String temp = "";
        String contentTemp = "";
        if (content.equals("1/x"))
            contentTemp = "rec";
        if (content.equals("n!"))
            contentTemp = "!";
        if (content.equals("x²"))
            contentTemp = "sqr";
        if (content.equals("√"))
            contentTemp = "sqt";
        if(content.equals("sin"))
        	contentTemp= "sin";
        if(content.equals("cos"))
        	contentTemp= "cos";
        if(content.equals("tan"))
        	contentTemp= "tan";
        if(content.equals("log"))
        	contentTemp= "log";
        int startIndex = indexOfNumberStart(result);// 数字的开头
        String substrhead = result.substring(0, startIndex);
        String substrtrail = result.substring(startIndex);
        if (result.startsWith("-") && startIndex == 1) {
            if (contentTemp == "!")
                temp = "-" + result.substring(startIndex) + "!";
            else
                temp = contentTemp + "(" + result + ")";
        } else {
            if (contentTemp == "!") {
                if (substrtrail.endsWith("π") || substrtrail.matches(".*\\.\\d*[1-9]+$"))
                    temp = result;
                else
                    temp = substrhead + substrtrail + contentTemp;
            } else
                temp = substrhead + contentTemp + "(" + substrtrail + ")";
        }
        return temp;
    }
}    	

    原文作者:王朝的宇宙 .
    原文地址: https://blog.csdn.net/qq_44648017/article/details/97618922
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞