我有一个问题需要解决,如下:
Create a method that returns an array that contains only the positive values of another
int[] a
我通过编写这个方法解决了这个问题:
public static int[] soloPositivi(int[] a) {
int[] pos = new int[a.length];
int j=0;
for (int i=0; i<a.length; i++){
if (a[i]>0) {
pos[j] = a[i];
j++;
}
}
return pos;
}
当然,当我使用以下示例进行测试时:
int[] a = new int[] {2,-3,0,7,11};
我得到[2,7,11,0,0]
,因为我设置:
int[] pos = new int[a.length];
问题是,如何让 pos 数组具有模块化长度,以便我可以获得 [2,7,11]
,而不必使用列表?我必须仅使用数组方法来解决这个问题。
最佳答案
首先循环统计正数元素的个数,知道长度,然后再次循环复制。
public static int[] copyPositiveVals(int[] arr) {
int count = 0;
for(int x : arr) {
if (x > 0) count++;
}
int[] arr2 = new int[count];
int i = 0;
for(int x : arr) {
if (x > 0) {
arr2[i] = x;
i++;
}
}
return arr2;
}
关于java - 如何在不知道数组长度的情况下创建数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37762195/