import java.util.Arrays;public class HelloWorld {? ? public static void main(String[] args) {? ? HelloWorld hello = new HelloWorld(); int[] nums = hello.getArray(8); System.out.println(Arrays.toString(nums));? } public int[] getArray(int length) { int[] nums = new int[length]; for (int num:nums) { ? ?num = (int)(Math.random()*100); } return nums;? }}為什么答案全是0呢?熱下面這個(gè)就可以了,為什么呢?package rholiday;import java.util.Arrays;import java.util.Arrays;public class HelloWorld {? ? public static void main(String[] args) {? ? ? ??? ? ? ? ?// 創(chuàng)建對(duì)象,對(duì)象名為hello? ? HelloWorld hello = new HelloWorld();? ? ? ??? ? ? ? // 調(diào)用方法并將返回值保存在變量中 int[] nums = hello.getArray(8);? ? ? ??? ? ? ? // 將數(shù)組轉(zhuǎn)換為字符串并輸出 System.out.println(Arrays.toString(nums));? } /* * 功能:創(chuàng)建指定長度的int型數(shù)組,并生成100以內(nèi)隨機(jī)數(shù)為數(shù)組中的每個(gè)元素賦值 * 定義一個(gè)帶參帶返回值的方法,通過參數(shù)傳入數(shù)組的長度,返回賦值后的數(shù)組 */ public int[] getArray(int length) {? ? ? ? // 定義指定長度的整型數(shù)組 int[] nums = new int[length];? ? ? ? int t = 0;? ? ? ? // 循環(huán)遍歷數(shù)組賦值 for (int num:nums) {? ? ? ? ? ?? // 產(chǎn)生一個(gè)100以內(nèi)的隨機(jī)數(shù),并賦值給數(shù)組的每個(gè) ? ?num = (int)(Math.random()*100); ? ?nums[t]=num; ? ?t++;? ? ? ?? } return nums; // 返回賦值后的數(shù)組 }}
添加回答
舉報(bào)
0/150
提交
取消