java常用类解析十一:Random类(Math.random())生成指定范围的随机数或字符

来源:互联网 发布:怎么样自学编程 编辑:程序博客网 时间:2024/05/29 08:40
[java] view plaincopy
  1. package mine.util.others;  
  2.   
  3. import java.util.Random;  
  4.   
  5. public class GetRandom {  
  6.     // 返回ch1和ch2之间(包括ch1,ch2)的任意一个字符,如果ch1 > ch2,返回'\0'  
  7.     public static char getRandomChar(char ch1, char ch2) {  
  8.         if (ch1 > ch2)  
  9.             return 0;  
  10.         // 下面两种形式等价  
  11.         // return (char) (ch1 + new Random().nextDouble() * (ch2 - ch1 + 1));  
  12.         return (char) (ch1 + Math.random() * (ch2 - ch1 + 1));  
  13.     }  
  14.   
  15.     // 返回a到b之間(包括a,b)的任意一個自然数,如果a > b || a < 0,返回-1  
  16.     public static int getRandomInt(int a, int b) {  
  17.         if (a > b || a < 0)  
  18.             return -1;  
  19.         // 下面两种形式等价  
  20.         // return a + (int) (new Random().nextDouble() * (b - a + 1));  
  21.         return a + (int) (Math.random() * (b - a + 1));  
  22.     }  
  23. }  


 

[java] view plaincopy
  1. package mine.util.others;  
  2.   
  3. public class TestGetRandom {  
  4.     public static void main(String[] args) {  
  5.         System.out.println("测试随机生成字符:");  
  6.         for (int i = 1; i <= 100; i++) {  
  7.             System.out.print(GetRandom.getRandomChar('A''Z') + "  ");  
  8.             if (i % 10 == 0)  
  9.                 System.out.println();  
  10.         }  
  11.         System.out.println("测试随机生成自然数:");  
  12.         for (int i = 1; i <= 100; i++) {  
  13.             System.out.print(GetRandom.getRandomInt(09) + "  ");  
  14.             if (i % 10 == 0)  
  15.                 System.out.println();  
  16.         }  
  17.     }