急求!!!如何用java程序代码实现计算器界面

用Java写的计算器的程序!不需要界面!~

用java写的计算器的程序,主要是通过控制台输入,主要方法是使用scanner类来接收用户从键盘输入的一个算式,通过分解算式,存入两个字符串,判断中间的的符号,进行相应计算,如下代码:System.out.println("-----------------------------------"); System.out.println("请输入一个算术表达式,如:45*23"); Scanner in = new Scanner(System.in);//接收用户从键盘输入的字符 String str = in.nextLine(); StringBuffer buffer = new StringBuffer();//保存左侧的数字 StringBuffer buffer1 = new StringBuffer();//保存右侧的数字 char t = ' ';//保存运算符 for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == '+' || str.charAt(i) == '-' || str.charAt(i) == '*' || str.charAt(i) == '/') { t = str.charAt(i);//识别是什么运算符 for (int j = i + 1; j < str.length(); j++) { buffer1.append(str.charAt(j)); } break; } else { buffer.append(str.charAt(i)); } } String c = buffer.toString(); String d = buffer1.toString(); double a = Double.parseDouble(c); double b = Double.parseDouble(d); double sum = 0; if (t == '+') { sum = a + b; } if (t == '-') { sum = a - b; } if (t == '*') { sum = a * b; } if (t == '/') { sum = a / b; } System.out.println("程序运算..."); System.out.println(c+t+d+"="+sum); System.out.print("-----------------------------------");运行结果如下:

java写的,可行

package ex1;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;

import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JTextField;

public class Calcutor extends JFrame {
private JTextField tf;
private JPanel panel1, panel2, panel3, panel4;
private JMenuBar myBar;
private JMenu menu1, menu2, menu3;
private JMenuItem editItem1, editItem2, help1, help2, help3;
private JRadioButtonMenuItem seeItem1, seeItem2;//单选框
private JCheckBoxMenuItem seeItem3;//复选框
private ButtonGroup bgb;
private String back;
private boolean IfResult = true, flag = false;
private String oper = "=";
private double result = 0;
private Num numActionListener;
private DecimalFormat df;

public Calcutor(){
super("科学计算器");//设置标题栏

df = new DecimalFormat("#.####");//保留四位小数

this.setLayout(new BorderLayout(10, 5));
panel1 = new JPanel(new GridLayout(1, 3, 10, 10));
panel2 = new JPanel(new GridLayout(5, 6, 5, 5));//5行6列
panel3 = new JPanel(new GridLayout(5, 1, 5, 5));
panel4 = new JPanel(new BorderLayout(5, 5));

/**
* 菜单栏
*/
myBar = new JMenuBar();
menu1 = new JMenu("编辑(E)");
menu2 = new JMenu("查看(V)");
menu3 = new JMenu("帮助(H)");

menu1.setFont(new Font("宋体", Font.PLAIN, 12));
menu2.setFont(new Font("宋体", Font.PLAIN, 12));
menu3.setFont(new Font("宋体", Font.PLAIN, 12));

/**
* 编辑栏
*/
editItem1 = new JMenuItem("复制(C) Ctrl+C");
editItem2 = new JMenuItem("粘贴(P) Ctrl+V");

editItem1.setFont(new Font("宋体",Font.PLAIN,12));
editItem2.setFont(new Font("宋体",Font.PLAIN,12));

/**
* 查看栏
*/
seeItem1 = new JRadioButtonMenuItem("科学型(T)");
seeItem2 = new JRadioButtonMenuItem("标准型(S)");
seeItem3 = new JCheckBoxMenuItem("数字分组(I)");

seeItem1.setFont(new Font("宋体",Font.PLAIN,12));
seeItem2.setFont(new Font("宋体",Font.PLAIN,12));
seeItem3.setFont(new Font("宋体",Font.PLAIN,12));

/**
* 帮助栏
*/
help1 = new JMenuItem("帮助主题(H)");
help2 = new JMenuItem("关于计算器(A)");

help1.setFont(new Font("宋体",Font.PLAIN,12));
help2.setFont(new Font("宋体",Font.PLAIN,12));

bgb = new ButtonGroup();//选项组

menu1.add(editItem1);
menu1.add(editItem2);

menu2.add(seeItem1);
menu2.add(seeItem2);
menu2.addSeparator();//添加一条分割线
menu2.add(seeItem3);

menu3.add(help1);
menu3.addSeparator();//添加一条分割线
menu3.add(help2);

myBar.add(menu1);
myBar.add(menu2);
myBar.add(menu3);

this.setJMenuBar(myBar);

numActionListener = new Num();//实现数字监听

/**
* 文本域,即为计算器的屏幕显示区域
*/
tf = new JTextField();
tf.setEditable(false);//文本区域不可编辑
tf.setBackground(Color.white);//文本区域的背景色
tf.setHorizontalAlignment(JTextField.RIGHT);//文字右对齐
tf.setText("0");
tf.setBorder(BorderFactory.createLoweredBevelBorder());
init();//对计算器进行初始化

}
/**
* 初始化操作
* 添加按钮
*/
private void init(){
addButton(panel1, "Backspace", new Clear(), Color.red);
addButton(panel1, "CE", new Clear(), Color.red);
addButton(panel1, "C", new Clear(), Color.red);

addButton(panel2, "1/x", new Signs(), Color.magenta);
addButton(panel2, "log", new Signs(), Color.magenta);
addButton(panel2, "7", numActionListener, Color.blue);
addButton(panel2, "8", numActionListener, Color.blue);
addButton(panel2, "9", numActionListener, Color.blue);
addButton(panel2, "÷", new Signs(), Color.red);

addButton(panel2, "n!", new Signs(), Color.magenta);
addButton(panel2, "sqrt", new Signs(), Color.magenta);
addButton(panel2, "4", numActionListener, Color.blue);
addButton(panel2, "5", numActionListener, Color.blue);
addButton(panel2, "6", numActionListener, Color.blue);
addButton(panel2, "×", new Signs(), Color.red);

addButton(panel2, "sin", new Signs(), Color.magenta);
addButton(panel2, "x^2", new Signs(), Color.magenta);
addButton(panel2, "1", numActionListener, Color.blue);
addButton(panel2, "2", numActionListener, Color.blue);
addButton(panel2, "3", numActionListener, Color.blue);
addButton(panel2, "-", new Signs(), Color.red);

addButton(panel2, "cos", new Signs(), Color.magenta);
addButton(panel2, "x^3", new Signs(), Color.magenta);
addButton(panel2, "0", numActionListener, Color.blue);
addButton(panel2, "-/+", new Clear(), Color.blue);
addButton(panel2, ".", new Dot(), Color.blue);
addButton(panel2, "+", new Signs(), Color.red);

addButton(panel2, "tan", new Signs(), Color.magenta);
addButton(panel2, "%", new Signs(), Color.magenta);
addButton(panel2, "π", numActionListener, Color.orange);
addButton(panel2, "e", numActionListener, Color.orange);
addButton(panel2, "′″", new Signs(), Color.orange);
addButton(panel2, "=", new Signs(), Color.red);

JButton btns = new JButton("计算器");
btns.setBorder(BorderFactory.createLoweredBevelBorder());
btns.setEnabled(false);//按钮不可操作
btns.setPreferredSize(new Dimension(20, 20));

panel3.add(btns);//加入按钮
addButton(panel3, "MC", null, Color.red);
addButton(panel3, "MR", null, Color.red);
addButton(panel3, "MS", null, Color.red);
addButton(panel3, "M+", null, Color.red);

panel4.add(panel1, BorderLayout.NORTH);
panel4.add(panel2, BorderLayout.CENTER);
this.add(tf, BorderLayout.NORTH);
this.add(panel3, BorderLayout.WEST);
this.add(panel4);

pack();
this.setResizable(false);//窗口不可改变大小
this.setLocation(300, 200);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
/**
* 统一设置按钮的的使用方式
* @param panel
* @param name
* @param action
* @param color
*/
private void addButton(JPanel panel, String name, ActionListener action, Color color){
JButton bt = new JButton(name);
panel.add(bt);//在面板上增加按钮
bt.setForeground(color);//设置前景(字体)颜色
bt.addActionListener(action);//增加监听事件
}
/**
* 计算器的基础操作(+ - × ÷)
* @param x
*/
private void getResult (double x){
if(oper == "+"){result += x;}
else if(oper == "-"){result -= x;}
else if(oper == "×"){result *= x;}
else if(oper == "÷"){result /= x;}
else if(oper == "="){result = x;}
tf.setText(df.format(result));
}
/**
* 运算符号的事件监听
*/
class Signs implements ActionListener{
public void actionPerformed(ActionEvent e) {
/*
* 用ActionEvent对象的getActionCommand()方法
* 取得与引发事件对象相关的字符串
*/
String str = e.getActionCommand();

/* sqrt求平方根 */
if(str.equals("sqrt")){
double i = Double.parseDouble(tf.getText());
if(i>=0){
/*
* String.valueOf() 转换为字符串
* df.format() 按要求保留四位小数
* Math.sqrt() 求算数平方根
*/
tf.setText(String.valueOf(df.format(Math.sqrt(i))));
}
else{
tf.setText("负数不能开平方根");
}
}

/* log求常用对数 */
else if(str.equals("log")){
double i = Double.parseDouble(tf.getText());
if(i>0){
tf.setText(String.valueOf(df.format(Math.log(i))));
}else{
tf.setText("负数不能求对数");
}
}

/* %求百分比 */
else if(str.equals("%")){
tf.setText(df.format(Double.parseDouble(tf.getText()) / 100));
}

/* 1/x求倒数 */
else if(str.equals("1/x")){
if(Double.parseDouble(tf.getText()) == 0){
tf.setText("除数不能为零");
}else{
tf.setText(df.format(1 / Double.parseDouble(tf.getText())));
}
}

/* sin求正弦函数 */
else if(str.equals("sin")){
double i = Double.parseDouble(tf.getText());
tf.setText(String.valueOf(df.format(Math.sin(i))));
}

/* cos求余弦函数 */
else if(str.equals("cos")){
double i = Double.parseDouble(tf.getText());
tf.setText(String.valueOf(df.format(Math.cos(i))));
}

/* tan求正切函数 */
else if(str.equals("tan")){
double i = Double.parseDouble(tf.getText());
tf.setText(String.valueOf(df.format(Math.tan(i))));
}

/* n!求阶乘 */
else if(str.equals("n!")){
double i = Double.parseDouble(tf.getText());
if((i%2==0)||(i%2==1))//判断为整数放进行阶乘操作
{
int j = (int)i;//强制类型转换
int result=1;
for(int k=1;k<=j;k++)
result *= k;
tf.setText(String.valueOf(result));
}
else
{
tf.setText("无法进行阶乘");
}
}

/* x^2求平方 */
else if(str.equals("x^2")){
double i = Double.parseDouble(tf.getText());
tf.setText(String.valueOf(df.format(i*i)));
}

/* x^3求立方 */
else if(str.equals("x^3")){
double i = Double.parseDouble(tf.getText());
tf.setText(String.valueOf(df.format(i*i*i)));
}

/* ′″角度转换 */
/**
* 将角度值转换成弧度值,方便三角函数的计算
*/
else if(str.equals("′″")){
double i = Double.parseDouble(tf.getText());
tf.setText(String.valueOf(i/180*Math.PI));
}

else{
if(flag){
IfResult = false;
}
if(IfResult){
oper = str;
}else{
getResult(Double.parseDouble(tf.getText()));
oper = str;
IfResult = true;
}
}
}
}
/**
* 清除按钮的事件监听
*/
class Clear implements ActionListener{
public void actionPerformed(ActionEvent e) {
/*
* 用ActionEvent对象的getActionCommand()方法
* 取得与引发事件对象相关的字符串
*/
String str = e.getActionCommand();
if(str == "C"){
tf.setText("0");
IfResult = true;
result = 0;
}else if(str == "-/+"){
double i = 0 - Double.parseDouble(tf.getText().trim());
tf.setText(df.format(i));
}else if(str == "Backspace"){
if(Double.parseDouble(tf.getText()) > 0){
if(tf.getText().length() > 1){
tf.setText(tf.getText().substring(0, tf.getText().length() - 1));
//使用退格删除最后一位字符
}else{
tf.setText("0");
IfResult = true;
}
}else{
if(tf.getText().length() > 2){
tf.setText(tf.getText().substring(0, tf.getText().length() - 1));
}else{
tf.setText("0");
IfResult = true;
}
}
}else if(str == "CE"){
tf.setText("0");
IfResult = true;
}
}
}
/**
* 数字输入的事件监听
*/
class Num implements ActionListener{
public void actionPerformed(ActionEvent e) {
String str = e.getActionCommand();
if(IfResult){
tf.setText("");
IfResult = false;
}
if(str=="π")
{
tf.setText(String.valueOf(Math.PI));
}
else if(str=="e")
{
tf.setText(String.valueOf(Math.E));
}
else{
tf.setText(tf.getText().trim() + str);
if(tf.getText().equals("0")){
tf.setText("0");
IfResult = true;
flag = true;
}
}
}
}
/**
* 小数点的事件监听
*/
class Dot implements ActionListener{
public void actionPerformed(ActionEvent e) {
IfResult = false;
if(tf.getText().trim().indexOf(".") == -1){
tf.setText(tf.getText() + ".");
}
}
}
/**
* main方法
*/
public static void main(String[] args) {
new Calcutor().setVisible(true);
}
}

package jisuanqi_new;

import java.awt.*;

import java.awt.event.*;

public class JiSuanQi_new implements ActionListener

{

 Panel p1;//声明面板p1

 TextField t1;//声明文本行t1

 String[] label = {"7","8","9","/","4","5","6","*","1","2","3","-","0",".","=","+"};//声明标签数组label1存放按钮上的标签

 Button[] b;//声明按钮数组存放16个按钮

 private int i;//声明i以备后用

 private String op1 = "0";//运算数备用

 private String operator = "+";//运算符备用

 private boolean append = false;//备用

public JiSuanQi_new()//构造方法

{

 t1=new TextField();//初始化文本行t1

 b = new Button[label.length];//初始化按钮数组b

    p1=new Panel();//初始化面板p1

 p1.setLayout(new GridLayout(4,4,4,4));//使面板选择网格布局管理器以备储存16个按钮(4行4列)

 for(int i=0;i<b.length;i++)//利用for循环把标签放在按钮上,使每个按钮添加事件监听器,在面板p1上添加上16个按钮

 {

        b[i] = new Button(label[i]);//把标签依次放在16个按钮上

        b[i].addActionListener(this);//使每个按钮添加动作事件监听器

     p1.add(b[i]); //分别将按钮添加到面板p1上

    } 

 Frame f=new Frame("计算器1.0");//初始化窗口f,起名字计算器1.0

 f.setLayout(new BorderLayout());//为窗口选择边界布局管理器

 f.add(BorderLayout.NORTH,t1);//把文本行他添加到窗口的北部

 f.add(BorderLayout.CENTER,p1);//把面吧p1添加到窗口的中间

 f.addWindowListener(new WindowAdapter(){//给窗口f添加窗口事件监听器

  public void windowClosing(WindowEvent eve){//运行窗口关闭方法

   System.exit(0);//退出程序

  }

 });

 f.setSize(250, 250);//设置窗口大小

 f.setLocation(200,200);

 f.setVisible(true);//显示窗口

}

public static void main(String args[])

{

 new JiSuanQi_new(); //调用构造方法

}

public void actionPerformed(ActionEvent ae) 

{//按钮被操作发生

    String comm = ae.getActionCommand();//返回与此动作相关的命令字符串,即:使用者第一次点击的按钮是什么。

    if("0123456789".indexOf(comm)!=-1)//如果相关命令字符串为0~9之间的数字则执行

    {

        if(append){

            String temp = t1.getText();//新数字

            t1.setText(temp+comm);

        }else{                         //因为此时append为false执行这个

            t1.setText(comm); //将文本行t1设置为相关命令字符串(你按中的按钮代码)

            append =  true;//此时append=true若继续按按钮若继续按数字的话1.第一次的按话不会改变2.非第一次按得话会覆盖之前按得数字(即缺点:只能进行单个数字的计算)

        }

    }

    else if(("+-*/".indexOf(comm)!=-1))//如果相关命令字符串为+-*/之间的数字则执行

    {

        //保存

     //t1.setText(comm);

        op1 = t1.getText();//把第一个数赋值给op1 

        operator = comm;//把命令字符串赋值给operator

        append = false;//此时append为false即若继续按按钮若按数字的话将重复上面的动作,按符号的话将覆盖之前的符号

    }

    else if("=".equals(comm))//如果按的是=号,则按条件进行下面的运算

    {

        String op2 = t1.getText();//op2第二个数

        double d1 = Double.parseDouble(op1);

        double d2 = Double.parseDouble(op2);

        if(operator.equals("+")){

            d1 = d1 + d2 ;

        }else if(operator.equals("-")){

            d1 = d1 - d2;

        }else if(operator.equals("*")){

            d1 = d1 * d2;

        }else {

            d1 = d1 / d2;

        }

        t1.setText(d1+"");//显示计算结果

        append = false;

    }

    else if(".".equals(comm))//若是.号继续按

    {

        String temp = t1.getText();

        if(temp.indexOf(".")==-1){

            t1.setText(temp+".");

            append = true;

        }

    }

}

}



public class GUI extends JFrame {
private JButton caculate=null;
private JLabel no1=null;
private JLabel no2=null;
private JTextField t1=null;
private JTextField t2=null;
private JTextField result=null;

public GUI(){
this.setLocation(500,500);
this.setSize(420, 420);
this.setTitle("窗口程序管理");
this.setVisible(true);

//this.setLayout(new FlowLayout());
this.setLayout(null);//去掉布局管理器

no1=new JLabel("第一个数");
no2=new JLabel("第二个数");
caculate=new JButton("相加等于");
t1=new JTextField();
t2 = new JTextField();
result = new JTextField();

no1.setBounds(30,20,80,20);
no2.setBounds(30,50,80,20);
caculate.setBounds(10,100,90,20);
t1.setBounds(150,20,60,20);
t2.setBounds(150,50,60,20);
result.setBounds(150,100,60,20);

caculate.addActionListener(
new ActionListener(){

public void actionPerformed( ActionEvent e) {

String str1=t1.getText();
String str2=t2.getText();
int num1=Integer.parseInt(str1);
int num2=Integer.parseInt(str2);
int num3=num1+num2;
result.setText(num3+"");

}
}
);

this.add(no1);
this.add(no2);
this.add(caculate);
this.add(t1);
this.add(t2);
this.add(result);

}
public static void main(String[] args) {
new GUI();
}
}
这只是一个小小的例子,至于其他的按钮,其他的些事件,你自己可以加进去的。还有就是键的方位什么的自己也可以设置啊。。。。我想你自己懂这个。。。

你实在不怎么会java界面代码编写的话可以尝试用Jbuilder这个开发工具。这个工具在这java图形设计上是有优势的

如何用javac 和java 编译运行整个Java工程
答:前言 本文教你怎么用javac和java命令 以及如何利用脚本(shell或bat)方便处理 并用简单的实例展示这些用法 IDE是把双刃剑 它可以什么都帮你做了 你只要敲几行代码 点几下鼠标 程序就跑起来了 用起来相当方便 你不用去关心它后面做了些什么 执行了哪些命令 基于什么原理 然而也是这种过分的依赖往往让...

如何用“JavaN-IDE”软件在手机上编写java程序?
答:我们老师在刚教我们学java时,用的就是EditPlus,因为不会提示你错误的信息,只能靠自己去找,这样会锻炼同学们对代码的敏感度。下面,就让来教大家怎么使用EditPlus编写java程序吧。1、打开EditPlus。2、点击新建--java。3、会出现java程序的基本框架,于是就可以在里面编写java了。4、在class后面写上...

急救!!怎样在vrml中调用一个Java程序
答:急救!!怎样在vrml中调用一个Java程序 我用vrml做了个虚拟教室,有用Java做了个聊天室程序,哪位达人教我怎样在虚拟教室里做一个按钮,鼠标点击就可以调出聊天程序的客户端,感激涕零... 我用vrml做了个虚拟教室,有用Java做了个聊天室程序,哪位达人教我怎样在虚拟教室里做一个按钮,鼠标点击就可以调出聊天程序的...

如何用Eclipse建立一个Java应用程序
答:‍至于java的jdk环境,这里就不再说了,可以自己百度(关键字:jdk环境安装)。‍解压缩下载的压缩文件,解压缩方法不再讲解,自己百度。解压后目录大概是这样的:‍2.双击打开,如遇到问题,不能正常打开,请检查jdk是否安装,是否与eclipse使用位数一致!进入后有个欢迎界面,关掉初始的...

如何用Eclipse建立一个Java应用程序?
答:4、我们可以看到新建的java项目,点击项目下的src包。5、右键SEC,选择箭头所指的new和CLASS,进入到新建页面。6、在箭头所指的name输入框中输入class名称,勾选箭头所指的框,点击箭头所指的finish。7、我们可以看到java文件创建好了。(1)开启Eclipse程序后,首先开始Eclipse中JAVA项目的新建,在上方的...

数据库如何用java写超市购物程序?
答:创建数据库连接 执行增删改查(CRUD)操作 提交或回滚事务 执行存储过程和函数 查询数据库元数据 此外,您还可以使用Java的面向对象编程技术来封装数据库操作,以便更方便地在您的程序中使用。例如,您可以创建一个类来表示超市商品,并定义一些方法来执行商品的增删改查操作。这样,您就可以在程序中通过...

如何编译运行一个简单的java程序
答:通常开发一个java应用程序可分为三个步骤:1.创建一个带有文件扩展名 *.java 的源文件 1).使用编辑器(如记事本,小编使用的是notepad++),输入以下6行文本:1 //一个简单的application例子:打印一行文本 2 class Hello { 3 public static void main (String args[]){ 4 System.out.println(...

如何在Java中执行其它程序
答:在编写Java程序时,有时候需要在Java程序中执行另外一个程序。 1、启动程序Java提供了两种方法用来启动其它程序: (1)使用Runtime的exec()方法 (2)使用ProcessBuilder的start()方法 不管在哪种操作系统下,程序具有基本类似的一些属性。一个程序启动后就程序操作系统的一个进程,进程在执行的时候有自己的环境变量、有自己...

怎样用java编写图形界面的Application程序
答:java编写图形界面需要用到swing等组件,可以在eclipse中安装windowbuilder来开发窗体,自动生成窗体代码,然后自己再根据需要修改,如:package mainFrame;import java.awt.EventQueue;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import javax.swing.ImageIcon;import javax.swing.JButton...

IT评价网,数码产品家用电器电子设备等点评来自于网友使用感受交流,不对其内容作任何保证

联系反馈
Copyright© IT评价网