问题描述
我有一个 main 方法,它创建一个包含 3 行和随机列数的参差不齐的数组。然后将该数组传递给名为 Proj09Runner 的类,以从左到右和从上到下以 1 开始到行长度总和结束用整数计数值填充数组元素。>
get "/articles/index",to: "articles#index"
get "/articles/new",to: "articles#new"
get "/articles/show",to: "articles#show"
我相信我有正确的代码来填充数组,我只是在将值返回到 main 方法以便打印出值时遇到问题。这是我目前所拥有的。
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.
任何帮助将不胜感激。
解决方法
问题是您的 run
方法在仅设置第一行第一列的值后返回得太早。它还试图返回它不需要的 array
。
实际上我认为它根本不需要返回值,因为它只是用值填充数组。将返回类型从 Integer
更改为 void
并删除您获得的早期 return
语句:
public void 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));
}
}
}
编辑:如果您需要用连续值填充数组,您可以在外部 for
循环中创建一个变量,初始化为 1,并在内部 {{ 1}} 循环:
for
或者,如果您想保持 for(int i=0,k=1;i<array.length;i++){
for(int j=0;j<array[i].length;j++,k++){
array[i][j] = new Integer(k);
}
}
循环简单,您也可以这样做:
for