2017年9月11日 星期一

Java 取亂數 A-Z / a-z

先前筆記過在 java 中用 Math.random() 實作一個亂數 (數字)。
今天來搞一個 A-Z / a-z 的字母亂數。


這次來玩 Random r = new Random(),其實兩者可以混用,參考下 code 就知道要怎麼用了。
在 ASCII 中, 65 - 90 是代表大寫字母 (A - Z),97 - 122 是代表小寫字母 ( a - z )。
知道這原理,就很容易做出來了。

Random r = new Random();

int upCase = r.nextInt(26)+65;  //得到 65 - 90 的隨機數
String up = String.valueOf((char)upCase);  // 得到A-Z

int downCase = r.nextInt(26)+97;  // 得到 97 - 122 的隨機數
String down = String.valueOf((char)downCase);  // 得到a-z

以上,科科。


0 意見:

張貼留言