这是我的代码,我试图随机添加元素。
有没有办法使用while
循环,for
循环或Java中的每个循环添加元素?
package arrays_into_2d_array;
import java.util.*;
public class Arrays2DArray {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Random random = new Random();
int [] arr1 = new int[50];
for(int i = 0; i < arr1.length; i++){
arr1[i] = 1+random.nextInt(5);
}
int [] arr2 = new int[100];
for(int i = 0; i < arr2.length; i++){
arr2[i] = 1+random.nextInt(5);
}
int [] arr3 = new int[200];
for(int i = 0; i < arr3.length; i++){
arr3[i] = 1+random.nextInt(5);
}
int [] arr4 = new int[400];
for(int i = 0; i < arr4.length; i++){
arr4[i] = 1+random.nextInt(5);
}
int [] arr5 = new int[800];
for(int i = 0; i < arr5.length; i++){
arr5[i] = 1+random.nextInt(5);
}
int [] arr6 = new int[1600];
for(int i = 0; i < arr6.length; i++){
arr6[i] = 1+random.nextInt(5);
}
int [] arr7 = new int[3200];
for(int i = 0; i < arr7.length; i++){
arr7[i] = 1+random.nextInt(5);
}
int [] arr8 = new int[6400];
for(int i = 0; i < arr8.length; i++){
arr8[i] = 1+random.nextInt(5);
}
int [] arr9 = new int[12800];
for(int i = 0; i < arr9.length; i++){
arr9[i] = 1+random.nextInt(5);
}
int [] arr10 = new int[25600];
for(int i = 0; i < arr10.length; i++){
arr10[i] = 1+random.nextInt(5);
}
int [][] arr2D = {arr1, arr2, arr3, arr4, arr5, arr6, arr7, arr8, arr9, arr10};
for(int i = 0; i < arr2D.length; i++){
System.out.println("Index = "+i+" of 2D array has = "+arr2D[i].length+" number of elements.");
}
}
}
任何帮助将不胜感激。
答案 0 :(得分:2)
您编写的代码太多,几乎相同,因此您应该使用循环。
package arrays_into_2d_array;
import java.util.*;
public class Arrays2DArray {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Random random = new Random();
int [] sizes = {50, 100, 200, 400, 800, 1600, 3200, 6400, 12800, 25600};
int [][] arr2D = new int[sizes.length][];
for(int i = 0; i < arr2D.length; i++){
arr2D[i] = new int[sizes[i]];
for(int j = 0; j < arr2D[i].length; j++){
arr2D[i][j] = 1+random.nextInt(5);
}
}
for(int i = 0; i < arr2D.length; i++){
System.out.println("Index = "+i+" of 2D array has = "+arr2D[i].length+" number of elements.");
}
}
}
答案 1 :(得分:0)
当然。您正在寻找的是一种方法。
您将声明一个接受int[]
和Random
实例并执行循环的方法:
public static void assignRandomValues(int[] array, Random random)
{
for (int i = 0; i < array.length; i++)
{
array[i] = 1 + random.nextInt(5);
}
}
然后你会把你的代码变成这个:
int[] arr1 = new int[50];
assignRandomValues(arr1, random);
......等等。
答案 2 :(得分:0)
Not exactly a loop, but the java 8 version using the stream API is definetly short:
int[][] arr2D = IntStream.range(0, 10).map(i -> 50 << i) // stream of sizes
.mapToObj(size -> IntStream.generate(() -> random.nextInt(5) + 1).limit(size).toArray()) // stream of arrays with given sizes
.toArray(int[][]::new); // combine arrays