概述
样例:
```
package Demo5;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MyPanel extends JPanel implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
JTextArea text = new JTextArea();
String str[]={"7","8","9","+","4","5","6","-","1","2","3","*","0",".","=","/"};
JButton btn[] = new JButton[str.length];
public MyPanel() {
setLayout(new GridLayout(4,4,5,5));
init();
}
public void init() {
for(int i=0;i<str.length;i++){
btn[i]=new JButton(str[i]);
btn[i].addActionListener(this);
add(btn[i]);
}
}
public void actionPerformed(ActionEvent e) {
JButton b = (JButton)e.getSource();
if(b != btn[14]) {
text.append(b.getText());
}
else {
String str = text.getText();
if(str.indexOf("*")!=-1) {
if(str.indexOf(".")!=-1) {
String[] arr = str.split("\*");
double a0 = Double.parseDouble(arr[0]);
double b0 = Double.parseDouble(arr[1]);
text.setText(String.valueOf(a0*b0));
}
else {
String[] arr = str.split("\*");
int a1 = Integer.parseInt(arr[0]);
int b1 = Integer.parseInt(arr[1]);
text.setText(String.valueOf(a1*b1));
}
}
if(str.indexOf("/")!=-1) {
if(str.indexOf(".")!=-1) {
String[] arr = str.split("\/");
double a2 = Double.parseDouble(arr[0]);
double b2 = Double.parseDouble(arr[1]);
text.setText(String.valueOf(a2/b2));
}
else {
String[] arr = str.split("\/");
int a3 = Integer.parseInt(arr[0]);
int b3 = Integer.parseInt(arr[1]);
text.setText(String.valueOf(a3/b3));
}
}
if(str.indexOf("+")!=-1) {
if(str.indexOf(".")!=-1) {
String[] arr = str.split("\+");
double a4 = Double.parseDouble(arr[0]);
double b4 = Double.parseDouble(arr[1]);
System.out.print(a4+b4);
text.setText(String.valueOf(a4+b4));
}
else {
String[] arr = str.split("\+");
int a5 = Integer.parseInt(arr[0]);
int b5 = Integer.parseInt(arr[1]);
text.setText(String.valueOf(a5+b5));
}
}
if(str.indexOf("-")!=-1) {
if(str.indexOf(".")!=-1) {
String[] arr = str.split("-");
double a6 = Double.parseDouble(arr[0]);
double b6 = Double.parseDouble(arr[1]);
text.setText(String.valueOf(a6-b6));
}
else {
String[] arr = str.split("-");
int a7 = Integer.parseInt(arr[0]);
int b7 = Integer.parseInt(arr[1]);
text.setText(String.valueOf(a7-b7));
}
}
}
}
}
class MyFrame extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
MyPanel pane = new MyPanel();
JTextArea text = pane.text;
public MyFrame() {
add(text,"North");
add(pane,"Center");
setBounds(200,200,300,300);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
public class Demo3 {
public static void main(String[] args) {
MyFrame frame = new MyFrame();
}
}
最后
以上就是结实墨镜为你收集整理的JAVA实现简单计算器的全部内容,希望文章能够帮你解决JAVA实现简单计算器所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复