java生成指定的隨機數並且包含大寫、小寫和數字,滿足以上條件的返回字串
阿新 • • 發佈:2019-01-08
以下的類完成的是產生隨機數,並且在指定的長度裡包括大寫字母、小寫字母、數字,滿足條件的則將輸出該隨機數。
public class RandomClass {
/**** 產生隨機數的方法
* @param length
* @return
*/
public static String getCharAndNumr(int length)
{ if(length>=3){
String val = "";
Random random = new Random();
//t0、t1、t2用來標識大小寫和數字是否在產生的隨機數中出現
int t0 = 0;
int t1 = 0;
int t2 = 0;
{
String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num"; // 輸出字母還是數字
//產生的是字母
if("char".equalsIgnoreCase(charOrNum)) // 字串
{
// int choice = random.nextInt(2) % 2 == 0 ? 65 : 97; //取得大寫字母還是小寫字母
int choice = 0;
if(random.nextInt(2) % 2 == 0){
choice = 65;
t0 = 1;
}
else{
choice = 97;
t1 = 1;
}
val += (char) (choice + random.nextInt(26));
}
//產生的是數字
else if("num".equalsIgnoreCase(charOrNum)) // 數字
{
val += String.valueOf(random.nextInt(10));
t2 =1;
}
//用於判斷是是否包括大寫字母、小寫字母、數字}else{
if(t0==0 || t1==0 || t2==0) {
val = getCharAndNumr(length); //不滿足則遞迴呼叫該方法
return val;
}else return val;
return null;}
}
/***
* 用來處理長度不符合要求的情況
* @param rcs
* @return
*/
public static String tt(String rcs){
int lenth = 0;
java.util.Scanner sc = new java.util.Scanner(System.in);
String val = null;
if(rcs == null){
System.out.println("重新輸入字串的長度,輸入的長度要大於3");
lenth = sc.nextInt();
rcs = getCharAndNumr(lenth); //呼叫隨機數的方法
val = tt(rcs); //遞迴呼叫字元是否符合要求
}
else{
val = rcs;
}
return val;
/****
* 主函式方法
* @param args
*/
public static void main(String[] args){
java.util.Scanner sc = new java.util.Scanner(System.in);
System.out.println("請輸入字串的長度");
int lenth = sc.nextInt(); //輸入字串的長度
String rcs = getCharAndNumr(lenth); //呼叫隨機數的方法
String val = tt(rcs); //得到隨機數
System.out.println("隨機數:"+val);
}
路過時發現文章有改進的地方,請隨時留言。。。。