BigDecimal的实现利用到了BigInteger,不同的是BigDecimal加入了小数的概念。一般的float型和Double型数据只可以用来做科学计算或工程计算,由于在商业计算中,要求数字精度比较高,所以要用到java.math.BigDecimal类。BigDecimal类支持任何精度的定点数,可以用它来精确计算货币值。
在BigDecimal类中常用的两个构造方法如下:
l public BigDecimal(double val):实例化时将双精度型转换为BigDecimal类型
l public BigDecimal(String val) :实例化时将字符串形式转换为BigDecimal类型
BigDecimal类型的数字可以用来做超大的浮点数的运算,比如加减乘除等,但是在所有的运算中除法是最复杂的,因为在除不尽的情况下末位小数点的处理是需要考虑的。
下面列举了BigDecimal类中实现加减乘除的方法。
l
public BigDecimal add(BigDecimal augend):做加法操作
l public BigDecimal subtract(BigDecimal subtrahend):做减法操作
l public BigDecimal multiply(BigDecimal multiplicand):做乘法操作
l public BigDecimal divide(BigDecimal divisor,int scale,int roundingMode) //做除法操作,方法中3个参数分别代表除数、商的小数点后的位数、近似处理模式
在上述方法中,roundingMode模式有多种设置,用于返回商末位小数点的处理,这些模式的名称与含义如表1所示。
下面设计一个类,这个类包括任意两个Decimal类型数字的加、减、乘、除运算方法。请读者看下面的实例。
例 在项目中创建BigDecimalDemo类,在类中分别定义add()、sub()、mul()和div()方法实现加减乘除运算,并输出运算结果。
import java.math.BigDecimal;
public class BigDecimalDemo {
static final int location = 10;
// 定义加法方法,参数为加数与被加数
public static BigDecimal add(double value1, double value2) {
BigDecimal b1 = new BigDecimal(Double.toString(value1)); // 实例化一个Decimal对象
BigDecimal b2 = new BigDecimal(Double.toString(value2));
return b1.add(b2); // 调用加法方法
}
// 定义减法方法,参数为减数与被减数
public static BigDecimal sub(double value1, double value2) {
BigDecimal b1 = new BigDecimal(Double.toString(value1));
BigDecimal b2 = new BigDecimal(Double.toString(value2));
return b1.subtract(b2); // 调用减法方法
}
// 定义乘法方法,参数为乘数与被乘数
public static BigDecimal mul(double value1, double value2) {
BigDecimal b1 = new BigDecimal(Double.toString(value1));
BigDecimal b2 = new BigDecimal(Double.toString(value2));
return b1.multiply(b2); // 调用乘法方法
}
// 定义除法方法,参数为除数与被除数
public static BigDecimal div(double value1, double value2) {
return div(value1, value2, location); // 调用自定义除法方法
}
// 定义除法方法,参数分别为除数与被除数以及商小数点后的位数
public static BigDecimal div(double value1, double value2, int b) {
if (b < 0) {
System.out.println("b值必须大于等于0");
}
BigDecimal b1 = new BigDecimal(Double.toString(value1));
BigDecimal b2 = new BigDecimal(Double.toString(value2));
// 调用除法方法,商小数点后保留b位,并将结果进行四舍五入操作
return b1.divide(b2, b, BigDecimal.ROUND_HALF_UP);
}
public static void main(String[] args) {
BigDecimalDemo b = new BigDecimalDemo();
System.out.println("两个数字相加结果:" + b.add(-7.5, 8.9));
System.out.println("两个数字相减结果:" + b.sub(-7.5, 8.9));
System.out.println("两个数字相乘结果:" + b.mul(-7.5, 8.9));
System.out.println("两个数字相除结果,结果小数后保留10位:" + b.div(10, 2));
System.out.println("两个数字相除,结果保留小数后5位:" + b.div(-7.5, 8.9, 5));
}
}
import java.util.Scanner;
public class MathDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入要计算的值");
double value=sc.nextDouble();
System.out.println("0.5的反正弦值:" + Math.asin(value));
System.out.println("0.5的反余弦值:" + Math.acos(value));
System.out.println("0.5的反正切值:" + Math.atan(value));
}
}
Math中三角函数的参数都是弧度制的。如果指定的参数是角度,就涉及了如何将角度转换成弧度。对于反三角函数其返回值是弧度的,如果需要角度则涉及如何将弧度转换成角度。这两种情况在Math类中都提供了方法来支持。本实例将演示这两个方法的使用,代码如下:
public class MathDemo {
public static void main(String[] args) {
System.out.println("弧度值0.5转换成角度值:" + Math.toDegrees(0.5));
System.out.println("角度值30转换成弧度值:" + Math.toRadians(30));
}
}
这两个方法是Math类提供的将角度转换成弧度和将弧度转换成角度的方法。其说明如下:
方法声明:public static double toDegrees(double angrad)
参数说明:angrad是需要转换的弧度
方法声明:public static double toRadians(double angdeg)
参数说明:angdeg是需要转换的角度
通过以上运算的结果,可以发现Java虚拟机的运算并不精确。例如,30°的正弦值应该是0.5,而sin()方法的返回值是0.49。这对于需要高精度的场合显然不理想,为此Java提供了BigInteger类,它可以完成任用精度的整数运算。本实例将使用其完成基本的四则运算。代码如下:
import java.math.BigInteger;
public class BigIntegerDemo2 {
public static void main(String[] args) {
BigInteger number1 = new BigInteger("5");
BigInteger number2 = new BigInteger("10");
System.out.println("5+10="+number1.add(number2));
System.out.println("5 - 10 = " + number1.subtract(number2));
System.out.println("5 * 10 = " + number1.multiply(number2));
System.out.println("5 / 10 = " + number1.divide(number2));
Big();
}
public static void Big(){
BigInteger result = BigInteger.ONE;
for(int i=1;i<201;i++) {
BigInteger number = new BigInteger(new Integer(i).toString());
result = result.multiply(number);
}
System.out.println(result);
}
}
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.UIManager;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class SimulatedClock extends JFrame {
/**
*
*/
private static final long serialVersionUID = 6800523034864043557L;
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Throwable e) {
e.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SimulatedClock frame = new SimulatedClock();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public SimulatedClock() {
addWindowListener(new WindowAdapter() {
@Override
public void windowActivated(WindowEvent e) {
do_this_windowActivated(e);
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 300, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
}
public void paint(Graphics g) {
super.paint(g);// 调用父类的paint()方法,这样能在画图时能保存外观
Rectangle rectangle = getBounds();// 获得组件的区域
Insets insets = getInsets();// 获得组件的边框
int radius = 120;// 设置圆的半径是120px
int x = (rectangle.width - 2 * radius - insets.left - insets.right) / 2 + insets.left;
int y = (rectangle.height - 2 * radius - insets.top - insets.bottom) / 2 + insets.top;
Point2D.Double center = new Point2D.Double(x + radius, y + radius);// 获得圆心坐标
Point2D.Double[] scales = new Point2D.Double[60];// 用60个点保存表盘的刻度
double angle = Math.PI / 30;// 表盘上两个点之间的夹角是PI/30
for (int i = 0; i < scales.length; i++) {// 获得所有刻度的坐标
scales[i] = new Point2D.Double();// 初始化点对象
scales[i].setLocation(x + radius + radius * Math.sin(angle * i), y + radius - radius * Math.cos(angle * i));// 利用三角函数计算点的坐标
}
for (int i = 0; i < scales.length; i++) {// 画所有刻度
if (i % 5 == 0) {// 如果序号是5则画成大点,这些点相当于石英钟上的数字
g.setColor(Color.RED);
g.fillOval((int) scales[i].x - 4, (int) scales[i].y - 4, 8, 8);
} else {// 如果序号不是5则画成小点,这些点相当于石英钟上的小刻度
g.setColor(Color.CYAN);
g.fillOval((int) scales[i].x - 2, (int) scales[i].y - 2, 4, 4);
}
}
Calendar calendar = new GregorianCalendar();// 创建日期对象
int hour = calendar.get(Calendar.HOUR);// 获得当前小时数
int minute = calendar.get(Calendar.MINUTE);// 获得当前分钟数
int second = calendar.get(Calendar.SECOND);// 获得当前秒数
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.red);// 将颜色设置成红色
g2d.draw(new Line2D.Double(center, scales[second]));// 绘制秒针
BasicStroke bs = new BasicStroke(3f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER);
g2d.setStroke(bs);
g2d.setColor(Color.blue);// 将颜色设置成蓝色
g2d.draw(new Line2D.Double(center, scales[minute]));// 绘制分针
bs = new BasicStroke(6f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER);
g2d.setStroke(bs);
g2d.setColor(Color.green);// 将颜色设置成绿色
g2d.draw(new Line2D.Double(center, scales[hour * 5 + minute / 12]));// 绘制时针
}
protected void do_this_windowActivated(WindowEvent e) {
new Thread() {
public void run() {
while (true) {
repaint();// 绘制时钟
try {
Thread.sleep(1000);// 线程休眠1秒钟
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
}.start();
}
}
增加圆形表盘
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.UIManager;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class SimulatedClock extends JFrame {
/**
*
*/
private static final long serialVersionUID = 6800523034864043557L;
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Throwable e) {
e.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SimulatedClock frame = new SimulatedClock();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public SimulatedClock() {
addWindowListener(new WindowAdapter() {
@Override
public void windowActivated(WindowEvent e) {
do_this_windowActivated(e);
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 300, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
}
public void paint(Graphics g) {
super.paint(g);// 调用父类的paint()方法,这样能在画图时能保存外观
Rectangle rectangle = getBounds();// 获得组件的区域
Insets insets = getInsets();// 获得组件的边框
int radius = 120;// 设置圆的半径是120px
int x = (rectangle.width - 2 * radius - insets.left - insets.right) / 2 + insets.left;
int y = (rectangle.height - 2 * radius - insets.top - insets.bottom) / 2 + insets.top;
Point2D.Double center = new Point2D.Double(x + radius, y + radius);// 获得圆心坐标
g.drawOval(x, y, 2 * radius, 2 * radius);// 绘制圆形
Point2D.Double[] scales = new Point2D.Double[60];// 用60个点保存表盘的刻度
double angle = Math.PI / 30;// 表盘上两个点之间的夹角是PI/30
for (int i = 0; i < scales.length; i++) {// 获得所有刻度的坐标
scales[i] = new Point2D.Double();// 初始化点对象
scales[i].setLocation(x + radius + radius * Math.sin(angle * i), y + radius - radius * Math.cos(angle * i));// 利用三角函数计算点的坐标
}
for (int i = 0; i < scales.length; i++) {// 画所有刻度
if (i % 5 == 0) {// 如果序号是5则画成大点,这些点相当于石英钟上的数字
g.setColor(Color.RED);
g.fillOval((int) scales[i].x - 4, (int) scales[i].y - 4, 8, 8);
} else {// 如果序号不是5则画成小点,这些点相当于石英钟上的小刻度
g.setColor(Color.CYAN);
g.fillOval((int) scales[i].x - 2, (int) scales[i].y - 2, 4, 4);
}
}
Calendar calendar = new GregorianCalendar();// 创建日期对象
int hour = calendar.get(Calendar.HOUR);// 获得当前小时数
int minute = calendar.get(Calendar.MINUTE);// 获得当前分钟数
int second = calendar.get(Calendar.SECOND);// 获得当前秒数
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.red);// 将颜色设置成红色
g2d.draw(new Line2D.Double(center, scales[second]));// 绘制秒针
BasicStroke bs = new BasicStroke(3f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER);
g2d.setStroke(bs);
g2d.setColor(Color.blue);// 将颜色设置成蓝色
g2d.draw(new Line2D.Double(center, scales[minute]));// 绘制分针
bs = new BasicStroke(6f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER);
g2d.setStroke(bs);
g2d.setColor(Color.green);// 将颜色设置成绿色
g2d.draw(new Line2D.Double(center, scales[hour * 5 + minute / 12]));// 绘制时针
}
protected void do_this_windowActivated(WindowEvent e) {
new Thread() {
public void run() {
while (true) {
repaint();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
}.start();
}
}
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
public class PermanentCalendar extends JFrame {
/**
*
*/
private static final long serialVersionUID = 3169863775528020253L;
private JTable table;
private JLabel currentMonthLabel;
private Calendar calendar = new GregorianCalendar();
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Throwable e) {
e.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PermanentCalendar frame = new PermanentCalendar();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public PermanentCalendar() {
setTitle("\u516C\u5386\u4E07\u5E74\u5386");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 282);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel YMPanel = new JPanel();
contentPane.add(YMPanel, BorderLayout.NORTH);
YMPanel.setLayout(new GridLayout(1, 3, 5, 10));
JPanel lastMonthPanel = new JPanel();
YMPanel.add(lastMonthPanel);
JButton lastMonthButton = new JButton("\u4E0A\u4E2A\u6708");
lastMonthButton.setFont(new Font("微软雅黑", Font.PLAIN, 16));
lastMonthButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
do_lastMonthButton_actionPerformed(e);
}
});
lastMonthPanel.add(lastMonthButton);
JPanel currentMonthPanel = new JPanel();
YMPanel.add(currentMonthPanel);
currentMonthPanel.setLayout(new BoxLayout(currentMonthPanel, BoxLayout.X_AXIS));
currentMonthLabel = new JLabel("");
currentMonthLabel.setFont(new Font("微软雅黑", Font.PLAIN, 20));
currentMonthLabel.setHorizontalAlignment(SwingConstants.CENTER);
currentMonthPanel.add(currentMonthLabel);
JPanel nextMonthPanel = new JPanel();
YMPanel.add(nextMonthPanel);
JButton nextMonthButton = new JButton("\u4E0B\u4E2A\u6708");
nextMonthButton.setFont(new Font("微软雅黑", Font.PLAIN, 16));
nextMonthButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
do_nextMonthButton_actionPerformed(e);
}
});
nextMonthPanel.add(nextMonthButton);
JScrollPane scrollPane = new JScrollPane();
contentPane.add(scrollPane, BorderLayout.CENTER);
table = new JTable();
table.setFont(new Font("微软雅黑", Font.PLAIN, 18));
table.getTableHeader().setFont(new Font("微软雅黑", Font.PLAIN, 20));
table.setRowHeight(25);
table.setCellSelectionEnabled(true);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
scrollPane.setViewportView(table);
currentMonthLabel.setText(updateLabel(0));
updateTable(calendar);
}
private void updateTable(Calendar calendar) {
String[] weeks = new DateFormatSymbols().getShortWeekdays();// 获得表示星期的字符串数组
String[] realWeeks = new String[7];// 新建一个数组来保存截取后的字符串
for (int i = 1; i < weeks.length; i++) {// weeks数组第一个元素是空字符串,因此从1开始循环
realWeeks[i - 1] = weeks[i].substring(2, 3);// 获得字符串的最后一个字符
}
int today = calendar.get(Calendar.DATE);// 获得当前日期
int monthDays = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);// 获得当前月的天数
calendar.set(Calendar.DAY_OF_MONTH, 1); // 将时间设置为本月第一天
int weekday = calendar.get(Calendar.DAY_OF_WEEK);// 获得本月第一天是星期几
int firstDay = calendar.getFirstDayOfWeek(); // 获得当前地区星期的起始日
int whiteDay = weekday - firstDay; // 这个月第一个星期有几天被上个月占用
Object[][] days = new Object[6][7];// 新建一个二维数组来保存当前月的各天
for (int i = 1; i <= monthDays; i++) {// 遍历当前月的所有天并将其添加的二维数组中
days[(i - 1 + whiteDay) / 7][(i - 1 + whiteDay) % 7] = i;
}// 数组的第一维表示一个月中各个星期,第二位表示一个星期中各个天
DefaultTableModel model = (DefaultTableModel) table.getModel();// 获得当前表格的模型
model.setDataVector(days, realWeeks);// 给表格模型设置表头和表体
table.setModel(model);// 更新表格模型
table.setRowSelectionInterval(0, (today - 1 + whiteDay) / 7);// 设置选择的行
table.setColumnSelectionInterval(0, (today - 1 + whiteDay) % 7);// 设置选择的列
}
private String updateLabel(int increment) {
calendar.add(Calendar.MONTH, increment);// 将当前月份增加increment月
SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月");// 设置字符串格式
return formatter.format(calendar.getTime());// 获得指定格式的字符串
}
protected void do_lastMonthButton_actionPerformed(ActionEvent e) {
currentMonthLabel.setText(updateLabel(-1));
updateTable(calendar);
}
protected void do_nextMonthButton_actionPerformed(ActionEvent e) {
currentMonthLabel.setText(updateLabel(1));
updateTable(calendar);
}
}
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
public class SevenStar extends JFrame {
/**
*
*/
private static final long serialVersionUID = 6787592245621788484L;
private JPanel contentPane;
private JTextField textField;
private JTextArea textArea;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Throwable e) {
e.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SevenStar frame = new SevenStar();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public SevenStar() {
setTitle("\u4E03\u661F\u5F69\u53F7\u7801\u751F\u6210\u5668");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.NORTH);
panel.setLayout(new GridLayout(1, 2, 5, 5));
JLabel label = new JLabel("\u8BF7\u8F93\u5165\u53F7\u7801\u4E2A\u6570\uFF1A");
label.setFont(new Font("微软雅黑", Font.PLAIN, 18));
label.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(label);
textField = new JTextField();
textField.setFont(new Font("微软雅黑", Font.PLAIN, 18));
panel.add(textField);
textField.setColumns(10);
JPanel buttonPanel = new JPanel();
contentPane.add(buttonPanel, BorderLayout.SOUTH);
JButton button = new JButton("\u751F\u6210\u53F7\u7801");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
do_button_actionPerformed(e);
}
});
button.setFont(new Font("微软雅黑", Font.PLAIN, 18));
buttonPanel.add(button);
JScrollPane scrollPane = new JScrollPane();
contentPane.add(scrollPane, BorderLayout.CENTER);
textArea = new JTextArea();
textArea.setFont(new Font("微软雅黑", Font.PLAIN, 18));
scrollPane.setViewportView(textArea);
}
protected void do_button_actionPerformed(ActionEvent e) {
int times = Integer.parseInt(textField.getText());// 获得用户输入的需要生成的中奖号码个数
StringBuilder sb = new StringBuilder();// 利用StringBuilder类保存彩票中奖号码
for (int i = 0; i < times; i++) {
int number = new Random().nextInt((int) Math.pow(10, 7));// 生成随机数
String luckNumber = "" + number;
while (luckNumber.length() < 7) {
luckNumber = "0" + luckNumber;// 如果随机数长度不够7位用0补齐
}
sb.append(luckNumber + "\n");
}
textArea.setText(sb.toString());// 显示生成的中奖号码
}
}
public class RandomTest {
/**
* @param args
* 获取2到32之间的6个偶数,并且求这6个偶数的和
*/
public static double EvenNum(double num1, double num2) {
double s = 0;
int[] j = new int[6];
Random cres = new Random();
for (int w = (int) num1, i = 0; w <= (int) num2; w += 2) {
j[i] = cres.nextInt((int) num2);
if (j[i] != 0 && j[i] % 2 == 0) {
System.out.println(j[i]);
s += j[i];
i++;
}
if (i == 6)
break;
}
return s;
}
public static double EvenNum2(double num1, double num2) {
double s = 0;
int[] j = new int[6];
for (int i = 0, w = 0; i < 20; i++) {
j[w] = (int) num1 + (int) (Math.random() * (num2 - num1));
if (j[w] != 0 && j[w] % 2 == 0) {
System.out.println("打印2到32之间的偶数(不包括32)" + j[w]);
s += j[w];
w++;
}
if (w == 6)
break;
}
return s;
}
public static void main(String[] args) {
System.out.println("和为:" + EvenNum2(2, 32));
}
}
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.LineBorder;
public class NumberFormateDemo extends JFrame {
private JTextArea infoArea;
private JTextField numberField;
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
NumberFormateDemo frame = new NumberFormateDemo();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* 创建窗体的构造方法
*/
public NumberFormateDemo() {
super();
final BorderLayout borderLayout = new BorderLayout(10,10);
getContentPane().setLayout(borderLayout);
setBounds(100, 100, 348, 225);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
getContentPane().add(panel, BorderLayout.NORTH);
final JLabel label = new JLabel();
label.setText("请输入要格式化的数字:");
panel.add(label, BorderLayout.WEST);
numberField = new JTextField(); // 创建数字文本框
numberField.setText("60"); // 演示数字
panel.add(numberField);
final JButton button = new JButton(); // 创建确定按钮
button.addActionListener(new ActionListener() { // 添加事件监听器
public void actionPerformed(final ActionEvent e) {
do_button_actionPerformed(e);
}
});
button.setText("确定");
panel.add(button, BorderLayout.EAST);
infoArea = new JTextArea(); // 创建文本域组件
infoArea.setFont(new Font("宋体", Font.PLAIN, 15)); // 设置字体
infoArea.setBorder(new LineBorder(Color.black, 1, false));
infoArea.setEditable(false); // 禁止编辑
getContentPane().add(infoArea);
setTitle("格式化数字");
}
/**
* 确定按钮的事件处理方法
* @param e 动作事件
*/
protected void do_button_actionPerformed(final ActionEvent e) {
String text = numberField.getText();
if(text==null||text.isEmpty()){ // 如果没有输入数字
infoArea.setText("请输入数字"); // 显示提示信息
return; // 结束该方法
}
double number=0;
try {
number = Double.parseDouble(text.trim()); // 字符串转换为数字
} catch (NumberFormatException e1) {
infoArea.setText("请输入正确的数字"); // 显示提示信息
return; // 结束该方法
}
infoArea.setText("");
DecimalFormat dmf=new DecimalFormat(); // 创建数字格式化对象
addRmbFormat(number, dmf); // 格式化为人民币格式
grouping3(number, dmf); // 3位分组
grouping4(number, dmf); // 4为分组
keep6(number, dmf); // 强制保留6位小数
percent(number, dmf); // 百分比格式输出
}
/**
* 百分比格式输出
* @param number 组字
* @param dmf 数字格式化对象
*/
private void percent(double number, DecimalFormat dmf) {
dmf.applyPattern("百分比:#.00%\n");
String numStr = dmf.format(number);
infoArea.append(numStr);
}
/**
* 强制保留6位小数
* @param number 组字
* @param dmf 数字格式化对象
*/
private void keep6(double number, DecimalFormat dmf) {
String numStr;
dmf.applyPattern("强制保留6位小数:#.000000\n");
numStr = dmf.format(number);
infoArea.append(numStr);
}
/**
* 按4为数字分组
* @param number 组字
* @param dmf 数字格式化对象
*/
private void grouping4(double number, DecimalFormat dmf) {
dmf.setGroupingUsed(true);
dmf.setGroupingSize(4);
String grouping4 = "按4为数字分组:" + dmf.format(number) + "\n";
infoArea.append(grouping4);
dmf.setGroupingUsed(false);
}
/**
* 按3为数字分组
* @param number 组字
* @param dmf 数字格式化对象
*/
private void grouping3(double number, DecimalFormat dmf) {
dmf.setGroupingUsed(true);
dmf.setGroupingSize(3);
dmf.applyPattern("");
String grouping3 = "按3为数字分组:" + dmf.format(number) + "\n";
infoArea.append(grouping3);
dmf.setGroupingUsed(false);
}
/**
* 人名币格式输出
* @param number 组字
* @param dmf 数字格式化对象
*/
private void addRmbFormat(double number, DecimalFormat dmf) {
dmf.applyPattern("人民币:¥#.00元\n");
String RMB = dmf.format(number);
infoArea.append(RMB);
}
}
public class UseCase {
/**
* @param args
*/
public static BigDecimal div(double value1,double value2,int b,int r){
if(b<0){
System.out.println("b值必须大于等于0");
}
BigDecimal b1=new BigDecimal(Double.toString(value1));
BigDecimal b2=new BigDecimal(Double.toString(value2));
return b1.divide(b2,b,r);
}
public static void main(String[] args) {
UseCase u=new UseCase();
System.out.println(u.div(-7.5,8.9,5,BigDecimal.ROUND_CEILING));
System.out.println(u.div(-7.5,8.9,5,BigDecimal.ROUND_DOWN));
System.out.println(u.div(-7.5,8.9,5,BigDecimal.ROUND_FLOOR));
System.out.println(u.div(-7.5,8.9,5,BigDecimal.ROUND_HALF_DOWN));
System.out.println(u.div(-7.5,8.9,5,BigDecimal.ROUND_HALF_EVEN));
System.out.println(u.div(-7.5,8.9,5,BigDecimal.ROUND_HALF_UP));
System.out.println(u.div(-7.5,8.9,5,BigDecimal.ROUND_UP));
}
}
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.border.LineBorder;
public class AccountRadian extends JFrame {
private JTextArea infoArea;
private JTextField numberField;
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
AccountRadian frame = new AccountRadian();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* 创建窗体的构造方法
*/
public AccountRadian() {
super();
final BorderLayout borderLayout = new BorderLayout(10,10);
getContentPane().setLayout(borderLayout);
setBounds(100, 100, 348, 225);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
getContentPane().add(panel, BorderLayout.NORTH);
final JLabel label = new JLabel();
label.setText("请输入要计算弧度的数字:");
panel.add(label, BorderLayout.WEST);
numberField = new JTextField(); // 创建数字文本框
numberField.setText("90"); // 演示数字
panel.add(numberField);
final JButton button = new JButton(); // 创建确定按钮
button.addActionListener(new ActionListener() { // 添加事件监听器
public void actionPerformed(final ActionEvent e) {
do_button_actionPerformed(e);
}
});
button.setText("确定");
panel.add(button, BorderLayout.EAST);
infoArea = new JTextArea(); // 创建文本域组件
infoArea.setFont(new Font("宋体", Font.PLAIN, 15)); // 设置字体
infoArea.setBorder(new LineBorder(Color.black, 1, false));
infoArea.setEditable(false); // 禁止编辑
getContentPane().add(infoArea);
setTitle("格式化数字");
}
/**
* 确定按钮的事件处理方法
* @param e 动作事件
*/
protected void do_button_actionPerformed(final ActionEvent e) {
String text = numberField.getText();
if(text==null||text.isEmpty()){ // 如果没有输入数字
infoArea.setText("请输入数字"); // 显示提示信息
return; // 结束该方法
}
double number=0;
try {
number = Double.parseDouble(text.trim()); // 字符串转换为数字
} catch (NumberFormatException e1) {
infoArea.setText("请输入正确的数字"); // 显示提示信息
return; // 结束该方法
}
infoArea.setText("");
percent(number);
addRmbFormat(number);
grouping3(number);
grouping4(number);
keep6(number);
getRadian(number);
}
/**
* 计算某数的三角正弦值
*/
private void percent(double number) {
Double doub = Math.sin(number);
infoArea.append("该数的正弦值是:"+doub+"\n");
}
/**
* 获取余弦值
*/
private void keep6(double number) {
double doub = Math.cos(number);
infoArea.append("该数的余弦值是:"+doub+"\n");
}
/**
* 获取某数的正切值
*/
private void grouping4(double number) {
double doub = Math.tan(number);
infoArea.append("该数的正切值是:"+doub+"\n");
}
/**
* 获取某数的反正弦值
*/
private void grouping3(double number) {
double doub = Math.asin(number);
infoArea.append("该数的反正弦值是:"+doub+"\n");
}
/**
* 获取某数的反余弦值
*/
private void addRmbFormat(double number) {
double doubl = Math.acos(number);
infoArea.append("该数的反余弦值是:"+doubl+"\n");
}
/**
* 获取某数的反余弦值
*/
private void getRadian(double number) {
double doubl = Math.toRadians(number);
infoArea.append("该数的弧度是:"+doubl);
}
}
public class Example {
public static void main(String[] args) {
double pfg=0;
double lfg=0; //存放立方根的变量
double cf=0; //存放乘方的变量
//求出5000的平方根,并转换为与结果最接近的整数
pfg=Math.rint(Math.sqrt(5000));
//求出5000的立方根,并转换为与结果最接近的整数
lfg=Math.rint(Math.cbrt(5000));
//求出1.33的立方,并转换为与结果最接近的整数
cf=Math.rint(Math.pow(1.33,3));
System.out.println("5000的平方根是:"+pfg);
System.out.println("5000的立方根是:"+lfg);
System.out.println("1.33的立方是:"+cf);
}
}
public class Example {
public static void main(String[] args) {
// 产生0(含0)~100(不含100)之间的随机整数
int result = (int) (Math.random() * 100);
System.out.println("产生0(含0)~100(不含100)之间的随机整数:" + result);
// 产生1(含1)~100(含100)之间的随机整数
result = (int) (Math.random() * 100 + 1);
System.out.println("产生1(含1)~100(含100)之间的随机整数" + result);
// 产生15(含15)~70(含70)之间的随机整数
result = (int) (Math.random() * 56 + 15);
System.out.println("产生15(含15)~70(含70)之间的随机整数" + result);
}
}
import java.text.DecimalFormat;
public class Example {
public static void main(String[] args) {
double num=123456789.123456;
//实例化DecimalFormat对象
DecimalFormat format=new DecimalFormat("###,###,###.####");
String str=format.format(num); //将数字进行格式化
System.out.println(str); //输出格式化的内容
}
}