java、C語言、JavaScript寫四則運算,模擬簡單的計算器

簡單的計算器的實現

java的swing

package Test0602;

/**
 * @Auther: Xinbai
 * @Date:2020/6/2 19:08
 */
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class Calculator extends JFrame {

    public Calculator(){

        setLayout(new FlowLayout(FlowLayout.LEFT,10,20)); //建立流式佈局
        add(new JLabel("Number 1"));
        JTextField tf1 = new JTextField(3); //文本框JTextFiled
        add(tf1);

        add(new JLabel("Number 2"));
        JTextField tf2 = new JTextField(3); //文本框JTextFiled
        add(tf2);

        add(new JLabel("result"));
        JTextField tf3 = new JTextField(5); //文本框JTextFiled
        add(tf3);

        JButton btnAdd = new JButton("Add"); //Add按鈕引用對象名爲btnAdd
        add( btnAdd);

        btnAdd.addActionListener(new ActionListener() { //加一個監聽器

            public void actionPerformed(ActionEvent e) { //實現功能的方法

                double result = Double.parseDouble(tf1.getText()) + Double.parseDouble(tf2.getText());
                tf3.setText(result+"");  //將result的結果轉換爲string形式顯示在tf3對應的文本框中
            }
        });

        JButton btnSubtract = new JButton("Subtract");
        add(btnSubtract);

        btnSubtract.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e) {

                double result = Double.parseDouble(tf1.getText()) - Double.parseDouble(tf2.getText());

                tf3.setText(result+"");
            }
        });

        JButton btnMultiply = new JButton("Multiply");
        add(btnMultiply);

        btnMultiply.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e) {

                double result = Double.parseDouble(tf1.getText()) * Double.parseDouble(tf2.getText());

                tf3.setText(result+"");
            }
        });

        JButton btnDivide = new JButton("Divide");
        add(btnDivide);

        btnDivide.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e) {

                double result = Double.parseDouble(tf1.getText()) / Double.parseDouble(tf2.getText());

                tf3.setText(result+"");
            }
        });
    }


    public static void main(String[] args) {

        Calculator frame = new Calculator();

        frame.setTitle("計算器"); //設置標題

        frame.setSize(400,200); //設置框的初始大小

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); /*設置關閉按鈕*/

        frame.setVisible(true); //顯示界面
    }
}

在這裏插入圖片描述

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Stack;
/**
 * @Auther: Xinbai
 * @Date:2020/6/2 18:39
 */

    class MyException extends Exception{
        public MyException() {
            super();
        }
        public MyException(String message) {
            super(message);
        }
    }


public class Caculate extends JFrame {
        /*
         *
         */

        private JTextField textField;               //輸入文本框
        private String input;                       //結果
        private String operator;                    //操作符

        public Caculate() {
            input = "";
            operator = "";

            JPanel panel = new JPanel();
            textField = new JTextField(30);
            textField.setEditable(false);                       //文本框禁止編輯
            textField.setHorizontalAlignment(JTextField.LEFT);
            //textField.setBounds(100, 100, 20, 20);            //在容器佈局爲空情況下生效
            textField.setPreferredSize(new Dimension(200,30));//設置該組件的初始大小

            //將textField加入本JFrame中,佈局爲邊界佈局,位置爲north
            this.add(textField, BorderLayout.NORTH);

            String[] name= {"7","8","9","+","4","5","6","-","1","2","3","*","0","C","=","/"};

            //將這個panel的佈局設置爲網格佈局,有四行四列,行間距和列間距爲1
            panel.setLayout(new GridLayout(4,4,1,1));

            for(int i=0;i<name.length;i++) {

                JButton button = new JButton(name[i]);

                //設置按鈕的時間監聽
                button.addActionListener(new MyActionListener());
                //將按鈕加入到panel中
                panel.add(button);
            }
            //將panel加入到本JFrame中,佈局爲邊界佈局,位置爲centre
            this.add(panel,BorderLayout.CENTER);
        }

        class MyActionListener implements ActionListener{           //內部類實現按鈕響應

            @Override
            public void actionPerformed(ActionEvent e) {
                int cnt=0;
                String actionCommand = e.getActionCommand();            //獲取按鈕上的字符串
                if(actionCommand.equals("+") || actionCommand.equals("-") || actionCommand.equals("*")
                        || actionCommand.equals("/")) {
                    input += " " + actionCommand + " ";
                }
                else if(actionCommand.equals("C")) {                    //清除輸入
                    input = "";
                }
                else if(actionCommand.equals("=")) {                    //按下等號
                    try {
                        input+= "="+calculate(input);
                    } catch (MyException e1) {
                        if(e1.getMessage().equals("被除數不能爲0"))
                            input = e1.getMessage();
                        else
                            input = e1.getMessage();
                    }
                    textField.setText(input);
                    input="";
                    cnt = 1;
                }
                else
                    input += actionCommand;                         //按下數字

                //因爲如果不按“=”按鈕cnt一直未0,所以可以保證顯示輸入的數字和操作鍵
                if(cnt == 0)
                    textField.setText(input);
            }
        }

        private String calculate(String input) throws MyException{              //計算函數
            String[] comput = input.split(" ");
            //System.out.println(input);
            Stack<Double> stack = new Stack<>();
            Double m = Double.parseDouble(comput[0]);
            stack.push(m);                                      //第一個操作數入棧

            for(int i = 1; i < comput.length; i++) {
                if(i%2==1) {
                    if(comput[i].equals("+"))
                        stack.push(Double.parseDouble(comput[i+1]));
                    if(comput[i].equals("-"))
                        stack.push(-Double.parseDouble(comput[i+1]));
                    if(comput[i].equals("*")) {                 //將前一個數出棧做乘法再入棧
                        Double d = stack.peek();                //取棧頂元素
                        stack.pop();
                        stack.push(d*Double.parseDouble(comput[i+1]));
                    }
                    if(comput[i].equals("/")) {                 //將前一個數出棧做乘法再入棧
                        double help = Double.parseDouble(comput[i+1]);
                        if(help == 0)
                            throw new MyException("被除數不能爲0");           //不會繼續執行該函數
                        double d = stack.peek();
                        stack.pop();
                        stack.push(d/help);
                    }
                }
            }

            double d = 0d;

            while(!stack.isEmpty()) {           //求和
                d += stack.peek();
                stack.pop();
            }

            String result = String.valueOf(d);
            return result;
        }

        public static void main(String[] args) {
            JFrame f = new Caculate();
            f.setTitle("計算器"); //設置標題
//            f.setTitle(f.getClass().getSimpleName());
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setBounds(400, 200, 500, 300);
            f.setVisible(true);
        }
    }

在這裏插入圖片描述

java


import java.util.Scanner;

/**
 * @Auther: Xinbai
 * @Date:2020/6/2 19:24
 */
public class Test {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (true) {
            System.out.println("請輸入第一個數:");
            int num1 = sc.nextInt();
            System.out.println("輸入操作符[輸入1表示+,2表示-,3表示*,4表示/]:");
            int s = sc.nextInt();
            System.out.println("請輸入第二個數:");
            int num2 = sc.nextInt();
            if (s == 1) {
                System.out.println(num1 + num2);
            } else if (s == 2) {
                System.out.println(num1 - num2);
            } else if (s == 3) {
                System.out.println(num1 * num2);
            } else if (s == 4) {
                if (num2 == 0) {
                    System.out.println("除數不能爲0");
                } else
                    System.out.println(num1 / num2);
            } else
                System.out.println("輸入有誤");
        }
    }
}

C語言

#include <stdio.h>
int main()
{
int a,b,result;
char m; 
while(true){
printf("請輸入計算式[加減乘除]:\n");
scanf("%d%c%d",&a,&m,&b);
if(m=='+')          //判斷是否進行加法運算,以下同理
result=a+b;
else if(m=='-')     
result=a-b;
else if(m=='*')
result=a*b;
else if(m=='/'){ 
if(b==0){
	printf("除數不能爲0,請重新輸入!"); //如果除數爲0,提示報錯 
} 
result=a/b;
printf("餘數爲:%d\n",a%b);
} 
else 
printf("您輸入有誤\n");   //如果輸入的符號非+-*或非/,報錯
printf("計算結果爲:%d\n",result);    //最後輸出結果
}
}

在這裏插入圖片描述

JavaScript

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>四則運算</title>
	</head>
	<body>
		<p>請輸入兩個數進行簡單的運算:</p>
		<input type="text" id="num1" />
		<select id="selete">
			<option value="+">+</option>
			<option value="-">-</option>
			<option value="*">*</option>
			<option value="/">/</option>
		</select>
		<input type="text" id="num2" />
		<input type="button" value="=" onclick="test()" />
		<input type="text" id="result" />
		<script type="text/javascript">
			function test() {
				var n1 = parseFloat(document.getElementById("num1").value);
				var n2 = parseFloat(document.getElementById("num2").value);
		
				var s1 = document.getElementById("selete").value;
				switch (s1) {
					case '+':
					 answer= n1 + n2;
						break;
					case '-':
					answer= n1 - n2;
						break;
					case '*':
					answer= n1 * n2;
						break;
					case '/':
					answer= n1 / n2;
						break;
				}
				document.getElementById("result").value=answer;
			}
		</script>
	</body>
</html>

在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章