【发布时间】:2021-07-30 21:18:20
【问题描述】:
我有一个 main 方法,它创建一个包含 3 行和随机列数的参差不齐的数组。然后将数组传递给名为 Proj09Runner 的类,以从左到右和从上到下的整数计数值填充数组的元素,从 1 开始,以行长度总和的总和结束。
import java.util.Random;
import java.util.Date;
class Proj09{
public static void main(String[] args){
//Create a pseudo-random number generator
Random generator = null;
if(args.length != 0){
generator = new Random(Long.parseLong(args[0]));
}else{
generator = new Random(new Date().getTime());
};
//Generate some small positive random numbers.
int[] vals = {Math.abs((byte)generator.nextInt())%5+2,
Math.abs((byte)generator.nextInt())%5+2,
Math.abs((byte)generator.nextInt())%5+2};
//Create an empty array object
Object[][] array = new Object[3][];
array[0] = new Object[vals[0]];
array[1] = new Object[vals[1]];
array[2] = new Object[vals[2]];
//Instantiate an object from the student's code.
Proj09Runner obj = new Proj09Runner();
//Pass a reference to the empty array to the run method
// of the object instantiated from the student's code
// where the elements in the array object will be
// populated with increasing Integer values.
obj.run(array);
//Display the data in the populated object.
for(int i=0;i<3;i++){
for(int j=0;j<vals[i];j++){
System.out.print(((Object[])array[i])[j] + " ");
}//end inner loop
System.out.println();//new line
}//end outer loop
//Print some information that must descibe the
// populated object.
System.out.println();//blank line
System.out.println("Row 0 width = " + vals[0]);
System.out.println("Row 1 width = " + vals[1]);
System.out.println("Row 2 width = " + vals[2]);
System.out.println("Final value = " + (vals[0] + vals[1] + vals[2]));
System.out.println("That's all folks.");
}//end main
}//end class Proj09
//End program specifications.
我相信我有正确的代码来填充数组,我只是在将值返回给 main 方法以便打印出值时遇到问题。这是我目前所拥有的。
public Integer run(Object[][] array){
for(int i=0;i<array.length;i++){
for(int j=0;j<array[i].length;j++){
array[i][j] = new Integer((i+1)*(j+1));
return array;
}
}
}
任何帮助将不胜感激。
【问题讨论】:
标签: java arrays jagged-arrays