There is a great deal of information out there on printing arrays in toString() but most suggest using Arrays.toString(arr); This however prints the whole array even the nulls and is formatted a specific way. I'm looking for a way to print the values in an array that are not null and to be able format it the way I want.

Example output.

Backyard is populated by:
Doug
Steve
Dog


I understand that my Backyard is another class. I'm just unsure of how to get output like that. Because I only used three spaces of the array and that means there are 7 spaces that are null that I do not want it to print.

If you need me to clarify something let me know. This is kind of confusing.

Thanks.

I'm not 100% sure what you are asking, but if you loop through your array, can you not check if an index is null, and if it is, ignore it?

for(int i=0;i<array.length,i++)
{
if(array[i]!=null)
System.out.println(array[i]);

}
public String toString() {
for(int i = 0; i <animals.length; i++)
{
    if(animals[i] != null){
                return name + "  is populated by:  \n" + animals[i];
        }
        }
return "String empty";
    }
}

I think we are on the same page. However my method cannot be type void so I have return statements. When I call on this method in my main it just print's the first one in the array.

Also animals[] is my array that is set to 10. I can have up to 10 animals in an area. However there will not always be 10 so when I call the two string I need to print out what is in there. example being the one I used before:

Example output.

Backyard is populated by:
Doug
Steve
Dog

So I guess my only problem is actually printing them all out.

Thanks and special thanks for the quick reply. :)

Instead of returning 1 name each time, build up your String.
e.g.

String s1 = "";//declare above your loop or something
if(animals[i] != null){
       s1 += animals[i]+"\n";//s1 = Doug...next time it finds one, s1 = doug, steve //etc., it will keep adding the values onto the string //s1, you will need the \n each time so it adds the next name on a new line

        }

//outside loop
return name + "is populated by " + s1;
commented: This person is great and helpful. +1

Instead of returning 1 name each time, build up your String.
e.g.
Java Syntax (Toggle Plain Text)

String s1 = "";//declare above your loop or something
    if(animals[i] != null){
    s1 += animals[i]+"\n";//s1 = Doug...next time it finds one, s1 = doug, steve //etc., it will keep adding the values onto the string //s1, you will need the \n each time so it adds the next name on a new line
     
    }
     
    //outside loop
    return name + "is populated

Wow, I didn't know you could do that. I thought it had to say with the original array. I feel dumb. I will remember this lesson and never make this mistake again. Thank you for your fast reply and kind help. I hope this helps some other people out there.

Thanks,

Newskin01

[SOLVED]

Member Avatar for ztini

You can save yourself a lot of headache by using ArrayList<String> instead of String[]. Why? Advanced for-looping:

public static void main(String[] args) {
		
		ArrayList<String> animals = new ArrayList<String>();
		animals.add("Lions");
		animals.add("Tigers");
		animals.add("Bears");
		
		for (String animal : animals) {
			System.out.println(animal);
		}
		
		System.out.println("Oh, my!");
	}

Of course, you could use an advanced for-loop on an array, but you have to include the same if-statement from before, to check for null. ArrayList size changes dynamically (well on the front end anyway) based on the data entered....so basically it will only hold only values and no nulls (unless you do .add(null)). It is almost always better to use an ArrayList.

One note. Do not use "\n", use System.getProperty("line.separator") to get the proper, platform-dependant line ending.

Edit: A second note, it is probably more effecient to simply print each line indivudually, if you can, as each String concatenation creates a StringBuffer and a new String. Or better, would be to "build your String" using a StringBuilder.

- StringBuilder is definitely the way to go if you want to assemble a String. Doesn't make a lot of difference in this sort of thing, but you want to get in the habit now, so later on when it matters, you aren't wasting cycles. My rule is, any time I concatenate Strings in any sort of a loop, I use a StringBuilder.

Like so:

String[] a = getMeAnArrayFromSomewhere();
String someFormattingStuff = ", ";
StringBuilder sb = new StringBuilder();
for (String s: a)
{
  sb.append(s);
  sb.append(someFormattingStuff);
}
System.out.println(sb.toString());

- The enhanced for loop works for arrays as wells as ArrayLists, so no need to rewrite for that purpose. ArrayLists are handy, though, and worth using for some things.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.