大橙子网站建设,新征程启航
为企业提供网站建设、域名注册、服务器等服务
用Java编写的实现加减乘除的程序如下
创新互联为企业级客户提高一站式互联网+设计服务,主要包括成都网站制作、做网站、App定制开发、重庆小程序开发公司、宣传片制作、LOGO设计等,帮助客户快速提升营销能力和企业形象,创新互联各部门都有经验丰富的经验,可以确保每一个作品的质量和创作周期,同时每年都有很多新员工加入,为我们带来大量新的创意。
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Calculator extends JFrame implements ActionListener{
JLabel jl1=new JLabel("第一个数");
JLabel jl2=new JLabel("运算符");
JLabel jl3=new JLabel("第二个数");
JLabel jl4=new JLabel("结果:");
JTextField jtf1=new JTextField(8);
JTextField jtf2=new JTextField(8);
JTextField jtf3=new JTextField(8);
String a[]={"+","-","*","/"};
JComboBoxString jcb=new JComboBoxString(a);
JButton jb1=new JButton("计算");
JButton jb2=new JButton("退出");
JPanel jp=new JPanel();
Calculator(){
setTitle("计算器");
jb1.addActionListener(this);
jb2.addActionListener(this);
jp.setLayout(null);
jl1.setBounds(30, 30, 80, 20);
jl2.setBounds(110, 30, 80, 20);
jl3.setBounds(190, 30, 80, 20);
jtf1.setBounds(30, 60, 70, 20);
jcb.setBounds(110, 60, 70,20);
jtf2.setBounds(190, 60, 70, 20);
jl4.setBounds(80, 110, 40, 20);
jtf3.setBounds(110, 110, 100, 20);
jb1.setBounds(60, 160, 60, 25);
jb2.setBounds(170, 160, 60, 25);
jp.add(jl1);jp.add(jl2);jp.add(jl3);
jp.add(jtf1);jp.add(jcb);jp.add(jtf2);
jp.add(jl4);jp.add(jtf3);
jp.add(jb1);jp.add(jb2);
add(jp,BorderLayout.CENTER);
setSize(300, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new Calculator();
}
@Override
public void actionPerformed(ActionEvent ae) {
if(ae.getSource()==jb1){
String c=((String) jcb.getSelectedItem()).trim();
if(jtf1.getText().trim().equals("")){
JOptionPane.showMessageDialog(this, "第一个数不能为空");
jtf1.requestFocus();
return;
}
if(jtf2.getText().trim().equals("")){
JOptionPane.showMessageDialog(this, "第二个数不能为空");
jtf2.requestFocus();
return;
}
double num1=Double.parseDouble(jtf1.getText().trim());
double num2=Double.parseDouble(jtf2.getText().trim());
double num3 = 0;
switch(c){
case "+":num3=num1+num2;break;
case "-":num3=num1-num2;break;
case "*":num3=num1*num2;break;
case "/":
if(num2==0){
JOptionPane.showMessageDialog(this, "除数不能为0");
jtf2.requestFocus();
return;
}else{
num3=num1/num2;
break;
}
}
jtf3.setText(String.valueOf(num3));
}
if(ae.getSource()==jb2){
System.exit(0);
}
}
}
运行结果
下面文件名要为:JiSuanQi.java
import java.awt.*;
import java.awt.event.*;
public class JiSuanQi
{
String s="",s1=null,s2=null;
Frame f=new Frame("计算器");
TextField tf=new TextField(30);
Panel p1=new Panel();
Panel p2=new Panel();
Panel p3=new Panel();
Button bt1=new Button("=");
Button bt2=new Button("删除");
Button[] bt=new Button[16];
int id=0;
public static void main(String[] args)
{
new JiSuanQi().init();
}
public void init()
{
f.setBackground(new Color(85,247,253));
f.setLayout(new BorderLayout(4,4));
p2.setLayout(new GridLayout(4,4,4,4));
p3.setLayout(new BorderLayout(4,4));
f.setResizable(false);
f.add(p1,BorderLayout.NORTH);
f.add(p2);
p3.add(bt2,BorderLayout.NORTH);
p3.add(bt1);
p1.add(tf);
f.add(p3,BorderLayout.EAST);
String[] b={"1","2","3","+","4","5","6","-","7","8","9","*","0",".","复位","/"};
for(int i=0;i16;i++)
{
bt[i]=new Button(b[i]);
p2.add(bt[i]);
}
bt[0].setForeground(Color.blue);
bt[1].setForeground(Color.blue);
bt[2].setForeground(Color.blue);
bt[4].setForeground(Color.blue);
bt[5].setForeground(Color.blue);
bt[6].setForeground(Color.blue);
bt[8].setForeground(Color.blue);
bt[9].setForeground(Color.blue);
bt[10].setForeground(Color.blue);
bt[12].setForeground(Color.blue);
bt[13].setForeground(Color.blue);
bt[3].setForeground(Color.red);
bt[7].setForeground(Color.red);
bt[11].setForeground(Color.red);
bt[15].setForeground(Color.red);
bt[14].setForeground(Color.red);
bt1.setForeground(Color.red);
bt2.setForeground(Color.red);
f.pack();
f.setVisible(true);
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
);
bt[0].addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
s+=1;
s2+=1;
tf.setText(s);
}
}
);
bt[1].addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
s+=2;
s2+=2;
tf.setText(s);
}
}
);
bt[2].addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
s+=3;
s2+=3;
tf.setText(s);
}
}
);
bt[4].addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
s+=4;
s2+=4;
tf.setText(s);
}
}
);
bt[5].addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
s+=5;
s2+=5;
tf.setText(s);
}
}
);
bt[6].addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
s+=6;
s2+=6;
tf.setText(s);
}
}
);
bt[8].addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
s+=7;
s2+=7;
tf.setText(s);
}
}
);
bt[9].addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
s+=8;
s2+=8;
tf.setText(s);
}
}
);
bt[10].addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
s+=9;
s2+=9;
tf.setText(s);
}
}
);
bt[12].addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
s+=0;
s2+=0;
tf.setText(s);
}
}
);
bt[13].addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
s+='.';
s2+='.';
tf.setText(s);
}
}
);
bt[3].addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
s1=s;
s+='+';
id=1;
s2="";
tf.setText(s);
}
}
);
bt[7].addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
s1=s;
s+='-';
id=2;
s2="";
tf.setText(s);
}
}
);
bt[11].addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
s1=s;
s+='*';
id=3;
s2="";
tf.setText(s);
}
}
);
bt[14].addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
s="";
s2="";
tf.setText(s);
}
}
);
bt[15].addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
s1=s;
s+='/';
id=4;
s2="";
tf.setText(s);
}
}
);
bt1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(id1) ;
else{
s+='=';
double a=Double.parseDouble(s1);
double b=Double.parseDouble(s2);
double c=0;
switch(id)
{
case 1:c=a+b; break;
case 2:c=a-b; break;
case 3:c=a*b; break;
case 4:c=a/b; break;
}
s+=c;
tf.setText(s);
}
s="";s1="";s2="";id=0;
}
}
);
bt2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
char[] c1;
char[] c2=new char[s.length()-1];
c1=s.toCharArray();
for(int i=0;is.length()-1;i++)
c2[i]=c1[i];
s=s.valueOf(c2);
if(id1)
{
s1=s;
}
if(s2.length()=1)
{
char[] c3;
char[] c4=new char[s2.length()-1];
c3=s2.toCharArray();
for(int i=0;is2.length()-1;i++)
c4[i]=c3[i];
s2=s2.valueOf(c4);
}
tf.setText(s);
}
}
);
}
}
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
System.out.println("请输入第一个数:");
double n1 = sc.nextDouble();
System.out.println("请输入运算符:");
String s = sc.next();
System.out.println("请输入第二个数:");
double n2 = sc.nextDouble();
if(s.equals("+")){
System.out.print(n1+"+"+n2+" = "+(n1+n2));
}else if(s.equals("-")){
System.out.print(n1+"+"+n2+" = "+(n1-n2));
}else if(s.equals("*")){
System.out.print(n1+"*"+n2+" = "+(n1*n2));
}else if(s.equals("/")){
if(n2==0){
System.out.println("除数不能等于0");
}else{
System.out.print(n1+"/"+n2+" = "+(n1/n2));
}
}else{
System.out.println("运算符输入错误,请重新输入。");
}
}
使用BigDecimal并且一定要用String来够造。
实现方法如下:
import java.math.BigDecimal;
/**
* 由于Java的简单类型不能够精确的对浮点数进行运算,这个工具类提供精
* 确的浮点数运算,包括加减乘除和四舍五入。
*/
public class Arith{
//默认除法运算精度
private static final int DEF_DIV_SCALE = 10;
//这个类不能实例化
private Arith(){
}
/**
* 提供精确的加法运算。
* @param v1 被加数
* @param v2 加数
* @return 两个参数的和
*/
public static double add(double v1,double v2){
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.add(b2).doubleValue();
}
/**
* 提供精确的减法运算。
* @param v1 被减数
* @param v2 减数
* @return 两个参数的差
*/
public static double sub(double v1,double v2){
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.subtract(b2).doubleValue();
}
/**
* 提供精确的乘法运算。
* @param v1 被乘数
* @param v2 乘数
* @return 两个参数的积
*/
public static double mul(double v1,double v2){
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.multiply(b2).doubleValue();
}
/**
* 提供(相对)精确的除法运算,当发生除不尽的情况时,精确到
* 小数点以后10位,以后的数字四舍五入。
* @param v1 被除数
* @param v2 除数
* @return 两个参数的商
*/
public static double div(double v1,double v2){
return div(v1,v2,DEF_DIV_SCALE);
}
/**
* 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指
* 定精度,以后的数字四舍五入。
* @param v1 被除数
* @param v2 除数
* @param scale 表示表示需要精确到小数点以后几位。
* @return 两个参数的商
*/
public static double div(double v1,double v2,int scale){
if(scale0){
throw new IllegalArgumentException(
"The scale must be a positive integer or zero");
}
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.divide(b2,scale,BigDecimal.ROUND_HALF_UP).doubleValue();
}
/**
* 提供精确的小数位四舍五入处理。
* @param v 需要四舍五入的数字
* @param scale 小数点后保留几位
* @return 四舍五入后的结果
*/
public static double round(double v,int scale){
if(scale0){
throw new IllegalArgumentException(
"The scale must be a positive integer or zero");
}
BigDecimal b = new BigDecimal(Double.toString(v));
BigDecimal one = new BigDecimal("1");
return b.divide(one,scale,BigDecimal.ROUND_HALF_UP).doubleValue();
}
};
分享
本回答由电脑网络分类达人 高德宝认证
其他类似问题
2009-02-08加减乘除运算(Java)14
2010-06-22Java实现有界面的简单的两个整数之间的加减乘除运算
2009-09-21myeclipse中java的加减乘除运算1
2011-05-27用java编写计算器,,,要求加减乘除等运算。。。1
2011-09-15java中的String型怎么实现数学的加减乘除运算?10
更多关于java简单加减乘除的问题
为您推荐:
举报| 2009-02-24 03:00
#为什么很多走失的孩子无法找回?#
提问者采纳
import java.util.Scanner;
class MakeOperation
{
public static void main(String[] args){
Scanner input=new Scanner(System.in);
Count count=new Count();
System.out.print("请输入你要运算的第一个数:");
count.one=input.next();
System.out.print("请输入你要进行运算的运算符:");
count.fu=input.next();
System.out.print("请输入你要运算的第二个数:");
count.two=input.next();
if(count.fu.equals("+")){
count.outcome=Float.parseFloat(count.one)+Float.parseFloat(count.two)+"";
// 将字符串解析为数字,注意下如果输入的不是数字程序会报错,缺少健壮性代码 }
System.out.println(count);
}
}
class Count{
String one;
String two;
String fu;
String outcome; // 结果
public String toString(){
return one+fu+two+"="+outcome;
}
}
下面的代码修改了Count类里域的部分参数,增加了一个用于检查输入是否正确的类。
import java.util.Scanner;
class MakeOperation
{
public static void main(String[] args){
Scanner input=new Scanner(System.in);
Count count=new Count();
CheckOperation checkOpera=new CheckOperation();
System.out.print("请输入你要运算的第一个数:");
count.one=checkOpera.checkNum(input);
System.out.print("请输入你要进行运算的运算符:");
String[] operators={"+","-","*","/"};
count.fu=checkOpera.checkOperator(input,operators);
System.out.print("请输入你要运算的第二个数:");
count.two=checkOpera.checkNum(input);
if("+".equals(count.fu)){
count.outcome=count.one+count.two;
System.out.println(count);
}
}
}
class Count{
float one;
float two;
String fu;
float outcome; // 结果
public String toString(){
return one+fu+two+"="+outcome;
}
}
class CheckOperation{
/*验证数字,输错了会提示用户重新输入*/
public float checkNum(Scanner input){
float num=0f;
try {
num=Float.parseFloat(input.next());
} catch (NumberFormatException e) {
System.out.print("请输入正确的数字: ");
num=checkNum(input); //直至获取到正确的值
}
return num;
}
/*验证输入的符号是否正确*/
public String checkOperator(Scanner input,String[] operators){
String opera=null;
boolean judge=true;
opera=input.next();
for(String operator:operators){
if(operator.equals(opera)) judge=false;
}
if(judge) {
System.out.print("请输入正确的运算符: ");
opera=checkOperator(input,operators);
}
return opera;
}
}
实际上这相当于javascript的eval方法,以下是该方法的java实现:
//Eval.java
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class Eval {
public int eval(String exp){
ListString list = infixExpToPostExp(exp);//转化成后缀表达式
return doEval(list);//真正求值
}
//遇到操作符压栈,遇到表达式从后缀表达式中弹出两个数,计算出结果,压入堆栈
private int doEval(ListString list) {
StackString stack = new StackString();
String element;
int n1,n2,result;
try{
for(int i = 0; i list.size();i++){
element = list.get(i);
if(isOperator(element)){
n1 = Integer.parseInt(stack.pop());
n2 = Integer.parseInt(stack.pop());
result = doOperate(n1,n2,element);
stack.push(new Integer(result).toString());
}else{
stack.push(element);
}
}
return Integer.parseInt(stack.pop());
}catch(RuntimeException e){
throw new IllegalExpressionException(e.getMessage());
}
}
private int doOperate(int n1, int n2, String operator) {
if(operator.equals("+"))
return n1 + n2;
else if(operator.equals("-"))
return n1 - n2;
else if(operator.equals("*"))
return n1 * n2;
else
return n1 / n2;
}
private boolean isOperator(String str){
return str.equals("+") || str.equals("-") || str.equals("*") || str.equals("/");
}
private ListString infixExpToPostExp(String exp){//将中缀表达式转化成为后缀表达式
ListString postExp = new ArrayListString();//存放转化的后缀表达式的链表
StringBuffer numBuffer = new StringBuffer();//用来保存一个数的
StackCharacter opStack = new StackCharacter();//操作符栈
char ch,preChar;
opStack.push('#');
try{
for(int i = 0; i exp.length();){
ch = exp.charAt(i);
switch(ch){
case '+':
case '-':
case '*':
case '/':
preChar = opStack.peek();
// 如果栈里面的操作符优先级比当前的大,则把栈中优先级大的都添加到后缀表达式列表中
while(priority(preChar) = priority(ch)){
postExp.add(""+preChar);
opStack.pop();
preChar = opStack.peek();
}
opStack.push(ch);
i++;
break;
case '(':
// 左括号直接压栈
opStack.push(ch);
i++;
break;
case ')':
// 右括号则直接把栈中左括号前面的弹出,并加入后缀表达式链表中
char c = opStack.pop();
while(c != '('){
postExp.add("" + c);
c = opStack.pop();
}
i++;
break;
// #号,代表表达式结束,可以直接把操作符栈中剩余的操作符全部弹出,并加入后缀表达式链表中
case '#':
char c1;
while(!opStack.isEmpty()){
c1 = opStack.pop();
if(c1 != '#')
postExp.add("" + c1);
}
i++;
break;
//过滤空白符
case ' ':
case '\t':
i++;
break;
// 数字则凑成一个整数,加入后缀表达式链表中
default:
if(Character.isDigit(ch)){
while(Character.isDigit(ch)){
numBuffer.append(ch);
ch = exp.charAt(++i);
}
postExp.add(numBuffer.toString());
numBuffer = new StringBuffer();
}else{
throw new IllegalExpressionException("illegal operator");
}
}
}
}catch(RuntimeException e){
throw new IllegalExpressionException(e.getMessage());
}
return postExp;
}
private int priority(char op){//定义优先级
switch(op){
case'+':
case'-':
return 1;
case'*':
case'/':
return 2;
case'(':
case'#':
return 0;
}
throw new IllegalExpressionException("Illegal operator");
}
}
Main.java 主函数所在类
public class Main
{
public static void main(String[] args) {
try {
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
String exp=br.readLine();
int result = eval.eval(exp);
System.out.println(result);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
IllegalExpressionException异常类
public class IllegalExpressionException extends RuntimeException{
public IllegalExpressionException(){
}
public IllegalExpressionException(String info){
super(info);
}
}
//JAVA编程:四则运算(接收用户输入的2个操作数,和运算符),计算之后,输出结果~~~~
import java.util.Scanner;
public class 四则运算 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入第一个数字:");
int a = sc.nextInt();
System.out.print("请输入运算符号:");
String str = sc.next();
char ch = str.charAt(0);
System.out.print("请输入第二个数字:");
int b = sc.nextInt();
switch(ch)
{
case '+':
System.out.println(a+"+"+ b + "="+(a+b));
break;
case '-':
System.out.println(a+"-"+ b+ "="+(a-b));
break;
case '*':
System.out.println(a+"*"+ b+ "="+(a*b));
break;
case '/':
if(b==0){
System.out.println("被除数为零,运算无意义!");
break;
}
else {
System.out.println(a+"/"+ b+ " = "+(a/b));
break;
}
default:
System.out.println("运算符是无意义字符!");
break;
}
}
}
望采纳~~~~~~~~