title: Java: For loop and If algorithm
body: <p>I've this question from an assignment to create a Store which rent out books, using a Store.java and Book.java. I've finished this assignment, but I'm curious for better algorithm to a specific part.</p>
  
  <p>--</p>
  
  <p><strong>Book.java</strong></p>
  
  <pre><code>public class Book {
  
      private String name;
  
      Book(String name)
          this.name = name;
  
      public String getName()
          return name;
  
  }
  </code></pre>
  
  <p><strong>Store.java</strong></p>
  
  <p>Inside main();</p>
  
  <pre><code> Book bookObj[] = new Book[3]; //Create 3 Array of Object.
   bookObj[0] = new Book("Game Over");
   bookObj[1] = new Book("Shrek"); 
   bookObj[2] = new Book("Ghost");
   Scanner console = new Scanner(System.in)
   input = console.nextLine();
  </code></pre>
  
  <p>Assuming, input = Devil.</p>
  
  <p>Now, I need to do a simple search to check whether the specific book exist.</p>
  
  <p>Example:</p>
  
  <pre><code> for(int i = 0; i &lt; bookObj.length; i++) {
       if(bookObj[i].getName().equals(input))
           System.out.println("Book Found!");
   }
  </code></pre>
  
  <p>Apparently, this is a for loop that cycles through the array of object and checks whether such Book exist. Now, the problem arise when I want to give an output that the Book was not found.</p>
  
  <p>Example:</p>
  
  <pre><code> for(int i = 0; i &lt; bookObj.length; i++) {
       if(bookObj[i].getName().equals(input))
           System.out.println("Book Found!");
       else
           System.out.println("Book not Found!");
   }
  </code></pre>
  
  <p>The problem with the above code is that Book not Found would be printed thrice. My goal is to avoid such problem. I do have solutions to this, but I'm still in search for a better one to use that utilizes getName(), which in my opinion still has room to improve.</p>
  
  <p>Usually, in structural programming, I would do the following,</p>
  
  <pre><code>for(int i = 0; i &lt; bookObj.length; i++) {
       if(bookObj[i].getName().equals(input))
           System.out.println("Book Found!");
       else if(i == bookObj.length - 1)
           System.out.println("Book not Found!");
   }
  </code></pre>
  
  <p>This is useful to tell whether it's the end of the loop, and the search has ended, but there was no successful result from the search.</p>
  
  <p>How should I think of it in Object Oriented way?</p>
  
  <p>All in all, my question is,</p>
  
  <ol>
  <li>Is there a better way to write the above code rather than checking that it's the end of the line?</li>
  <li>Is there a better way to utilize getName() method or to use other methods?</li>
  </ol>