Math类

Math数学类的使用:

 

double abs(double a)  //求绝对值

ceil(double a)       //向上取整

floor(double a)      //向下取整

round(double a)    // 四舍五入

random()       // 产生随机数,产生的是大于等于0.0-小于1.0之间的随机数

System.out.println("绝对值" + Math.abs(-3));

System.out.println("向上取整" + Math.ceil(3.14));

System.out.println("向下取整" + Math.floor(-3.14));

System.out.println("四舍五入" + Math.round(3.82));

System.out.println("随机数" + Math.random());

    // 如果想要产生1- 10之间的随机数:0 - 10

System.out.println("随机数" + (int)(Math.random() * 11));

 

1. 生成指定范围的随机数:

//首先生成0-20的随机数,然后对(20-10+1)取模得到[0-10]之间的随机数,然后加上min=10,最后生成的是10-20的随机数

 

int max = 20;

int min = 10;

Random random = new Random();

// random.nextInt(max)表示生成[0,max]之间的随机数

int s = random.nextInt(max) % (max - min + 1) + min;

System.out.println("随机数:" + s);

 

2. 自动生成验证码:

import java.util.Random;

public class Demo2 {

public static void main(String[] args) {

// TODO Auto-generated method stub

         // 生成验证码

      char[] arr = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i','1', '2', '3', '4', '5', '6',};

  StringBuffer str = new StringBuffer();

      //随机在数组中选择四个数

      Random random = new Random();

      for(int i = 0; i < 4; i++) {

       // 开始产生随机数

       int index = random.nextInt(arr.length);

       str.append(arr[index]);

      }

 System.out.println("验证码:" + str);

}

}

 

posted @ 2016-11-28 13:59  彬之华666  阅读(103)  评论(0编辑  收藏  举报