Java: For loop and If algorithm

40,529

Solution 1

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.

int foundAtIndex = -1;
for(int i = 0; i < 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 >= 0)
    System.out.println("Book Found!");
else
    System.out.println("Book not Found!");

Alternatively (unless your assignment specifically requires using an array) you should prefer a Set, which can do the search for you with a single call to contains().

How should I think of it in Object Oriented way?

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.

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 Book 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:

  • put both the collection of books and the search method into Store (probably as regular members), or
  • put them into Book as static members.

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.

Solution 2

You could introduce state and remember whether you have found the book or not.

If you're not using Java 1.4 or earlier, you could also use the foreach loop syntax:

boolean bookFound = false;
for(Book currentBook : bookObj) {
     if(currentBook.getName().equals(input))
     //TODO: see above
}

Also, I would suggest looking into the Collections library, and replace your array with a list or set:

Set<Book> books = new HashSet<Book>();
books.put(new Book("Game Over"));
books.put(new Book("Shrek")); 
books.put(new Book("Ghost"));

And, while were at it, you could also think about when two books are equal and override equals() and hashCode() accordingly. If equal() would be changed to check the title, you could simply use books.contains(new Book(input)); and have the libraries do the work for you.

Solution 3

To solve the problem in a better way you must understand that the power of Java comes not from the language itself but from the Java Framework.

You should learn the usage of the Java Collection classes (never work with arrays anymore). Then you will be able to solve the search with just one line of code:

ArrayList<Book> listOfBooks;
// init your list here
listOfBooks.contains(new Book(input));

To make this work, you must also learn how to correctly implement the equals() method of your Book class.

Happy learning!

Share:
40,529
Ben C.
Author by

Ben C.

Updated on November 07, 2020

Comments

  • Ben C.
    Ben C. over 3 years

    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.

    --

    Book.java

    public class Book {
    
        private String name;
    
        Book(String name)
            this.name = name;
    
        public String getName()
            return name;
    
    }
    

    Store.java

    Inside main();

     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();
    

    Assuming, input = Devil.

    Now, I need to do a simple search to check whether the specific book exist.

    Example:

     for(int i = 0; i < bookObj.length; i++) {
         if(bookObj[i].getName().equals(input))
             System.out.println("Book Found!");
     }
    

    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.

    Example:

     for(int i = 0; i < bookObj.length; i++) {
         if(bookObj[i].getName().equals(input))
             System.out.println("Book Found!");
         else
             System.out.println("Book not Found!");
     }
    

    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.

    Usually, in structural programming, I would do the following,

    for(int i = 0; i < 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!");
     }
    

    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.

    How should I think of it in Object Oriented way?

    All in all, my question is,

    1. Is there a better way to write the above code rather than checking that it's the end of the line?
    2. Is there a better way to utilize getName() method or to use other methods?
  • Dave Jarvis
    Dave Jarvis over 13 years
    This is correct. Use a collection (like a Set) instead of an array.
  • KevinDTimm
    KevinDTimm over 13 years
    note that you should break from the loop when you've found your item (either using break; or testing bookFound in the for loop). note too that the enhanced for looping in current java is a far better solution.
  • KevinDTimm
    KevinDTimm over 13 years
    contains() does not appear in the original specification - equals() however does - downvote negated
  • Thomas Lötzer
    Thomas Lötzer over 13 years
    @KevinDTimm I still edited my answer to include the contains() suggestion, since it may be useful.
  • KevinDTimm
    KevinDTimm over 13 years
    IIRC, contains will find matches within the string. The OP 'requires' that 'Devil' be found - this implies exact match - so I would hesitate to use contain
  • Thomas Lötzer
    Thomas Lötzer over 13 years
    @KevinDTimm I'm doing contains() not on a String but on the set. On the String you're right, contains() would not be a good idea there.
  • Tony Ennis
    Tony Ennis over 13 years
    It saddens me that arrays are taught as primary data structures. They have become special-case data structures now.
  • Ben C.
    Ben C. over 13 years
    I haven't learn Generics so I can't use the Collection Framework until I do. Will learn it myself :)
  • Péter Török
    Péter Török over 9 years
    -1 for publishing code which is likely to throw an ArrayIndexOutOfBoundsException on the very first line, all the while bashing other solutions for being "incorrect". Not to mention ignoring Java coding conventions.
  • Tyler Durden
    Tyler Durden over 9 years
    @PéterTörök The technique used in my code is the most efficient method. The first line initializes a sentinel (read Knuth 1.4.4). Somewhat comical for "programmer" that uses flag variables and doesn't even know what a sentinel is to be criticizing my code.
  • Péter Török
    Péter Török over 9 years
    You are repeatedly making sweeping allegations (based on minimal information) about what others may or may not know about programming. Rest assured that I read Knuth and know what a sentinel is. However, what works in one language may not be automatically ported to another. And correctness trumps efficiency. It is a fact that indexing a Java array one past its allocated size leads to an ArrayIndexOutOfBoundsException. (Unless you make sure to reserve an extra element in advance - which may not always be possible, and is not mentioned anywhere in your answer anyway.)