0

Hi so im writing a program and i want to return part of an array that does doesnt include null or 0 in it. so the array is originally int and i converted it to string and use this

public String toString(){
    // TODO: Return the String with the format of [1,2,3,4] as an example. Have stack items seperated by commas, enclosed inside brackets, and no comma at the end!

    if(top ==0 || a== null )
        return "[ ]";
    String [] d = new String [n];
    for(int r=0; r<n ; r++) {
        //if (r<0 && a[r] != 0)
        d[r] = Integer.toString(a[r]);
    }
    return "[" + String.join("," , d) + "]";


    // This can be removed but is here to prevent the Java error while testing!
}

to return the result i wanted but instead of it returning the valued i need it is returing all the values in the array no matter what if statement i am using. so n =256. can someone plz help me my hw is due soon and its the last part thats been bugging me the entire day.

1 Answers1

0

Consider the code:

for(int r=0; r<n ; r++) {
    if (<anything>)
        d[r] = Integer.toString(a[r]);
}

In this code r is going to increment on each iteration irrespective of whether the <anything> is true or not. So you will be filling values when the condition holds and skipping the other values. This probably is not what you want.

You have a few options. The easiest is to use a List instead of an array:

List<String> result = new ArrayList<>();
for(int r=0; r<n ; r++) {
    if (<anything>)
        result.add(Integer.toString(a[r]);
}

If you must use an array then you will need to store the number of items separately so that you know how many items that met the condition there are:

int itemCount = 0;
for(int r=0; r<n ; r++) {
    if (<anything>)
        d[itemCount++] = Integer.toString(a[r]);
}

You can then either use the item count in your print statement or resize the array:

d = Arrays.copyOf(d, itemCount);

Even easier than all of these is to use a Stream to do it all in one statement:

String result = Arrays.stream(a)
    .filter(<anything>).mapToObj(Integer::toString)
    .collect(Collectors.joining(",", "[", "]");
sprinter
  • 27,148
  • 6
  • 47
  • 78