这是代码:
import java.lang.System;
import java.lang.Math;
public class ArrayFunHouseTwo
{
public static int[] getCountValuesBiggerThanX(int[] numArray, int count, int x)
{
int[] newNumArray = new int[0];
//int num = 0;
int cnt = 0;
int z = 0;
for(int y = 0; y < numArray.length; y++){
if(numArray[y] > x && z < count){
newNumArray = new int[count];
newNumArray[z] = numArray[y];
z++;
}
}
//}
return newNumArray;
}
}
并且它是关联的跑步者类:
import java.util.Arrays;
public class Lab14b
{
public static void main( String args[] )
{
int[] one = {1,2,3,4,5,6,7,8,9,10};
int[] two = {1,2,3,9,11,20,30};
//add more test cases
int[] three = {9,8,7,6,5,4,3,2,0,-2};
int[] four = {3,6,9,12,15,18,21,23,19,17,15,13,11,10,9,6,3,2,1,0};
System.out.println(Arrays.toString(four));
System.out.println("first 7 values greater than 9 " + ArrayFunHouseTwo.getCountValuesBiggerThanX(four, 7, 9));
System.out.println("first 5 values greater than 15 " + ArrayFunHouseTwo.getCountValuesBiggerThanX(four, 5, 15));
}
}
正如我上面所说,它正在输出位置,我认为它就是它,而不是数组本身。
即。我得到了:前7个值大于9 [I @ 38f0b51d
前5个值大于15 [I @ 4302a01f
而不是前7个值大于9 [12,15,18,21,23,19,17]
前5个值大于15 [18,21,23,19,17]
更新
好的,现在我得到了:前7个值大于9 [0,0,0,0,0,0,17]
前5个值大于15 [0,0,0,0,17]
答案 0 :(得分:2)
您希望在构建字符串时调用此方法:
Arrays.toString(array);
将对象添加到String时,将调用其toString()方法 可悲的是,对于数组来说,这会打印出你看到的垃圾(它实际上并不是垃圾,但实际上是有用的)
将您的代码更改为:
System.out.println("first 5 values greater than 15 " +
Arrays.toString(ArrayFunHouseTwo.getCountValuesBiggerThanX(four, 5, 15)));
答案 1 :(得分:2)
将函数的返回值转换为Arrays.toString
System.out.println("first 7 values greater than 9 " + Arrays.toString(ArrayFunHouseTwo.getCountValuesBiggerThanX(four, 7, 9)));
System.out.println("first 5 values greater than 15 " + Arrays.toString(ArrayFunHouseTwo.getCountValuesBiggerThanX(four, 5, 15)));
关于你的新问题,你不想在循环中如此深入newNumArray = new int[count];
,每次都会被覆盖。
我的java很生疏,但也许您可以在第一行中将newNumArray
设置为null
,并且只有在null
时才在循环内重新创建它。或者直接将其改为最终尺寸..取决于您想要输出的内容。