0

I need to create an array that has a random amount of values from 8 to 12, but it says my variable is incompatible. What do I have to change? Should x not be an 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.

Edit: Since we are making the x variable static, how do I use it in the other file? because I need the array values to be random.

1
  • 1
    "it says my variable is incompatible" What is the exact message, and which line of the code does it refer to? Commented Jan 16, 2014 at 16:21

1 Answer 1

2

x is an instance variable. 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). This won't compile because during the static Fish[] myFish = new Fish[x]; there is no any Fish instance.

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.

Here's the official explanation of static variables (officials prefer to call them class variables).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.