我需要这个问题的帮助。我试图让程序在5个句子中显示1-99之间的奇数随机数,每个句子中有20个值。这就是我提出的,它只在每个句子中显示一个值。其余的请帮助我。谢谢
int[] n = new int[20];
int i = 1;
while (i<=5)
{
int x=(int) (Math.random()*100);
x=x*2+1;
while (x<=100)
{
for (int index = 0; index < n.length; index++)
{
n[index] = (int) (Math.random()*100);
}
for (int index = 0; index < n.length; index++)
{
System.out.print(x + " ");
}
System.out.printf();
i++;
break;
}
}
答案 0 :(得分:0)
OP的代码声明它需要奇数,并需要&#34;显示&#34;,我认为只是转储输出。希望这个答案提供指导,而不仅仅是复制/粘贴作为家庭作业问题的解决方案。
public static void main(String[] args)
{
int[] odds = new int[100];
Random rnd = new Random();
for (int i = 0; i < odds.length; ++i) {
int nxt = 0;
while ( (nxt % 2) == 0) {
nxt = rnd.nextInt(99) + 1;
}
odds[i] = nxt;
}
for (int i = 0; i < odds.length; ++i) {
System.out.print(String.format("%2d ", odds[i]));
if ((i + 1) % 20 == 0) {
System.out.println();
}
}
}
示例输出:
73 15 71 15 21 23 63 97 11 11 89 39 75 33 73 53 31 25 43 47
69 87 85 93 39 59 41 19 67 77 55 53 19 29 49 23 93 63 73 41
71 27 15 31 39 99 47 43 85 67 81 75 15 37 55 33 97 73 45 47
37 73 93 89 35 31 29 59 35 61 71 79 15 45 49 11 27 73 23 21
13 71 7 93 31 9 29 77 21 95 91 63 21 83 43 49 61 63 61 1
答案 1 :(得分:0)
使用以下代码更新您的代码:
int[] n = new int[20];
int i = 1;
while (i<=5)
{
int x=(int) (Math.random()*100);
x=x*2+1;
while (x<=100)
{
for (int index = 0; index < n.length; index++)
{
n[index] = (int) (Math.random()*100);
}
for (int index = 0; index < n.length; index++)
{
int x1=(int) (Math.random()*100);
x1=x1*2+1;
System.out.print(x1 + " ");
}
System.out.printf("\n");
i++;
break;
}
}
答案 2 :(得分:0)
你的代码在这里完全被破坏了:
for (int index = 0; index < n.length; index++){
System.out.print(x + " ");
}
你打印的值是你在开头用你计算的值x的20倍
我会做类似的事情:
public static void main(String[] args) {
int[] n = new int[20];
int i = 1;
while (i <= 5) {
for (int index = 0; index < n.length; index++) {
// random number between 0-49 then multiplied by 2 +1 still be
// between 0 and 1-100
n[index] = (int) (new Random().nextInt(49) * 2 + 1);
}
// pretty easy way to print arrays, no loop needed.
System.out.println(Arrays.toString(n));
i++;
}
}