2013-12-12 51 views
0

部分填充数组作为我的节目,我需要建立一个将无论读取并打印阵列的填充槽他们在哪里的方法的一部分的方法。我的意思是,如果数组的长度为10,并且只填充了数组[0]和数组[9],则该方法应该读取整个数组,并且只打印填充的内容而不填充它们之间的零。建立读取并打印在java中

这是该方法将如何看待

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; 

} 

,但它打印整个数组,而不是只是充满槽。 如何让它不打印未填充的阵列插槽?

+0

检查以确保它们不是空的。此外,您不应该覆盖进入您的方法的参数。 –

+0

而不是直接打印,检查数组中的插槽实际上是否先填充,如果是真的,则仅打印 – Dragondraikk

回答

1

你重写通过countOfInts值。

你必须改变你的循环语句,并在此之前,你可以添加一个检查,如果传递的countOfInts是有效的(否则,有一个很大的possibily的ArrayIndexOutOfBoundException在传递一个非法countOfInts值的情况下被抛出)。

if (countOfInts >= 0 && countOfInts <= intList.length) { 
    for (i = 0; i < countofInts; i++) { 
     System.out.print(intList[i] + "\t "); 
    } 
} 
+0

非常感谢。我没有意识到我是一个变量。 – WeekzGod

1

添加此如果条件:

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

现在只打印填写插槽,因为INT的默认值为0。

0

试试这个..!

>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;}