[英]Java: Generating a random 3 digit number using a for loop
我需要使用for循环为项目生成一个随机的3位数字,但是完全卡住了。 这就是我所拥有的。
for(int counter = 0; counter < 3; counter++){
randNum = r.nextInt(9 - 9 + 1) + 9;
System.out.println(singleNum1);
}
我知道通常如何使用for循环,而不是生成数字。 每个数字必须分开,然后拼凑在一起。 我将如何去做?
您可以以不同的方式执行此操作,但是这里的主要信息是在开始使用它们进行编码之前,请先检查您正在使用的方法及其工作方式。
如果方法的使用很复杂,请使用简单的算法,然后尝试对其进行优化。
这是一个方法:
Random r = new Random();
String output = "";
for (int i = 0 ; i < 3 ; i++){
output+=r.nextInt(10);
}
int outputInt = Integer.parseInt(output);
这是第二个:
Random r = new Random();
int output = 0;
for (int i = 0 ; i < 3 ; i++){
output+=(r.nextInt(10)*Math.pow(10, i));
}
System.out.println(output);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.