得到指定位数的随机数和随机字母

来源:互联网 发布:软件测试面试题 编辑:程序博客网 时间:2024/05/22 15:38
package com.cr.service;public class Random {/** * 得到指定位数的 随机数整数 * @param length * @return */public static String getIntRandom(int length) { // 纯数字int[] array = new int[length];StringBuilder str = new StringBuilder();for (int i = 0; i < length; i++) {array[i] = (int) (Math.random() * 10);str.append(array[i]);}return str.toString();}/** * 得到指定位数的 随机字母 * @param length * @return */public static String getCharRandom(int length) { // 纯字母int[] array = new int[length];char[] chars = new char[length];StringBuilder str = new StringBuilder();for (int i = 0; i < length; i++) {while (true) {array[i] = (int) (Math.random() * 200);if ((array[i] > 64 && array[i] < 91)|| (array[i] > 96 && array[i] < 123))break;}chars[i] = (char) array[i];str.append(chars[i]);}return str.toString();}/** * 得到指定位数的 随机字母加数字 * @param length * @return */public  static String getMixRandom(int length) { // 字母数字混合int[] array = new int[length];char[] chars = new char[length];StringBuffer str = new StringBuffer();int temp = 0;for (int i = 0; i < length; i++) {while (true) {temp = (int) (Math.random() * 1000);if ((temp > 47 && temp < 58) || (temp > 64 && temp < 91)|| (temp > 96 && temp < 123)) {break;}}array[i] = temp;chars[i] = (char) array[i];str.append(chars[i]);}return str.toString();}public static void main(String[] args) {System.out.println(getCharRandom(2));}}

0 0
原创粉丝点击