[英]How to make a function that counts the amount of equal values (in random position) inside a 2d array?
[英]How to create an array with a random amount of values
我需要創建一個具有從8到12的隨機值的數組,但它表示我的變量不兼容。 我需要改變什么? x應該不是int嗎?
以下是包含問題的代碼的第一部分:
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; } }
我的代碼的第二部分是:
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() );
} } }
你能解釋一下這個問題嗎,因為我想了解我做錯了什么。 我還必須將權重設為1到20之間的隨機數,但我無法使用這種類型的隨機數。
編輯:由於我們將x變量設為靜態,如何在其他文件中使用它? 因為我需要數組值是隨機的。
x
是一個實例變量。 你試圖從靜態上下文訪問( javac
編譯器會說“引用”)實例變量( javac
會說“非靜態變量”)( javac
會說同樣的事情)。 這將無法編譯,因為在static Fish[] myFish = new Fish[x];
沒有任何Fish
實例。
您可以將代碼更改為:
static int min = 8;
static int max = 12;
static int x = min + (int)(Math.random() * ((max-min) + 1));
這將使非靜態變量x
靜態。
這是靜態變量的官方解釋(官員更喜歡稱它們為類變量)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.