Home > OS >  how to return a class type in a method in Java
how to return a class type in a method in Java

Time:01-05

I have implemented a particular method to search a book corresponding to a given ISBN number and return that book. But I have used the return type as void in that method (searchBook method ) because I cannot figure out how to return a "Book". So how do I return that book rather than printing it ?

    public class User {
        int ID;
        String name;
        String email;
        int age;
        String isbn;

        public User(int ID,String name,int age){
            this.ID = ID;
            this.name = name;
            this.age = age;
        }

        public static void searchBook(Book[] b, String isbn) {
            int found = 0;
            for (int i = 0; i < 6; i  ) {
                if (b[i].ISBN == isbn) {
                    found = 1;
                    System.out.println(b[i].title);
                    break;
                }
            }
            if (found == 0) {
                System.out.println("ISBN Not Found");
            }
        }
    }

    public class Book {
        String title;
        String author;
        String ISBN;
        float rating;
        int noOfDays;

        public  static void displayBookDetails(Book[] b){   
            System.out.println("Title\t\t\t\tAuthor\t\tISBN\t\tRating");
            for(int i=0;i<b.length;i  )
            {
                System.out.println(b[i].title "\t\t\t" b[i].author "\t" b[i].ISBN  "\t" b[i].rating);
            }
        }

        //book constructor
        public Book(String title,String author ,String ISBN,float rating){
            this.title = title;
            this.author = author;
            this.ISBN = ISBN;
            this.rating = rating;
        }
    }
public class Driver {

    

    public static void main(String[] args) {


Book[] arr = new Book[6];
        arr[0] = new Book("Rabbi Zidni Ilma", "Martin", "2194-5357", 6.5f);
        arr[1] = new Book("A story of a soldier","Martin", "2193-4567", 3.2f);
        arr[2] = new Book("Apple Garden", "Rexon", "2104-3080", 1.2f);
       }
}

**System.out.println(Customer.searchItem(item,53965307));**

CodePudding user response:

Just return Book object after finding book. And there is an error. String value should be compared by equals method.

    public static Book searchBook(Book[] books, String isbn) {
        for (Book book : books) {
            if (book.ISBN.equals(isbn)) {
                return book;
            }
        }
        // or throw new RuntimeException("Not Found Book matching isbn");
        return null;
    }
Override toString method
class Book {

    // ... other code

    @Override
    public String toString() {
        return title   "\t\t\t"  author "\t"  ISBN  "\t"  rating;
    }
}

CodePudding user response:

Here's an example of how you would return an object from a method.

To compare objects including Strings, you need to use equals instead of == operator. The == operator only works on primitive values.

class Book {
    String title;
    Book(String title){ this.title = title; }
}

class Main{
    
    static Book find(Book[] books, String title){
        for(int i=0; i<books.length; i  )
            if (books[i].title.equals(title)){
                return books[i];
        return null;
    }
    
    public static void main(String[] args) {
        Book[] books = {new Book("A"), new Book("B"), new Book("C")};
        Book b = find(books, "B");
        System.out.println(b.title);
    }
}

CodePudding user response:

Declare that method searchBook returns Book (rather than void) and add two return statements: One if the Book is found and another if it is not.

/**
 * Returns the book having the supplied ISBN in array 'b' or null if
 * no book in 'b' has the given ISBN.
 *
 * @param b - array of books to search.
 * @param isbn - ISBN to search for in 'b'.
 *
 * @return  Book with given ISBN or null if nothing found.
 */
public static Book searchBook(Book[] b, String isbn) {
    for (int i = 0; i < 6; i  ) {
        if (b[i].ISBN.equals(isbn)) {
            return b[i];
        }
    }
    return null;
}

If you are using at least Java 8 then you can use the stream API

public static java.util.Optional<Book> searchBook(Book[] b, String isbn) {
    return java.util.Arrays.stream(b)
                           .filter(book -> isbn.equals(book.ISBN))
                           .findFirst();
}

Refer to How do I compare strings in Java to see how to test whether two strings are equal.

  •  Tags:  
  • Related