我试图创建10列和10行数字的两个独立输出。第一个输出使用数字4到7,第二个输出使用数字10到90(例如10,20,30等)。但是随机调用这些数字,而不是按特殊顺序调用。下面是我的Java代码:
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();
while (i <= 100)
{
//number = rand.nextInt(4) + 4;
System.out.printf("%-5d", rand.nextInt(10 *(80) + 10));
if (i % 10 == 0)
{
System.out.println();
}
i++;
}
}
}
我无法弄清楚我缺少的是什么,代码只运行第一个while语句而不是第二个while语句。
答案 0 :(得分:1)
您尚未重新初始化i
,并且在第一个循环之后,它已经等于101
,因此不会输入第二个循环。
正如您对问题的评论中所提到的,for
循环在这里是一个更合适的构造。
此外,在第二个循环中,声明:
rand.nextInt(10 *(80) + 10)
似乎不会做你想要的。你可能需要这样的东西:
rand.nextInt(9) * 10 + 10
答案 1 :(得分:0)
您需要在第二个i
之前重置while
。
答案 2 :(得分:0)
在第二个while循环之前设置i的值。
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;//modified here
while (i <= 100)
{
//number = rand.nextInt(4) + 4;
System.out.printf("%-5d", rand.nextInt(10 *(80) + 10));
if (i % 10 == 0)
{
System.out.println();
}
i++;
}
}
}