计算器输入计算式输出结果

这个比较简单,只能实现两个数的加减乘除运算,后面那个虽然实现了输入式子输出结果,但是比较麻烦。

import java.util.Scanner;

public class Calculator {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个算式(加:+减:-乘:*除:/)[结束请按q\\Q]");
        String s = sc.nextLine();
        do {

            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                if(c=='+') {
                    add( Double.parseDouble(s.substring(0,i)),Double.parseDouble(s.substring(i+1,s.length())));
                }else if(c=='-') {
                    sub( Double.parseDouble(s.substring(0,i)),Double.parseDouble(s.substring(i+1,s.length())));
                }else if(c=='*') {
                    mul( Double.parseDouble(s.substring(0,i)),Double.parseDouble(s.substring(i+1,s.length())));
                }else if(c=='/') {
                    div( Double.parseDouble(s.substring(0,i)),Double.parseDouble(s.substring(i+1,s.length())));
                }
            }
            s = sc.nextLine();
        }while(!s.equalsIgnoreCase("q"));
        sc.close();
    }
    //+-*/方法
    public static void add(double a,double b) {
        System.out.println("="+(a+b));
    }
    public static void sub(double a,double b) {
        System.out.println("="+(a-b));
    }
    public static void mul(double a,double b) {
        System.out.println("="+(a*b));
    }
    public static void div(double a,double b) {
        System.out.println("="+(a/b));
    }
}

运行结果:

请输入一个算式(加:+减:-乘:*除:/)[结束请按q\Q]
3+3
=6.0
5/3
=1.6666666666666667
9*0.3
=2.6999999999999997
3*5
=15.0
Q

然后我想了想能不能实现输入个运算式输出结果呢,经过想了好几个小时,终于实现了,由于刚学了十天,可能做的比较复杂了。毕竟好多java自带的API都还不知道。然而这个还不能实现括号输入,再想想,嘻嘻

import java.util.ArrayList;
import java.util.Scanner;

public class CalculatorAnother {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个算式(加:+减:-乘:*除:/)[结束请按q\\Q]");
        String s = sc.nextLine();
        //循环输入算式
        do {
            //存放+-*/运算符
            ArrayList<Integer> arrYsf = new ArrayList<Integer>();
            //存放+-运算符
            ArrayList<Integer> arrJj = new ArrayList<Integer>();
            //存放*/运算符
            ArrayList<Integer> arrCc = new ArrayList<Integer>();
            //存放所有的数字
            ArrayList<Double> arrDouble = new ArrayList<Double>();
            char[] cs = s.toCharArray();
            boolean b = false;
            double a;
            //遍历字符串,把是运算符的索引存进arrYsf里面
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                if(c=='+'||c=='-'||c=='*'||c=='/') {
                    arrYsf.add(i);
                }
            }
            //遍历字符串,把加减法和乘除法分别存进arrJj和arrCc数组里面
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                if(c=='+'||c=='-') {
                    arrJj.add(i);
                }else if(c=='*'||c=='/'){
                    arrCc.add(i);
                }
            }
            //得到所有的数并存进arrDouble
            for (int j = 0; j <= arrYsf.size(); j++) {
                if(j==0) {
                    arrDouble.add(Double.parseDouble(s.substring(0,arrYsf.get(j))));
                }
                else if(j==arrYsf.size()){
                    arrDouble.add(Double.parseDouble(s.substring(arrYsf.get(j-1)+1,s.length())));
                }
                else {
                    arrDouble.add(Double.parseDouble(s.substring(arrYsf.get(j-1)+1,arrYsf.get(j))));
                }
            }
            //打印arrDouble(测试用)
            /*for (int i = 0; i < arrDouble.size(); i++) {
                System.out.println(arrDouble.get(i));
            }*/

            //循环计算乘除法,每次计算一个乘法或者除法
            do {
                b = false;
                if(arrCc.isEmpty()) {
                    break;
                }else {
                //运算乘除法,把结果放回arrDouble数组替换已经运算的数字,并去除arrCc已经使用的元素
                    for (int j = 0; j < arrYsf.size(); j++) {
                        if(arrYsf.get(j)==arrCc.get(0)) {
                            if(cs[arrYsf.get(j)]=='*') {
                                a = mul(arrDouble.get(j),arrDouble.get(j+1));
                                arrDouble.remove(j);
                                arrDouble.remove(j);
                                arrDouble.add(j, a);
                                arrYsf.remove(j);
                                arrCc.remove(0);
                                b = true;
                                break;
                            }else if(cs[arrYsf.get(j)]=='/') {
                                a = div(arrDouble.get(j),arrDouble.get(j+1));
                                arrDouble.remove(j);
                                arrDouble.remove(j);
                                arrDouble.add(j, a);
                                arrYsf.remove(j);
                                arrCc.remove(0);
                                b = true;
                                break;
                            }
                        }
                    }
                }
            }while(b);
            //循环计算加减法,每次计算一个乘法或者加法
            do {
                b = false;
                //运算加减法,把结果放回arrDouble数组替换已经参与运算的数字,并去除arrJj已经使用的元素
                if(arrJj.isEmpty()) {
                    break;
                }else {
                    for (int j = 0; j < arrYsf.size(); j++) {
                        if(arrYsf.get(j)==arrJj.get(0)) {
                            if(cs[arrYsf.get(j)]=='+') {
                                a = add(arrDouble.get(j),arrDouble.get(j+1));
                                arrDouble.remove(j);
                                arrDouble.remove(j);
                                arrDouble.add(j, a);
                                arrYsf.remove(j);
                                arrJj.remove(0);
                                b = true;
                                break;
                            }else if(cs[arrYsf.get(j)]=='-') {
                                a = sub(arrDouble.get(j),arrDouble.get(j+1));
                                arrDouble.remove(j);
                                arrDouble.remove(j);
                                arrDouble.add(j, a);
                                arrYsf.remove(j);
                                arrJj.remove(0);
                                b = true;
                                break;
                            }
                        }
                    }
                }
            }while(b);  
            System.out.println("="+arrDouble.get(0));
            s = sc.nextLine();
        }while(!s.equalsIgnoreCase("q"));
        sc.close();
    }

    public static double add(double a,double b) {
        return a+b;
    }
    public static double sub(double a,double b) {
        return a-b;
    }
    public static double mul(double a,double b) {
        return a*b;
    }
    public static double div(double a,double b) {
        return a/b;
    }
}

运行结果:

请输入一个算式(加:+减:-乘:*除:/)[结束请按q\Q]
5*5+5-3-2/1+6*1-6
=25.0
5+5
=10.0
5+5+5+5+5+5+5+5
=40.0
q
你可以使用 Java 的 Swing 库来创建一个简单的计算器界面,然后使用 Java 的计算功能来计算输入的表达。以下是一个简单的示例代码: ``` import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Calculator extends JFrame implements ActionListener { private JTextField inputField; private JButton[] numberButtons; private JButton[] operatorButtons; private JButton equalsButton; private JButton clearButton; public Calculator() { super("Calculator"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new BorderLayout()); inputField = new JTextField(); add(inputField, BorderLayout.NORTH); JPanel buttonPanel = new JPanel(new GridLayout(4, 4)); numberButtons = new JButton[10]; for (int i = 0; i < 10; i++) { numberButtons[i] = new JButton("" + i); numberButtons[i].addActionListener(this); buttonPanel.add(numberButtons[i]); } operatorButtons = new JButton[4]; operatorButtons[0] = new JButton("+"); operatorButtons[1] = new JButton("-"); operatorButtons[2] = new JButton("*"); operatorButtons[3] = new JButton("/"); for (int i = 0; i < 4; i++) { operatorButtons[i].addActionListener(this); buttonPanel.add(operatorButtons[i]); } equalsButton = new JButton("="); equalsButton.addActionListener(this); buttonPanel.add(equalsButton); clearButton = new JButton("C"); clearButton.addActionListener(this); buttonPanel.add(clearButton); add(buttonPanel, BorderLayout.CENTER); pack(); setVisible(true); } public void actionPerformed(ActionEvent e) { Object source = e.getSource(); if (source == equalsButton) { String expression = inputField.getText(); try { double result = evaluate(expression); inputField.setText("" + result); } catch (Exception ex) { inputField.setText("Error"); } } else if (source == clearButton) { inputField.setText(""); } else { String text = ((JButton)source).getText(); inputField.setText(inputField.getText() + text); } } private double evaluate(String expression) throws Exception { String[] tokens = expression.split(" "); Stack<Double> stack = new Stack<Double>(); for (String token : tokens) { if (isNumber(token)) { stack.push(Double.parseDouble(token)); } else if (isOperator(token)) { double operand2 = stack.pop(); double operand1 = stack.pop(); double result = applyOperator(token, operand1, operand2); stack.push(result); } else { throw new Exception("Invalid expression"); } } return stack.pop(); } private boolean isNumber(String token) { try { Double.parseDouble(token); return true; } catch (NumberFormatException e) { return false; } } private boolean isOperator(String token) { return token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/"); } private double applyOperator(String operator, double operand1, double operand2) throws Exception { if (operator.equals("+")) { return operand1 + operand2; } else if (operator.equals("-")) { return operand1 - operand2; } else if (operator.equals("*")) { return operand1 * operand2; } else if (operator.equals("/")) { if (operand2 == 0) { throw new Exception("Division by zero"); } return operand1 / operand2; } else { throw new Exception("Invalid operator"); } } public static void main(String[] args) { new Calculator(); } } ``` 这个计算器可以处理简单的四则运算,例如 "2 + 3 * 4",并且可以处理错误情况,例如除以零。你可以在文本框中输入表达,然后按下 "=" 按钮来计算结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值