定義一個帶參帶返回值的方法,實現輸出隨機數數組
阿新 • • 發佈:2017-06-07
public
public class mains {
public static void main(String[] args) {
// 創建對象,對象名為hello
mains hello = new mains();
// 調用方法並將返回值保存在變量中
int[] nums = hello.getArray(8);
// 將數組轉換為字符串並輸出
System.out.println(Arrays.toString(nums));
}
/*
* 功能:創建指定長度的int型數組,並生成100以內隨機數為數組中的每個元素賦值
* 定義一個帶參帶返回值的方法,通過參數傳入數組的長度,返回賦值後的數組
*/
public int[] getArray(int length) {
// 定義指定長度的整型數組
int[] nums = new int[length];
// 循環遍歷數組賦值
for (int i=0; i<nums.length;i++) {
// 產生一個100以內的隨機數,並賦值給數組的每個成員
int a=(int)(Math.random()*100);
nums[i]=a;
}
return nums; // 返回賦值後的數組
}
}
定義一個帶參帶返回值的方法,實現輸出隨機數數組