-2

Getting an out of bounds error when trying to print the names of Movie objects stored in an Array.

Not sure whats happening here.

public String toString()
    {
        for(i=0;i<=mov.length;i++);
        return "Movie: "+mov[i].getName();

    }

I did just use the method from a previous example given to us and changed it to fit my program but its not working.

  • 3
    VTC - Typo. `for(i=0;i<=mov.length;i++);` Remove the semicolon - your for loop has no body. Thus `mov[mov.length+1]` which is invalid - Also `i < mov.length` - because, **and** *additionally*, `mov[mov.length]` is invalid. Finally, `return "Movies: " + Arrays.toString(mov);` (and remove the loop). – Elliott Frisch May 17 '17 at 00:46
  • suppose you have a error in the for loop code. `for(i=0;i<=mov.length;i++){ return "Movie: "+mov[i].getName(); }` – Rajith Pemabandu May 17 '17 at 00:47
  • @RajithPemabandu It gives me Missing return statement now?? – Sam Howard May 17 '17 at 00:55
  • This code doesn't make any sense. Why are you looping altogether? – shmosel May 17 '17 at 01:06
  • @shmosel how so? As I said, I used an example that was given to us that worked and just changed it to suit my code. – Sam Howard May 17 '17 at 01:15
  • There's no point in looping if you're returning a single, fixed value. What were you trying to do? – shmosel May 17 '17 at 01:16
  • @shmosel trying to get it to print the names of all the Movie objects stored in the array mov[] – Sam Howard May 17 '17 at 01:24
  • There's no print statement, only a `return` statement, which only runs once per method invocation, meaning it'll return the last movie name. – shmosel May 17 '17 at 01:26
  • @shmosel Is there a way to do what I want though? What should I be looking at to figure out how to do it? – Sam Howard May 17 '17 at 01:29
  • Yes, there are many ways. For example, `return Stream.of(mov).map(Movie::getName).map("Movie: "::concat).collect(Collectors.joining(", "));` – shmosel May 17 '17 at 01:31

1 Answers1

0

In your code, you are exiting the function immediately in the first iteration of your for loop. Then only the first item in the array will be returned.

This is probably closer to what you want, by concatenating all items in the array before returning it:

public String toString()
{
    String newline = System.getProperty("line.separator");
    StringBuilder result = new StringBuilder();
    for(i=0;i<=mov.length;i++) {
        result.append("Movie: ").append(mov[i].getName()).append(newline);
    }
    return result.toString();
}
KC Wong
  • 2,410
  • 1
  • 18
  • 26