我正在学习java,并且我还处于非常初级的水平。我的问题是:创建3个随机数并将其放入一个数组中。此数组中的索引不应包含6和4。然后使用foreach循环显示数组的输出。我从昨晚开始尝试,但无法得到解决方案。请帮我解决这个问题。下面是我的代码:
发布于 2018-07-23 00:58:33
下面是一个示例,它可以为您提供所需的输出:
int[] nums = new int[3];
for(int x = 0; x < nums.length; x++) {
int num = (int) (Math.random() * 10 + 1);
if(num == 6 | num == 4) {
x--;
continue;
}
else
nums[x] = num;
System.out.println(Arrays.toString(nums));
}
我们在这里可以做的是,每次在循环中创建一个新的随机数。如果数字是6或4,我们将激活一个continue语句,以便重新开始循环,我们还将从x中减去-1,这样循环就不会再次开始。如果生成的随机数不是6或4,我们将把这个数字存储在数组中,并用一个索引与我们所在的迭代相对应。每次通过循环,我们都可以打印更新后的数组。如果您想先创建随机数:
int x = 0;
int y = 0;
int z = 0;
int count = 0;
boolean isRunnin = true;
while(isRunnin) {
int num = (int) (Math.random() * 10 + 1);
if(num == 6 | num == 4) {
continue;
}
else {
if(count == 0) {
x = num;
}
else if(count == 1) {
y = num;
}
else if(count == 2) {
z = num;
}
}
count++;
if(count > 2) {
isRunnin = false;
}
}
System.out.println(x);
System.out.println(y);
System.out.println(z);
这将生成三个随机数,然后您可以将这些数放在一个for循环的数组中。
发布于 2018-07-23 03:46:35
下面应该行得通
public static void main(String[] args)
{
firstThreeDigits() ;
}
public static void firstThreeDigits()
{
Random randomNumber= new Random();
int[] firstArray= new int[3];
for (int i = 0,j=0; ;j++) //i for array index and j for running loop until we get 3 numbers which are not 4 or 6
{
int number=randomNumber.nextInt(10);
if(!(number==4||number==6)) //if random number is NOT 4 or 6
{
firstArray[i]=number; // add to array
i++;
if(i==3) // print three number from array and break the loop
{
for(int num:firstArray)
{
System.out.println(num);
}
break;
}
}
}
}
发布于 2018-07-22 16:38:49
编译错误是由于将int[] value
传递给firstThreeDigit()
方法造成的。删除int[] value
虽然可以解决编译问题,但在这种情况下,您的代码可能会反复运行多次来解决单个问题。
这可能就是您想要实现的目标。试着用下面的方法重构你的代码。
public static void main(String[] args){
firstThreeDigit();
}
public static void firstThreeDigit(){
Random rand = new Random();
int[] firstArray = new int[3];
int count = 0;
while(count < 3) {
int randomNumber = rand.nextInt(10);
if (randomNumber != 4 && randomNumber != 6) {
firstArray[count] = randomNumber;
count++;
}
}
for(int i : firstArray){
System.out.println(i);
}
}
https://stackoverflow.com/questions/51463278
复制相似问题