[英]Random character and number generator doesn't work in the way I want
import java.util.Random;
public class Test {
public static void main(String[] args) {
randomIDGenerator();
}
public static String randomIDGenerator() {
Random r = new Random();
char a = 0;
for (int i = 0; i < 3; i++) {
a = (char) (r.nextInt(26) + 'a');
}
int b = 0;
for (int j = 0; j < 2; j++) {
b = r.nextInt(10);
}
String h = "" + b;
String n = a + h;
System.out.println(n);
return n;
}
}
I am writing a code in Java and I want my output to be 3 characters from a to z and 2 numbers from 0 to 9 (eg abc01) but the program gives me 1 character and 1 number (eg a1). 我正在用Java编写代码,我希望输出的结果是a到z的3个字符和0到9的2个数字(例如abc01),但是程序给了我1个字符和1个数字(例如a1)。 Why does the program do this despite I've put 3 and 2 into loops? 尽管我将3和2放入了循环,但是为什么程序仍要这样做呢? From all I know the first loop must operate 3 times and the second one must operate 2 times. 据我所知,第一个循环必须运行3次,第二个循环必须运行2次。 So at the end my output have to be 3 characters and 2 numbers. 所以最后我的输出必须是3个字符和2个数字。 Thanks! 谢谢!
char
and int
can store one value so use String
as char
和int
可以存储一个值,因此使用String
作为
String a = "";
for (int i = 0; i < 3; i++) {
a += (char) (r.nextInt(26) + 'a');
}
for (int j = 0; j < 2; j++) {
a += r.nextInt(10);
}
return a;
You generate your random items correctly, but you do not collect the results in a proper way. 您正确生成您的随机项目,但是您没有以正确的方式收集结果。 Each iteration of the loop writes over the results of prior iteration, leaving both a
and b
with the result of the last iteration. 循环的每次迭代都会覆盖先前迭代的结果,而a
和b
都保留上一次迭代的结果。
I recommend using a StringBuilder
to store characters as you generate them: 我建议使用StringBuilder
在生成字符时存储它们:
Random r = new Random();
StringBuilder res = new StringBuilder();
for (int i = 0; i < 3; i++) {
res.append((char)(r.nextInt(26) + 'a'));
}
for (int j = 0; j < 2; j++) {
res.append(r.nextInt(10)); // You could use the same trick with '0'
}
System.out.println(res);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.