一、擷取數字中的每一位
int i = 58713;
個位 : i % 10;
十位 : i / 10 % 10;
百位 : i / 10 / 10 % 10;
千位 : i / 1000 % 10;
萬位 : i / 10000 % 10;
二、元素值使用随機數生成(範圍為i~j)
Random r = new Random();
int num = r.nextInt(j - i + 1) + i;
原理 :
r.nextInt(num)
會生成0~num-1的随機數. 那麼可以先生成i~j範圍内的值,在依次往後移i個即可.
随機擷取小寫字母
Random r = new Random();
char c = (char) (r.nextInt('z' - 'a' + 1) + 'a');
案例 : 随機擷取5個大小寫字母
public class CharRandom{
public static void main(String[] args) {
String str = getStr();
System.out.println(str);
}
private static String getStr() {
char[] chs = new char[5];
Random r = new Random();
for (int i = 0; i < chs.length; i++) {
chs[i] = (char)(r.nextInt('z' - 'a' + 1) + 'a');
}
int bound = r.nextInt(chs.length);
for (int i = 0; i < bound; i++) {
int j = r.nextInt(chs.length);
chs[j] = (char) (r.nextInt('Z' - 'A' + 1) + 'A');
}
return new String(chs);
}
}