Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/360.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在java中构建读取和打印部分填充数组的方法_Java_Arrays_Methods_Build - Fatal编程技术网

在java中构建读取和打印部分填充数组的方法

在java中构建读取和打印部分填充数组的方法,java,arrays,methods,build,Java,Arrays,Methods,Build,作为我程序的一部分,我需要构建一个方法,该方法将只读取和打印阵列中已填充的插槽,无论它们位于何处。我的意思是,如果数组长度为10,并且只填充了数组[0]和数组[9],那么该方法应该读取整个数组,只打印填充的内容,而不是中间的零 这就是该方法的外观 printArray( intList, countOfInts ); 这是我建立的方法: static public int printArray( int[] intList, int countofInts) { for (count

作为我程序的一部分,我需要构建一个方法,该方法将只读取和打印阵列中已填充的插槽,无论它们位于何处。我的意思是,如果数组长度为10,并且只填充了数组[0]和数组[9],那么该方法应该读取整个数组,只打印填充的内容,而不是中间的零

这就是该方法的外观

printArray( intList, countOfInts );
这是我建立的方法:

static public int printArray( int[] intList, int countofInts)
 {
    for (countofInts = 0; countofInts < intList.length; countofInts++)
    { 
        System.out.print(intList[countofInts] + "\t ");
    }
    return countofInts;

 }
static public int printary(int[]intList,int countofits)
{
for(countofits=0;countofits
它可以工作,但它会打印整个阵列,而不仅仅是填充的插槽。 如何使其不打印未填充的阵列插槽?

如果条件为:

if(intList[countofInts]!=0)
     System.out.print(intList[countofInts] + "\t ");

现在它只打印填充的插槽,因为int的默认值是0。

您正在覆盖传递的
countofits

if (countOfInts >= 0 && countOfInts <= intList.length) {
   for (i = 0; i < countofInts; i++) { 
       System.out.print(intList[i] + "\t ");
   }
}
必须更改循环语句,在此之前,还可以添加一个检查,检查传递的
countofits
是否有效(否则,在传递无效的
countofits
值的情况下,很可能会抛出
ArrayIndexOutOfBoundException

如果(countofits>=0&&countofits试试这个

>static public int printArray( int[] intList, int countofInts){
for (countofInts = 0; countofInts < intList.length; countofInts++)
{ if(intList[countofInts ]!=0)
    System.out.print(intList[countofInts] + "\t ");
}
return countofInts;}
>静态公共int-printary(int[]intList,int-countofits){
for(countofits=0;countofits
检查以确保它们不是空的。此外,您不应该覆盖进入方法的参数。与其直接打印,不如先检查数组中的某个插槽是否已填充,如果是,则仅打印