目录
一、Math和BigDecimal
package t12_7;
import java.math.BigDecimal;
/**
* 数学类
* Math:属性和方法全为static
* BigDecimal 小数精确运算,可以指定小数点后的位数
* @author 惊蛰
*
*/
public class Test {
public static void main(String[] args) {
//Math:属性和方法全为static
System.out.println(Math.max(1, 9));
//BigDecimal 小数精确运算,可以指定小数点后的位数
BigDecimal num1 = new BigDecimal("3.14");
BigDecimal num2 = new BigDecimal("2.15");
BigDecimal result = null;
//加add
result = num1.add(num2);
System.out.println(result);
//减subtract
result = num1.subtract(num2);
System.out.println(result);
//乘multiply
result = num1.multiply(num2);
System.out.println(result);
//除divide,可设置精度
result = num1.divide(num2,2);
System.out.println(result);
result = num1.divide(num2,4,BigDecimal.ROUND_HALF_UP);//四舍五入
System.out.println(result);
//设置精度setScale
BigDecimal num3 = num1.multiply(num2);
System.out.println("result1:"+num3);
System.out.println("result2:"+num3.setScale(1,BigDecimal.ROUND_HALF_UP));
//精确运算
double d1 = 3.14;
double d2 = 2.15;
System.out.println(d1*d2);
System.out.println(num1.multiply(num2));
}
}
二、Random
1.产生随机数
package t12_7_1;
import java.util.Random;
/**
* Random类
* @author 惊蛰
*
*/
public class Test {
public static void main(String[] args) {
//生成伪随机数
Random rd = new Random();
System.out.println(rd.nextInt());//随机
System.out.println(rd.nextInt(10));//0-9
}
}
2.彩票兑奖系统
package t12_7_1;
/**
* 彩票兑奖
*/
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class caipiao {
public static Scanner sc = new Scanner(System.in);
public static Integer buy[] = new Integer[3];
public static Integer win[] = new Integer[3];
public static void main(String[] args) {
//1.购买彩票
buyLottery();
//2.彩票开奖
getWinno();
//3.兑奖
getWinmoney();
}
private static void getWinmoney() {
int num = 0;
for(int i=0;i<3;i++) {
if(buy[i] == win[i]) {
num++;
}
}
System.out.println("您买中"+num+"个号码");
}
private static void getWinno() {
Random rd = new Random();
for(int i=0;i<3;i++) {
win[i] = rd.nextInt(10);
}
System.out.println("开奖号码为"+Arrays.toString(win));
}
private static void buyLottery() {
System.out.println("请输入购买的彩票");
for(int i=0;i<3;i++) {
buy[i] = sc.nextInt();
}
System.out.println("您购买的号码为"+Arrays.toString(buy));
}
}
3.生成随机验证码,验证时忽略大小写
package t12_7_1;
import java.util.Random;
import java.util.Scanner;
/**
* 生成5位置随机验证码
* @author 惊蛰
*
*/
public class TestRandomCode {
public static StringBuilder str1 = new StringBuilder();
public static String s1;
public static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
//生成验证码
String create = RandomCode();
System.out.println(create);
System.out.println("请输入验证码");
s1 = sc.next();
//equals 逐个比对
//equalsIgnoreCase 逐个比对,并忽略大小写
if(s1.equalsIgnoreCase(create)){
System.out.println("pass");
}
else {
System.out.println("error");
}
}
private static String RandomCode() {
char[] ch = {'4','5','6','7','8','9','a'
,'b','c','d'};
Random rd = new Random();
int num;
for(int i=1;i<=5;i++) {
num = rd.nextInt(10);
str1.append(ch[num]);
}
return str1.toString();
}
}