-1

I am trying to print each element in a String array but I seem to only be able to print a specific index.

    public String toString() {
        return fruits.fruitColor + fruits.fruitName;
    }

    public String toString() {
        return fruits[i].fruitColor + fruits[i].fruitName;
        i++; // I don't understand why the int i cannot be incremented to print out the next set of information?
    }

I don't know if I like the Arrays.toString(array) method because I don't necessarily want the [] format, but rather specific information from each element in chronological order. I attempted for loops as well in the toString() method, which also failed. Any suggestions are appreciated.

shibaking
  • 61
  • 1
  • 6
  • 5
    Because you already `return`ed. – SLaks Jun 07 '18 at 20:40
  • [This](https://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-a-java-array) is exactly what you are asking. – Arthur Attout Jun 07 '18 at 20:40
  • 2
    Possible duplicate of [What's the simplest way to print a Java array?](https://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-a-java-array) – jmoerdyk Jun 07 '18 at 20:42
  • 2
    `return Arrays.stream(fruits).map(f -> f.fruitColor + f.fruitName).collect(Collectors.joining(", "));` – Elliott Frisch Jun 07 '18 at 20:43
  • I undersand those questions seem very similar, but how can I extract information from an index in the string array, then increment it. It seems that the Arrays.toString() is forcing a format of [string0, string1, string2] when I am looking for an output of: "My first word is string0 and my second word is string1" I was hoping a for loop could accomplish something like this, since each of my arrays get populated by the user in the main function. – shibaking Jun 07 '18 at 20:46
  • The guy don't know how to code very much, but sure tried and asked for help. In my book that's a good question. I don't get the down votes. I'll up vote. – Sebastian D'Agostino Jun 07 '18 at 20:46
  • Based on this it may not be possible to override toString method for the Array of strings https://stackoverflow.com/a/10296164/3254405 – boateng Jun 07 '18 at 20:48
  • Can you clarify your input and expected output? The question is a little unclear imo. – achAmháin Jun 07 '18 at 20:48

1 Answers1

0
  1. you are returning before the increment is happening, you could just do
string str = fruits[i].fruitColor + fruits[i].fruitName;
i++;
return str;

Im curious to what scope that index variable is in.. you should hand it an index as a paramater instead

Zach Hutchins
  • 801
  • 1
  • 12
  • 16