Java 要生成随机输出:从901到999的100个数字
我试图创建两个独立的10列10行数字输出。我知道我可以使用数字4到7进行第一次输出,使用数字10到90进行第二次输出。但是我在使用901到999的数字进行第三次输出时遇到了麻烦。下面是我的Java代码:Java 要生成随机输出:从901到999的100个数字,java,random,Java,Random,我试图创建两个独立的10列10行数字输出。我知道我可以使用数字4到7进行第一次输出,使用数字10到90进行第二次输出。但是我在使用901到999的数字进行第三次输出时遇到了麻烦。下面是我的Java代码: import java.util.Random; public class LabRandom { private static final Random rand = new Random(); public static void main(String[] args) {
import java.util.Random;
public class LabRandom
{
private static final Random rand = new Random();
public static void main(String[] args)
{
int number;
int i = 1;
while (i <= 100)
{
//number = rand.nextInt(4) + 4;
System.out.printf("%-5d", rand.nextInt(4) + 4);
if (i % 10 == 0)
{
System.out.println();
}
i++;
}
System.out.println();
i = 1;
while (i <= 100)
{
//number = rand.nextInt(4) + 4;
System.out.printf("%-5d", rand.nextInt(9)*10+10);
if (i % 10 == 0)
{
System.out.println();
}
i++;
}
System.out.println();
i = 1;
while (i <= 100)
{
//number = rand.nextInt(4) + 4;
System.out.printf("%-5d", rand.nextInt(100)*10);
if (i % 10 == 0)
{
System.out.println();
}
i++;
}
}
}
import java.util.Random;
公共类LabRandom
{
私有静态最终随机兰德=新随机();
公共静态void main(字符串[]args)
{
整数;
int i=1;
(i我无法理解您想要什么。如果您想创建一个900到999范围内随机选择的100个数字的输出,并且每10个数字后有换行符,请尝试将此循环添加到您的代码中:
i = 1;
while (i <= 100)
{
// generate a random number from 0 to 100-1,
// then add 900 to transform the range to 900 to 999
System.out.printf("%-5d", rand.nextInt(100) + 900);
if (i % 10 == 0)
{
System.out.println();
}
i++;
}
i=1;
顺便说一句,如果你真的想打印数字10到90,你的第二个循环是不正确的。
现在打印10的倍数,从10到90,例如10,20,30….90
对于介于之间的每个数字,您都希望:
耐克斯汀兰德(80)+10
您可能想了解nextInt(value)的具体功能(在适当的IDE中很容易做到,因为它将提供JavaDoc工具提示,这当然在一般Java类中是可用的,并且非常详细)。您的问题是什么?如果您想要901到999,那么您的nextInt应该是99,而不是100。(当然,你需要加901,而不是乘以10。)
// difference between the highest and the lowest value you want to have in your result
int range = 99;
// the lowest possible value you want to see in your result
int lowestValue = 901;
//note that you will never get the numbers 900 and 1000 this way, only between
int result = rand.nextInt(range) + lowestValue;