-1
public String toString() {
    for(int i = 0; i<items.length; i++) { //i++ is considered "dead code"
        return "Name: " + items[i].getName() + ", Is carn? " + items[i].getVeg() + ", Pop: " + items[i].getPop();
    }
    return null;
}

This method should go through an array and return the name, veg and pop. Works for items[0] but not further.

5 Answers5

2

Your for loop is the same as:

int i = 0:
while (i < items.length) {
  return "Name: " /* etc */;
  i++; // Update.
}

If you enter the loop, you start to execute the body, and then return, so you never execute the update.

If you don't enter the loop, you don't execute the update.

So you don't execute the update, hence the update is dead code.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
1

i++ is supposed to run after first and subsequent iterations, since code is returning without any condition in the first iteration itself i++ will never be reached.

dev. K
  • 63
  • 1
  • 6
0

This is considered "dead code" as the return statement will end the function so instead having the for loop just print the lines and then the function ceasing it's execution following the loop.

Or if you want to use the lines being made here for something, make an array of strings out of them and return that

Scain40
  • 21
  • 3
0

Right, you're probably confused about what the return statement does. I think you're trying to do the following:

public String toString() {
    final StringBuilder result = new StringBuilder();
    for(int i = 0; i<items.length; i++) {
        result.append("Name: ").append(items[i].getName())
              .append(", Is carn? ").append(items[i].getVeg())
              .append(", Pop: ").append(items[i].getPop())
              .append("\n");
    }
    return result.toString();
}

The return statement does exactly that: it returns immediately from a method and returns a result (or nothing, in case of a void method). It doesn't somehow magically append to your expected result; you'll have to do that yourself.

SeverityOne
  • 2,476
  • 12
  • 25
0

return an Array or a List. Also it is better to make a method toString (or print if you already have toString) in your Item class. I would do it like this.

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Demo {
    private Item[] items;

    class Item {
        private String name;
        private boolean veg;
        private String pop;
        /* Constructor, getters and setters */

        @Override
        public String toString() {
            return "Name: " + name + ", Is carn? " + veg + ", Pop: " + pop;
        }
    }

    public List<String> listItemsString() {
        return Stream.of(items).map(Item::toString).collect(Collectors.toList());
    }

    public String[] arrayItemsString() {
        return Stream.of(items).map(Item::toString).toArray(String[]::new);
    }
}