编写一个将2D数组作为参数的方法。该数组返回一个新的2D数组 相同大小的整数(相同的行数和列数)。返回的数组中的值是相同的 作为参数数组中的那些,除了任何负值都是正数。
我的方法不会编译编译器一直在抱怨我的方法是非法启动表达式。它似乎没有认识到我曾经写过一个方法。
这就是我所做的:
public class Examprep1
{
public static void main (String[] args)
{
int [][] array = new int[2][4];
array[0][0]=1;
array[0][1]=5;
array[0][2]=-7;
array[0][3]=9;
array[1][0]=-2;
array[1][1]=4;
array[1][2]=6;
array[1][3]=-8;
int x;
// Using for loops to create the 2D array
for (int rows=0; rows<2; rows++)
{
for (int cols=0; cols<4;cols++)
{
System.out.print( array[rows][cols]+ " ");
}
System.out.println("");
}
System.out.println(newArray(array));
private static int[][] newArray(int[][] old)
{
int y;
int[][] current = new int [2][4];
for (int rows=0; rows<2; rows++)
{
for (int cols=0; cols<4;cols++)
{
if (old[rows][cols]<0)
{
y=Math.abs(old[rows][cols]);
old[rows][cols] = (int)Math.pow(old[rows][cols],2)/x;
}
old[rows][cols] = current[rows][cols];
}
}
return current;
}
}
}
答案 0 :(得分:0)
您的实施似乎过于复杂。您可以在一行中声明和初始化2D数组。您还可以使用Arrays.deepToString(Object[])
打印2D阵列。像,
public static void main(String[] args) {
int[][] array = { { 1, 5, -7, 9 }, { -2, 4, 6, -8 } };
System.out.println(Arrays.deepToString(array));
System.out.println(Arrays.deepToString(newArray(array)));
} //<-- remember to close main.
然后,您可以使用Object.clone()
复制old
数组。迭代数组,并将当前值设置为Math.abs(int)
。像,
private static int[][] newArray(int[][] old) {
int[][] current = old.clone();
for (int i = 0; i < current.length; i++) {
for (int j = 0; j < current[i].length; j++) {
current[i][j] = Math.abs(current[i][j]);
}
}
return current;
}
哪个输出
[[1, 5, -7, 9], [-2, 4, 6, -8]]
[[1, 5, 7, 9], [2, 4, 6, 8]]