用JAVA编写一个简单的计算器,要求如下:然后 通过输入 显示结果,比如说:
以下是上图计算器的代码:
package Computer;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Stack;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Count extends JApplet implements ActionListener
{
/**
*
*/
private static final long serialVersionUID = 1L;
private JTextField textField = new JTextField("请输入");
String operator = "";//操作
String input = "";//输入的 式子
boolean flag =true;
//boolean flag1 = true;
//boolean flag2 = true;
public void init()//覆写Applet里边的init方法
{
Container C = getContentPane();
JButton b[] = new JButton[16];
JPanel panel = new JPanel();
C.add(textField, BorderLayout.NORTH);
C.add(panel,BorderLayout.CENTER);
panel.setLayout(new GridLayout(4, 4,5,5));
String name[]={"7","8","9"," ","4","5","6","-","1","2","3","*","0","C","=","/"};//设置 按钮
for(int i=0;i16;i)//添加按钮
{
b[i] = new JButton(name[i]);
b[i].setBackground(new Color(192,192,192));
b[i].setForeground(Color.BLUE);//数字键 设置为 蓝颜色
if(i%4==3)
b[i].setForeground(Color.RED);
b[i].setFont(new Font("宋体",Font.PLAIN,16));//设置字体格式
panel.add(b[i]);
b[i].addActionListener(this);
}
b[13].setForeground(Color.RED);//非数字键,即运算键设置为红颜色
b[13].setForeground(Color.RED);
}
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("="))//当监听到等号时 , 则处理 input
{
input = "=" compute(input);
textField.setText(input);
input="";
cnt = 1;
}
else
input= actionCommand;//数字为了避免多位数的输入 不需要加空格
if(cnt==0)
textField.setText(input);
}
private String compute(String input)//即1237 的 样例
{
String str[];
str = input.split(" ");
StackDouble s = new StackDouble();
double m = Double.parseDouble(str[0]);
s.push(m);
for(int i=1;istr.length;i)
{
if(i%2==1)
{
if(str[i].compareTo(" ")==0)
{
double help = Double.parseDouble(str[i 1]);
s.push(help);
}
if(str[i].compareTo("-")==0)
{
double help = Double.parseDouble(str[i 1]);
s.push(-help);
}
if(str[i].compareTo("*")==0)
{
double help = Double.parseDouble(str[i 1]);
double ans = s.peek();//取出栈顶元素
s.pop();//消栈
ans*=help;
s.push(ans);
}
if(str[i].compareTo("/")==0)
{
double help = Double.parseDouble(str[i 1]);
double ans = s.peek();
【java计算器代码简单 java计算器代码简单易懂】s.pop();
ans/=help;
s.push(ans);
}
}
}
double ans = 0d;
while(!s.isEmpty())
{
ans =s.peek();
s.pop();
}
String result = String.valueOf(ans);
return result;
}
public static void main(String args[])
{
JFrame frame = new JFrame("Count");
Count applet = new Count();
frame.getContentPane().add(applet, BorderLayout.CENTER);
applet.init();//applet的init方法
applet.start();//线程开始
frame.setSize(350, 400);//设置窗口大小
frame.setVisible(true);//设置窗口可见
}
}
编写java程序简单计算器主要涉及的知识点: 类的写法, 以及方法的调用 .建议多做练习. 如果有看不懂的地方. 可以继续追问,一起讨论.
参考代码如下
//Number类
class Number {
private int n1;//私有的整型数据成员n1
private int n2;//私有的整型数据成员n2
// 通过构造函数给n1和n2赋值
public Number(int n1, int n2) {
this.n1 = n1;
this.n2 = n2;
}
// 加法
public int addition() {
return n1n2;
}
// 减法
public int subtration() {
return n1 - n2;
}
// 乘法
public int multiplication() {
return n1 * n2;
}
// 除法 (可能除不尽,所以使用double作为返回类型)
public double division() {
return n1 * 1.0 / n2; // 通过n1*1.0 把计算结果转换成double类型.
}
}
//Exam4 类
public class Exam4{
public static void main(String[] args) {
Number number=new Number(15, 6);//创建Number类的对象
//下面的是调用方法得到返回值进行输出显示
System.out.println("加法" number.addition());
System.out.println("减法" number.subtration());
System.out.println("乘法" number.multiplication());
System.out.println("除法" number.division());
}
}
求大神发个完整简单的java计算器代码,public static void main(String[] args) {
System.out.println("简单计算器");
boolean flag=true;//while循环是否继续 , true继续循环,false停止循环
System.out.println("请输入第一个数字");
while(flag){
Scanner scan = new Scanner(System.in);
String bh=scan.next();
try {
double num = Double.parseDouble(bh);
System.out.println("请输入符号( 、-、*、/)");
while(1==1){
String fh=scan.next();
if(" ".equals(fh) || "-".equals(fh) || "*".equals(fh) || "/".equals(fh)){
System.out.println("请输入第二个数字");
while(1==1){
String bh2=scan.next();
try {
double num2 = Double.parseDouble(bh2);
double num3=0;
if(" ".equals(fh)){
num3=num num2;
}else if("-".equals(fh)){
num3=num-num2;
}else if("*".equals(fh)){
num3=num*num2;
}else if("/".equals(fh)){
num3=num/num2;
}
System.out.println(num3);
break;
} catch (Exception e) {
System.out.println("请输入第二个正确的数字");
continue;
}
}
break;
}else{
System.out.println("请输入正确的符号( 、-、*、/)");
continue;
}
}
System.out.println("是否继续运算:输入Y或者y继续,输入其它任意字符退出");
String yn=scan.next();
if("Y".equals(yn) || "y".equals(yn)){
continue;
}else{
System.out.println("运算结束");
break;
}
}catch (NumberFormatException e) {//输入非数字类型时
System.out.println("请输入第一个正确的数字");
continue;
}
}
}
JAVA简单咋做,计算器代码简单写了下,代码如下请参照:
/**
* 计算器类
*
* @author Administrator
*
*/
public class Calculator extends JFrame implements ActionListener {
private static final long serialVersionUID = 3868243398506940702L;
// 文本框
private JTextField result;
// 按钮数组
private JButton[] buttons;
// 按钮文本
private final String[] characters = { "7", "8", "9", "/", "4", "5", "6",
"*", "1", "2", "3", "-", "0", ".", "=", " " };
// 是否为第一个输入的数字
private boolean isFirstDigit = true;
// 运算结果
private double resultNum = 0.0;
// 运算符
private String operator = "=";
public Calculator(String title) {
// 设置标题栏
super(title);
// 初始化各组件
init();
// 注册各组件监听器
registerListener();
// 显示窗体
setVisible(true);
}
/**
* 初始化各组件
*/
private void init() {
// 常用属性初始化
setSize(220, 200);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
/* 文本框对象初始化 */
result = new JTextField("0");
// 文本右对齐
result.setHorizontalAlignment(JTextField.RIGHT);
// 设置是否可编辑
result.setEditable(false);
/* 按钮初始化 */
buttons = new JButton[characters.length];
for (int i = 0; ibuttons.length; i) {
buttons[i] = new JButton(characters[i]);
buttons[i].setFocusable(false); // 不允许按钮定位焦点
}
/* 将文本框与按钮添加到窗体中 */
add(result, BorderLayout.NORTH);
JPanel pnl = new JPanel(new GridLayout(4, 4, 5, 5));
for (JButton jButton : buttons) {
pnl.add(jButton);
}
add(pnl);
this.getContentPane().setFocusable(true);
}
/**
* 注册监听器
*/
private void registerListener() {
for (JButton jButton : buttons) {
jButton.addActionListener(this);
}
// 注册键盘事件
this.getContentPane().addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
String text = String.valueOf(e.getKeyChar());
if (Character.isDigit(text.charAt(0)) || ".".equals(text)) { // 数字或小数点
handleNumber(text);
} else if (" -*/=".indexOf(text) != -1) { // 运算符
handleOperator(text);
} else if (e.getKeyCode() == 8) { // 退格键
String tmp = result.getText().trim();
if (tmp.length() == 1) {
result.setText("0");
isFirstDigit = true;
} else {
result.setText(tmp.substring(0, tmp.length() - 1));
}
}
}
});
}
@Override
public void actionPerformed(ActionEvent e) {
JButton btn = (JButton) e.getSource();
String text = btn.getText().trim();
if (Character.isDigit(text.charAt(0)) || ".".equals(text)) { // 处理数字和小数点
handleNumber(text);
} else { // 处理运算符
handleOperator(text);
}
}
/**
* 处理数字和小数点
*
* @param text
*/
private void handleNumber(String text) {
if (isFirstDigit) { // 第一次输入
if (".".equals(text)) {
this.result.setText("0.");
} else {
this.result.setText(text);
}
} else if ("0".equals(text)"0".equals(this.result.getText())) {
isFirstDigit = true;
return;
} else if (".".equals(text)this.result.getText().indexOf(".") == -1) {
this.result.setText(this.result.getText()".");
} else if (!".".equals(text)) {
this.result.setText(this.result.getText()text);
}
isFirstDigit = false;
}
/**
* 处理运算符
*
* @param text
*/
private void handleOperator(String text) {
switch (operator) { // 处理各项运算适用于JDK1.7版本的
case " ":
resultNum= Double.parseDouble(this.result.getText());
break;
case "-":
resultNum -= Double.parseDouble(this.result.getText());
break;
case "*":
resultNum *= Double.parseDouble(this.result.getText());
break;
case "/":
resultNum /= Double.parseDouble(this.result.getText());
break;
case "=":
resultNum = Double.parseDouble(this.result.getText());
break;
}
// 将文本框的值修改为运算结果
this.result.setText(String.valueOf(resultNum));
// 将点击的运算符放入operator保存
operator = text;
// 下一个数字第一次点击
isFirstDigit = true;
}
public static void main(String[] args) {
new Calculator("My Calculator");
}
}
运行结果如下:
用Java设计一个简单的计算器 。无聊写java计算器代码简单了个java计算器代码简单 , 修复java计算器代码简单了下Bugjava计算器代码简单:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class Calculate extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JButton plus, reduce, multiply, divice, reset;
private JTextField one, two, result;
private boolean device_falg = false;
private final int width = 400, height = 300;
public Calculate() {
super("修改密码");
this.setLayout(null);
this.setSize(width, height);
init();
Layout();
}
public void init() {
plus = new JButton("加");
reduce = new JButton("减");
multiply = new JButton("乘");
divice = new JButton("除");
reset = new JButton("清空");
one = new JTextField();
two = new JTextField();
result = new JTextField();
}
public void Layout() {
this.add(new JLabel("第一个数")).setBounds(20, 10, 60, 80);
this.add(one).setBounds(100, 38, 100, 25);
this.add(new JLabel("第二个数")).setBounds(20, 40, 60, 80);
this.add(two).setBounds(100, 70, 100, 25);
this.add(new JLabel("结果")).setBounds(20, 85, 60, 80);
this.add(result).setBounds(100, 110, 100, 25);
this.add(plus).setBounds(70, 170, 80, 25);
this.add(reduce).setBounds(200, 170, 80, 25);
this.add(multiply).setBounds(70, 200, 80, 25);
this.add(divice).setBounds(200, 200, 80, 25);
this.add(reset).setBounds(300, 220, 80, 25);
plus.addActionListener(this);
reduce.addActionListener(this);
multiply.addActionListener(this);
divice.addActionListener(this);
reset.addActionListener(this);
this.setVisible(true);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
public boolean Format() {
boolean FLAG = false;
boolean flag = false;
String one = this.one.getText().toString().trim();
String two = this.two.getText().toString().trim();
if (one == null || one.equals("") || two == null || two.equals("")) {
JOptionPane.showMessageDialog(getParent(), "请输入完整信息!");
FLAG = false;
flag = true;
}
boolean boll_1 = one.matches("[\\d]{1,100}");
boolean boll_2 = two.matches("[\\d]{1,100}");
boolean boll_3 = one.matches("[\\d]{1,100} [.] [\\d]{1,100}");
boolean boll_4 = two.matches("[\\d]{1,100} [.] [\\d]{1,100}");
if (flag) {
return false;
}
if ((boll_1boll_2) || (boll_3boll_4) || (boll_1boll_4)
|| (boll_3boll_2)) {
FLAG = true;
} else {
JOptionPane.showMessageDialog(getParent(), "请输入数字!");
FLAG = false;
}
if (FLAGdevice_falg) {
if (Double.parseDouble(two) == 0) {
JOptionPane.showMessageDialog(getParent(), "被除数不能为0!");
FLAG = false;
device_falg=false;
}
}
return FLAG;
}
public double Plus(double one, double two) {
return onetwo;
}
public double Multiply(double one, double two) {
return one * two;
}
public double Divice(double one, double two) {
return one / two;
}
public double Reduce(double one, double two) {
return one - two;
}
public void Clear() {
one.setText("");
two.setText("");
result.setText("");
}
@Override
public void actionPerformed(ActionEvent e) {
Object o = e.getSource();
if (o == reset) {
Clear();
return;
}
if (o == divice) {
device_falg = true;
}
if (!Format()) {
return;
}
double one = Double.parseDouble(this.one.getText());
double two = Double.parseDouble(this.two.getText());
double result = 0;
if (o == plus) {
result = Plus(one, two);
} else if (o == reduce) {
result = Reduce(one, two);
} else if (o == multiply) {
result = Multiply(one, two);
} else if (o == divice) {
result = Divice(one, two);
}
this.result.setText(""result);
}
public static void main(String[] args) {
new Calculate();
}
}
java计算器代码简单的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于java计算器代码简单易懂、java计算器代码简单的信息别忘了在本站进行查找喔 。
推荐阅读
- 穿越火线的单机版游戏,穿越火线单机版游戏介绍
- 卖东西怎么开公众号,卖东西的微信公众号
- oracle表改名特别慢,oracle修改表名sql
- 虚拟键盘与主机连接,虚拟键盘与主机连接不上
- mysql是怎么解决脏读 mysql怎么解决脏读幻读不可重复读
- 软件小程序开发的图片,程序开发软件属于什么软件
- 十月会出什么手机cpu,十月份有什么手机发布
- 华为p10使用鸿蒙系统怎么样,鸿蒙系统 华为p10
- 系统城windows原版的简单介绍