简体   繁体   中英

Building a method that reads and prints partially filled array in java

As part of my program I need to build a method that will read and print only the filled slots of the array no matter where they are. By that I mean if there was an array length ten and only array[0] and array[9] were filled the method should read the entire array and only print whats been filled and not the zeros in between.

This is how the method will look

printArray( intList, countOfInts );

This is the method I've built:

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

 }

It works but it prints the whole array instead of just the slots that are filled. How do I make it not print the slots of the array that aren't filled?

add this if condition:

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

now it only prints the filled slots because the default of int is 0.

You're overriding the passed countOfInts value.

You have to change your loop statement and also, before that, you can add a check if the passed countOfInts is valid (otherwise, there is a great possibily an ArrayIndexOutOfBoundException to be thrown in a case of passing an invalid countOfInts value).

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

Try this..!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM