當前位置:成語大全網 - 新華字典 - java隨機生成20個長度為12-20的大小寫字母混雜的“單詞”,按字典順序進行輸出

java隨機生成20個長度為12-20的大小寫字母混雜的“單詞”,按字典順序進行輸出

字母的字典順序:大寫字母小於小寫字母

'A'~ 'Z'對應ASCII值:65~90?

'a'~'z'對應ASCII值:97~122

程序運行截圖:

1隨機生成壹個長度為12-20的大小寫字母混雜的“單詞”

/**

?*?隨機獲取長度為12~20的大小寫字母混雜的“單詞”

?*/

private?String?randomWord()?{

//?12~20長度,包含12及20

int?length?=?12?+?(int)?(Math.random()?*?9);

String?word?=?"";

for?(int?i?=?0;?i?<?length;?i++)?{

word?+=?(char)?randomChar();

}

return?word;

}

/**

?*?隨機獲取'a'~'z'?和?'A'~?'Z'中的任壹字符

?*?

?*?'A'~?'Z'對應ASCII值:65~90

?*?

?*?'a'~'z'對應ASCII值:97~122

?*?

?*?@return

?*/

private?byte?randomChar()?{

//?0<=?Math.random()<?1

int?flag?=?(int)?(Math.random()?*?2);//?0小寫字母1大寫字母

byte?resultBt;

if?(flag?==?0)?{

byte?bt?=?(byte)?(Math.random()?*?26);//?0?<=?bt?<?26

resultBt?=?(byte)?(65?+?bt);

}?else?{

byte?bt?=?(byte)?(Math.random()?*?26);//?0?<=?bt?<?26

resultBt?=?(byte)?(97?+?bt);

}

return?resultBt;

}

2.for循環生成20個長度為12-20的大小寫字母混雜的“單詞”

3.按字典順序進行排序

/**

*?

*?由小到大排序

*?

*?從後向前冒泡

*?

*?@param?arr

*/

public?void?bubbleSort(String[]?arr)?{

if?(arr?==?null?||?arr.length?==?0)

return;

for?(int?i?=?0;?i?<?arr.length?-?1;?i++)?{

//?循環之後下標i處為數組中最小的元素

for?(int?j?=?arr.length?-?1;?j?>?i;?j--)?{

if?(!compareString(arr[j],?arr[j?-?1]))?{

swap(arr,?j?-?1,?j);

}

}

}

}

/**

*?比較兩個字符串大小

*?

*?@param?param1

*?@param?param2

*?@return?true:param1?>?param2?false:param1?<=?param2;

*/

private?boolean?compareString(String?param1,?String?param2)?{

char[]?paramC1?=?param1.toCharArray();

char[]?paramC2?=?param2.toCharArray();

//?獲取最短字符串長度

int?minLength?=?paramC1.length?<?paramC2.lengthparamC1.length

:?paramC2.length;

for?(int?i?=?0;?i?<?minLength;?i++)?{

if?(paramC1[i]?==?paramC2[i])?{

}?else?if?(paramC1[i]?>?paramC2[i])?{

return?true;

}?else?{

return?false;

}

}

return?paramC1.length?>?paramC2.length;

}

/**

*?交換元素

*?

*?@param?arr數組

*?@param?i

*數組下標

*?@param?j

*數組下標

*/

public?void?swap(String[]?arr,?int?i,?int?j)?{

String?temp?=?arr[i];

arr[i]?=?arr[j];

arr[j]?=?temp;

}

4.測試類

public?class?StringDemo?{

public?static?void?main(String[]?args)?{

StringDemo?localDemo?=?new?StringDemo();

String[]?words?=?new?String[20];

System.out.println("隨機生成的20個單詞:");

for?(int?i?=?0;?i?<?words.length;?i++)?{

words[i]?=?localDemo.randomWord();

System.out.println(words[i]);

}

localDemo.bubbleSort(words);

System.out.println();

System.out.println("按字典順序打印:");

for?(String?word?:?words)?{

System.out.println(word);

}

}

}