我制作了一个将2D阵列转换为一维阵列的方法,但是我在打印它时遇到了麻烦。在main方法中创建一个新数组或调用该方法存在问题。谁都可以帮忙??
public class flatten {
public static int[] flatten1(int[][] a){
int c=0;
for(int i=0;i<a.length;i++){
for(int j=0;j<a[i].length;j++){
c++;
}
}
int[] x = new int[c];
int k=0;
for(int i=0;i<a.length;i++){
for(int j=0;j<a[i].length;j++){
x[k++]=a[i][j];
}
}
return x;
}
public static void main(String[]args){
flatten1 f = new flatten1({{2,5,3,7,4,8},{3,4,1,2}});
for(int i=0; i<f.length;i++){
System.out.print(f[i]+" ");
}
}
}
答案 0 :(得分:1)
首先你不能这样做:
XYZ
flatten1不是一个类它是一个方法,你不能实例化flatten1并输入一个2D int数组。 对于上面的法律,您需要创建一个名为flatten1的类并创建一个构造函数,该构造函数将2D int数组作为参数,我相信这不是您想要做的。
您的展平方法效果很好,将主要方法更改为以下内容:
flatten1 f = new flatten1({{2,5,3,7,4,8},{3,4,1,2}});
答案 1 :(得分:0)
试试这个:
*Main> f o :: K
<interactive>:2:1:
No instance for (F a0 K) arising from a use of `f'
The type variable `a0' is ambiguous
Possible fix: add a type signature that fixes these type variable(s)
Note: there are several potential instances:
instance F M K -- Defined at hw.hs:28:10
instance F L K -- Defined at hw.hs:22:10
Possible fix: add an instance declaration for (F a0 K)
In the expression: f o :: K
In an equation for `it': it = f o :: K
<interactive>:2:3:
No instance for (O a0) arising from a use of `o'
The type variable `a0' is ambiguous
Possible fix: add a type signature that fixes these type variable(s)
Note: there are several potential instances:
instance O L -- Defined at hw.hs:16:10
instance O K -- Defined at hw.hs:13:10
In the first argument of `f', namely `o'
In the expression: f o :: K
In an equation for `it': it = f o :: K
答案 2 :(得分:0)
在主要方法中,当您打印f [i]时,您不会打印第一个值。由于f是一个数组数组,你试图打印第i个数组而不是第i个元素。确保你理解这种区别,因为它很重要。打印第i个数组只会给你一个内存地址。
要解决此问题,只需将print语句更改为:
System.out.print(Arrays.toString(f[i])+" ");