Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You should loop through the array and use an index / boolean flag to store whether or not the book is found. Then print the message in the end, based on the index / flag value.</p> <pre><code>int foundAtIndex = -1; for(int i = 0; i &lt; bookObj.length; i++) { if(bookObj[i].getName().equals(input)) { foundAtIndex = i; // store the actual index for later use break; // no need to search further } } if(foundAtIndex &gt;= 0) System.out.println("Book Found!"); else System.out.println("Book not Found!"); </code></pre> <p>Alternatively (unless your assignment specifically requires using an array) you should prefer a <code>Set</code>, which can do the search for you with a single call to <a href="http://download.oracle.com/javase/6/docs/api/java/util/Set.html#contains%28java.lang.Object%29" rel="nofollow noreferrer"><code>contains()</code></a>.</p> <blockquote> <p>How should I think of it in Object Oriented way?</p> </blockquote> <p>When looking at a single method, there is not much difference between procedural and OO style. The differences start to appear at a higher level, when trying to organize a bunch of conceptually related data and methods that operate on these.</p> <p>The OO paradigm is to tie the methods to the data they operate on, and encapsulate both into coherent objects and classes. These classes are preferably representations of important domain concepts. So for your book store, you may want to put all book related code into your <code>Book</code> class. However, the above search method (and the collection of books it operates on) is not related to any particular book instance, so you have different choices:</p> <ul> <li>put both the collection of books and the search method into <code>Store</code> (probably as regular members), or</li> <li>put them into <code>Book</code> as <code>static</code> members.</li> </ul> <p>The first choice is more natural, so I normally would prefer that. However, under specific circumstances the second option might be preferable. In (OO) design, there are hardly ever clean "yes/no" answers - rather tradeoffs between different options, each having their own strengths and weaknesses.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload