[英]Why doesn't my number record and print in my array?
Ok so I'm trying to make a pretty simple number generator with limits of 1 and 100. I've read over everything I can find online and can't figure out why my code doesn't record the numbers between 1-100 in the array then print the numbers from the array. 好的,所以我试图制作一个非常简单的数字生成器,其限制为1和100。我已经阅读了所有可以在网上找到的内容,无法弄清楚为什么我的代码没有记录1到100之间的数字。然后,数组将打印数组中的数字。 When I run the code the number 36 gets printed over and over. 当我运行代码时,数字36一遍又一遍地打印出来。 What am I doing wrong? 我究竟做错了什么?
import java.util.Random;
public class NumberGen
{
public static void main(String[] args)
{
int numbers[]=new int[10];
Random gen = new Random();
for(int i=0; i<numbers.length;i++)
{
int number=gen.nextInt();
while(number<1 || number>100)
{
number=gen.nextInt();
}
while(number<=100 && number >=1)
{
numbers[i]=number;
System.out.println(numbers[i]);
}
}
}
}
Shouldn't the second while be an if? 第二个难道不是吗? I'm pretty sure it's an infinite loop. 我很确定这是一个无限循环。 And why are you using the first while, well all of: 以及为什么要使用头一段时间?
int number=gen.nextInt();
while(number<1 || number>100)
{
number=gen.nextInt();
}
when you could just int number=gen.nextInt(100)+1; 当你可以int number = gen.nextInt(100)+1;
You should use another flavor of nextInt
-> http://docs.oracle.com/javase/7/docs/api/java/util/Random.html#nextInt(int) 您应该使用nextInt
另一种形式-> http://docs.oracle.com/javase/7/docs/api/java/util/Random.html#nextInt(int)
In your case: 在您的情况下:
int number=gen.nextInt( 100 ) + 1;
Consider what is happening here: 考虑一下这里发生了什么:
for(int i=0; i<numbers.length;i++)
{
/**
*int number=gen.nextInt();
*while(number<1 || number>100)
*{
* number=gen.nextInt();
*}
**/
number = 1;
while(number<=100 && number >=1)
{
numbers[i]=number;
System.out.println(numbers[i]);
}
}
The while in the for loop is stuck in an infinite loop since 'number' never changes for循环中的while卡在无限循环中,因为'number'永不改变
What you should be trying to do is store the number in a single for/while loop then print in a seperate for/while loop 您应该尝试将数字存储在单个for / while循环中,然后在单独的for / while循环中打印
for(int i=0; i<numbers.length;i++){
//FYI gen.nextInt(100) generates a int from 0 to 99
//store values
}
for(int i=0; i<numbers.length;i++){
//print values in arr
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.