首页 > 学院 > 开发设计 > 正文

工具类:获得随机字母和数字的组合(字母+数字组合,字母组合,数字组合)

2019-11-15 00:34:37
字体:
来源:转载
供稿:网友
工具类:获得随机字母和数字的组合(字母+数字组合,字母组合,数字组合)
package util;import java.util.Random;/** *  * @author jkfeng * 获得随机字母和数字的组合(字母+数字组合,字母组合,数字组合) * */public class RandomCharOrNumUtil {public static void main(String[] args) {System.out.PRintln(getCharAndNum(6));System.out.println(getChar(6));System.out.println(getNum(6));}/** * 获得随机子母和数字的组合 * @param length * @return 随机字母和数字的组合 */public static String getCharAndNum(int length) {String val = "";Random random = new Random();String charOrNum = "";for (int i = 0; i < length; i++) {if (i == 0) {charOrNum = "char";}else if (i == (length-1)) {charOrNum = "num";}else {charOrNum = (random.nextInt(2)%2 == 0) ? "char":"num";}if ("num".equalsIgnoreCase(charOrNum)) {//如何获得 0-9之间的数字int num = random.nextInt(10);if (num == 0) {num = 2;}if (num == 1) {num = 5;}val += String.valueOf(num);}else {//如何获得随机的字符//97 - 122   0-25char char1  = (char)(97+random.nextInt(26));if (char1 == 'o') {char1 = 'm';}val += String.valueOf(char1);}}val = val.toUpperCase();return val; }/** * 获得随机字母组合 * @param length * @return 随机字母组合 */public static String getChar(int length) {String val = "";Random random = new Random();for (int i = 0; i < length; i++) {//如何获得随机的字符//97 - 122   0-25char char1  = (char)(97+random.nextInt(26));val += String.valueOf(char1);}val = val.toUpperCase();return val; }/** * 获得随机数字组合 * @param length * @return 随机数字组合 */public static String getNum(int length) {String val = "";Random random = new Random();for (int i = 0; i < length; i++) {//如何获得 0-9之间的数字int num  = random.nextInt(10);val += String.valueOf(num);}val = val.toUpperCase();return val; }}  

  


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表