[英]Generate 10 Random Integers storing them in an Array and then calling a Method to display the Array
所以我需要在1-20范圍內生成10個隨機整數,但我必須將它們存儲在一個名為數字的數組中。 然后我必須調用一個名為displayArray的方法來顯示數組的內容,對於賦值我必須使用for循環來遍歷數組。
displayArray方法的方法標題是:
public static void displayArray(int[] array)
這就是我所做的
public class RandomIntegers {
static int numbers = 0;
public static void displayArray(int[] array) {
System.out.println(numbers + "Numbers Generated");
}
}//end class
和
public class Random_Integers{
public static void main(String[] args) {
RandomIntegers[] numbers = new RandomIntegers[10];
//Generates 10 Random Numbers in the range 1 -20
for(int i = 0; i < numbers.length; i++) {
numbers[i] = (int)(Math.random() * 20);
RandomIntegers Numbers = new RandomIntegers();
numbers[i] = Numbers;
}//end for loop
for (int i = 0; i < numbers.length; i++) {
numbers Numbers = numbers[i];
Numbers[i].displayArray;
System.out.println();
}//end for loop
}//end main method
}//end class
線條上出現錯誤
類型不匹配無法從int轉換為RnadomIntegers
numbers[i] = (int)(Math.random() * 20);
數字無法解析為某種類型
numbers Numbers = numbers[i];
語法錯誤輸入'AssignmentOperator Expression'以完成表達式
Numbers[i].displayArray;
我意識到我需要將一個RandomIntegers類的實例分配給數組中的插槽來修復第一個問題,但我不知道怎么樣,有人能告訴我怎么做
我不知道如何解決其他2個問題我只是學習如何使用java所以有人可以指導我正確的方向
你只需要使用一個for循環 - 像這樣:
public static void main(String[] args)
{
int[] numbers = new int[10];
//Generates 10 Random Numbers in the range 1 -20
for(int i = 0; i < numbers.length; i++) {
numbers[i] = (int)(Math.random()*20 + 1);
}//end for loop
System.out.println("Numbers Generated: " + Arrays.toString(numbers));
}
要生成隨機整數 ,最好使用它:
Random rand = new Random();
numbers[i] = rand.nextInt(20)+1;
rand.nextInt(20)
調用將給出0到19之間的隨機數,因此添加1會使其從1到20。
實際上,您不需要每次都創建一個新的Random()
; 你放了這個
Random rand = new Random();
在你的循環開始,然后
numbers[i] = rand.nextInt(20)+1;
在里面。
由於你有幾個錯誤,我建議你重新開始,一點一點地寫你的代碼,並在每個階段檢查它編譯並做你想要的。 例如,首先打印一個隨機數,然后檢查它是否有效。
你創建了一個RandomIntegers類型的數組,使用它將工作int[] numbers = new int[10];
代碼沒有問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.