简体   繁体   English

如何使用随机数量的值创建数组

[英]How to create an array with a random amount of values

I need to create an array that has a random amount of values from 8 to 12, but it says my variable is incompatible. 我需要创建一个具有从8到12的随机值的数组,但它表示我的变量不兼容。 What do I have to change? 我需要改变什么? Should x not be an int? x应该不是int吗?

Here is the first part of the code that includes the problem: 以下是包含问题的代码的第一部分:

public class Fish {

int min = 8;
int max = 12;
int x = min + (int)(Math.random() * ((max-min) + 1));

static Fish[] myFish = new Fish[x];
static int Fcount=0;
private float weight;

public Fish(float w) { weight = w;
  myFish[Fcount] = this;
  Fcount++;
}
public float getWeight( ) { return weight; } }

The second part of my code is: 我的代码的第二部分是:

public class GoFish {
public static void main(String[] args) {

  float[] myWeights;
  for (int i = 0 ; i < x ; i++){ 
     int min = 1;
     int max = 20;
     myWeights[i] = min + (int)(Math.random() * ((max-min) + 1));
  }

  for ( float w : myWeights ) { new Fish(w); }
  for ( Fish f : Fish.myFish ) { 
     System.out.println( f.getWeight() );
  } } }

Could you also explain the problem, because I would like to understand what I'm doing wrong. 你能解释一下这个问题吗,因为我想了解我做错了什么。 I also have to make the weight a random number between 1 and 20, but I can't get this type of random numbers to work. 我还必须将权重设为1到20之间的随机数,但我无法使用这种类型的随机数。

Edit: Since we are making the x variable static, how do I use it in the other file? 编辑:由于我们将x变量设为静态,如何在其他文件中使用它? because I need the array values to be random. 因为我需要数组值是随机的。

x is an instance variable. x是一个实例变量。 You're trying to access ( javac compiler would say "reference") instance variable ( javac would say "non-static variable") from a static context ( javac would say the same thing). 你试图从静态上下文访问( javac编译器会说“引用”)实例变量( javac会说“非静态变量”)( javac会说同样的事情)。 This won't compile because during the static Fish[] myFish = new Fish[x]; 这将无法编译,因为在static Fish[] myFish = new Fish[x]; there is no any Fish instance. 没有任何Fish实例。

You can change your code to: 您可以将代码更改为:

static int min = 8;
static int max = 12;
static int x = min + (int)(Math.random() * ((max-min) + 1));

This will make non-static variable x static. 这将使非静态变量x静态。

Here's the official explanation of static variables (officials prefer to call them class variables). 是静态变量的官方解释(官员更喜欢称它们为类变量)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM