Math类

Math数学类的使用:java

 

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

ceil(double a)       //向上取整app

floor(double a)      //向下取整dom

round(double a)    // 四舍五入spa

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

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

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

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

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

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);

}

}

相关文章
相关标签/搜索