java的加减乘除代码 java加减乘除math

java的加减乘除运算使用BigDecimal并且一定要用String来够造 。
实现方法如下:
import java.math.BigDecimal;
/**
* 由于Java的简单类型不能够精确的对浮点数进行运算java的加减乘除代码,这个工具类提供精
* 确的浮点数运算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();
}
/**
* 提供(相对)精确的除法运算java的加减乘除代码,当发生除不尽的情况时 , 精确到
* 小数点以后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();
}
};
加减乘除运算(Java)实际上这相当于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; ilist.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 n1n2;
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; iexp.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写计算器代码加减乘除import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener
{
private boolean dotExist, operated, equaled; // 帮助运算的布尔变量
private double storedNumber; // 目前的结果
private char lastOperator; // 表示上一运算符
private JTextField operation; // 结果栏
private JButton dot, plus, minus, multi, div, sqrt, equal, changePN, clear; // 运算符
private JButton[] numbers; // 数字
// 构造者
public Calculator()
{
【java的加减乘除代码 java加减乘除math】setTitle("Calculator");
// 初始化变量
dotExist = false; // 表示当前的数是否有小数点
operated = false; // 表示任意运算符是否被按下
equaled = false; // 表示等号是否被按下
storedNumber = 0;
lastOperator = '?';
// 初始化窗口变量
operation = new JTextField("0");
operation.setEditable(false);
numbers = new JButton[10];
for (int i = 0; i10; i)
numbers[i] = new JButton(""i);
dot = new JButton(".");
plus = new JButton(" ");
minus = new JButton("-");
multi = new JButton("*");
div = new JButton("/");
sqrt = new JButton("√");
equal = new JButton("=");
changePN = new JButton("±");
clear = new JButton("AC");
// 将窗口物体放入窗口
GridBagLayout layout = new GridBagLayout();
getContentPane().setLayout(layout);
addComponent(layout, operation, 0, 0, 4, 1);
addComponent(layout, numbers[1], 1, 0, 1, 1);
addComponent(layout, numbers[2], 1, 1, 1, 1);
addComponent(layout, numbers[3], 1, 2, 1, 1);
addComponent(layout, numbers[4], 2, 0, 1, 1);
addComponent(layout, numbers[5], 2, 1, 1, 1);
addComponent(layout, numbers[6], 2, 2, 1, 1);
addComponent(layout, numbers[7], 3, 0, 1, 1);
addComponent(layout, numbers[8], 3, 1, 1, 1);
addComponent(layout, numbers[9], 3, 2, 1, 1);
addComponent(layout, dot, 4, 0, 1, 1);
addComponent(layout, numbers[0], 4, 1, 1, 1);
addComponent(layout, sqrt, 4, 2, 1, 1);
addComponent(layout, plus, 1, 3, 1, 1);
addComponent(layout, minus, 2, 3, 1, 1);
addComponent(layout, multi, 3, 3, 1, 1);
addComponent(layout, div, 4, 3, 1, 1);
addComponent(layout, equal, 5, 0, 2, 1);
addComponent(layout, changePN, 5, 2, 1, 1);
addComponent(layout, clear, 5, 3, 1, 1);
}
// 对按钮进行反应的方法
public void actionPerformed(ActionEvent e)
{
JButton btn = (JButton)e.getSource();
if (btn == clear)
{
operation.setText("0");
dotExist = false;
storedNumber = 0;
lastOperator = '?';
}
else if (btn == equal)
{
operate('=');
equaled = true;
}
else if (btn == plus)
{
operate(' ');
equaled = false;
}
else if (btn == minus)
{
operate('-');
equaled = false;
}
else if (btn == multi)
{
operate('*');
equaled = false;
}
else if (btn == div)
{
operate('/');
equaled = false;
}
else if (btn == changePN)
{
operate('p');
operate('=');
equaled = true;
}
else if (btn == sqrt)
{
operate('s');
operate('=');
equaled = true;
}
else
{
if (equaled)
storedNumber = 0;
for (int i = 0; i10; i)
if (btn == numbers[i])
{
if (operation.getText().equals("0"))
operation.setText(""i);
else if(! operated)
operation.setText(operation.getText()i);
else
{
operation.setText(""i);
operated = false;
}
}
if (btn == dot! dotExist)
{
operation.setText(operation.getText()".");
dotExist = true;
}
}
}
// 进行运算的方法
private void operate(char operator)
{
double currentNumber = Double.valueOf(operation.getText()).doubleValue();
if (lastOperator == '?')
storedNumber = currentNumber;
else if (lastOperator == ' ')
storedNumber= currentNumber;
else if (lastOperator == '-')
storedNumber -= currentNumber;
else if (lastOperator == '*')
storedNumber *= currentNumber;
else if (lastOperator == '/')
storedNumber /= currentNumber;
else if (lastOperator == 'p')
storedNumber *= -1;
else if (lastOperator == 's')
storedNumber = Math.sqrt(currentNumber);
else if (lastOperator == '='equaled)
storedNumber = currentNumber;
operation.setText(""storedNumber);
operated = true;
lastOperator = operator;
}
// 快捷使用GridBagLayout的方法
private void addComponent(GridBagLayout layout, Component component, int row, int col, int width, int height)
{
GridBagConstraints constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.BOTH;
constraints.insets = new Insets(10, 2, 10, 2);
constraints.weightx = 100;
constraints.weighty = 100;
constraints.gridx = col;
constraints.gridy = row;
constraints.gridwidth = width;
constraints.gridheight = height;
layout.setConstraints(component, constraints);
if (component instanceof JButton)
((JButton)component).addActionListener(this);
getContentPane().add(component);
}
// 主方法初始化并显示窗口
public static void main(String[] args)
{
Calculator calc = new Calculator();
calc.setSize(290, 400);
calc.setVisible(true);
}
}
用Java编写实现加减乘除,界面如下用Java编写的实现加减乘除的程序如下
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);
}
}
}
运行结果
关于java的加减乘除代码和java加减乘除math的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站 。

    推荐阅读