Search code examples
javaarraysmethodsreturn-type

how to return a class type in a method in Java


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

Solution

  • 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;
        }
    }