我想使用扫描仪输入字符串"abcde12345ABCDE"
,然后根据以下要求生成长度为4的随机字符串:
示例运行:
Input
abcde12345ABCDE
\\Processing....
Output
A25b
然后我还希望提示匹配生成的号码。
Plz enter the generated no.!!
A25b
这是我用来生成随机字符串的代码
final String alphanumeric = "abcde12345ABCDE";
final int n = alphanumeric.length();
Random r = new Random();
for(int i = 0; i < 4; i++) {
System.out.println(alphanumeric.charAt(r.nextInt(n)));
}
答案 0 :(得分:0)
public static void main(String[] args) {
final String alphanumeric = "abcde12345ABCDE";
List<Character> digits = getPart(alphanumeric, true);
List<Character> letters = getPart(alphanumeric, false);
Random r = new Random();
System.out.print(letters.get(r.nextInt(letters.size())));
System.out.print(digits.get(r.nextInt(digits.size())));
System.out.print(digits.get(r.nextInt(digits.size())));
System.out.print(letters.get(r.nextInt(letters.size())));
}
public static List<Character> getPart(String src, boolean numbers) {
List<Character> result = new ArrayList<>();
for (int i = 0; i < src.length(); i++) {
if (numbers == Character.isDigit(src.charAt(i))) {
result.add(src.charAt(i));
}
}
return result;
}