java、C语言、JavaScript写四则运算,模拟简单的计算器
程序员文章站
2022-03-08 23:48:34
...
简单的计算器的实现
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>
上一篇: 使用ES6如何实现单例模式
下一篇: 漫画:最最最最最简单的选择排序