Math
数学相关的工具类,提供大量的静态方法,完成与数学运算的相关操作。
常用方法
public static double abs(double num);绝对值
public static double ceil(double num);向上取整
public static double floor(double num);向下取整
public static long round(double num);四舍五入
小问题举例
1、计算在-10.8到5.9之间,绝对值大于6或者小于2.1的整数有多少个?
import java.util.ArrayList;
import static java.lang.Math.ceil;
import static java.lang.Math.floor;
import static java.lang.Math.abs;
public class Demo1 {
//计算在-10.8到5.9之间,绝对值大于6或者小于2.1的整数有多少个?
public static void main(String[] args) {
double a=-10.8;
double b=5.9;
//分别向上向下取整数并且强制转换为整数
int c=(int)ceil(a);
int d=(int)floor(b);
ArrayList<Integer> list=new ArrayList<>();
int count=0;
for (int i = c; i <= d ; i++) {
if(abs(i)>6||abs(i)<2.1) {
list.add(i);
count++;
}
}
System.out.println("绝对值大于6或者小于2.1的整数:"+list+",个数为:"+count);
}
}
2、发红包的小例子
群主有一笔金额,群主从余额中扣除金额,将金额均分为n份,让成员领取。
成员领取红包后,保存到成员的余额当中。
public class User {
private String name;
private int balance;
public User() {
}
public User(String name, int balance) {
this.name = name;
this.balance = balance;
}
public void show(){
System.out.println(name+":"+balance);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
}
import java.util.ArrayList;
public class GroupHolder extends User{
public GroupHolder() {
}
public GroupHolder(String name, int balance) {
super(name, balance);
}
public ArrayList<Integer> send (int totalMoney, int count){
//判断余额是否充足
if(super.getBalance()<totalMoney){
System.out.println("余额不足!");
}else {
//设置剩余红包钱数
super.setBalance(super.getBalance()-totalMoney);
}
int redbag=totalMoney/count;
int redbag1=totalMoney%count;
ArrayList<Integer> list=new ArrayList<>();
for (int i = 0; i < count-1; i++) {
list.add(redbag);
}
list.add(redbag+redbag1);
return list;
}
}
import java.util.Random;
public class NormalUser extends User{
public NormalUser() {
}
public NormalUser(String name, int balance) {
super(name, balance);
}
public void receive(ArrayList<Integer> list){
//从群主的红包中随机抽取一个
Random r=new Random();
int num=r.nextInt(list.size());
//获取指定位置的红包,并加入余额当中
super.setBalance(super.getBalance()+list.get(num));
//获取红包后将红包移除
list.remove(num);
}
}
import java.util.ArrayList;
public class Aplication {
public static void main(String[] args) {
ArrayList<Integer> list =new ArrayList<>();
GroupHolder g=new GroupHolder("群主",1000);
NormalUser n1=new NormalUser("张三",10);
NormalUser n2=new NormalUser("李四",10);
NormalUser n3=new NormalUser("王五",10);
g.show();
n1.show();
n2.show();
n3.show();
System.out.println("===========");
list=g.send(20,3);
n1.receive(list);
n2.receive(list);
n3.receive(list);
g.show();
n1.show();
n2.show();
n3.show();
}
}