繁体   English   中英

在 java 中搜索数组并打印 output

[英]search an array in java and print the output

在这个 java 程序中,我试图搜索“图书”类型数组中是否存在 ISBN 号。 但是,当我尝试实现该方法并显示 output 时,我收到一条错误消息,提示“对于 Book 类型,方法 searchBook(Book, String) 是未定义的”。 <-- HERE注释显示错误弹出的位置。 我不明白如何纠正这个错误,任何帮助将不胜感激。 谢谢你。

驱动 class 是: QuizMain

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

    void searchBook(Book[] b, String isbn) {

        for (int i =0;i<6;i++) {
            if (b[i].ISBN == isbn) {
                System.out.println(b[i].title);
            } else {
                System.out.println("ISBN Not Found");
            }
        }
    }
}
public class Book {
    String title;
    String author;
    String ISBN;
    float rating;
    int noOfDays;

    void displayBookDetails() {
        System.out.println("Title\tAuthor\tISBN\tRating"+this.title +this.author + this.ISBN +this.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 QuizMain {
    public static void main(String[] args) {

        Book[] arr = new Book[6];
        arr[0] = new Book("Vincent la la ","king","2194-5357",6.5f);
        arr[1] = new Book("A man of wisdom","henry","2193-4567",3.2f);
        arr[2] = new Book("Apple Garden","timorthy","2104-3080",1.2f);
        arr[3] = new Book("Sherlock","Arthur","2165-0932",5.5f);
        arr[4] = new Book("Hello John","Tarnia","2134-2342",1.5f);
        arr[5] = new Book("Tarzan","Martin","2111-0564",4.2f);

        for(int i =0;i<arr.length;i++) { 
            arr[i].searchBook(arr[i], "2165-0932"); // <-- HERE
        }
        arr.searchBook(arr[5], "2165-0932"); // <-- HERE

    }
}

您的代码中有两个问题。 First one your searchBook function expecting Book type array and string but you are passing it one Book instant ie arr[i] with string and secondly you have define the searchBook() function in User class and using it with object of Book class. 将您的 function 移至预订 class。 Even you don't need that function in any of Book or User class you can simply define static function searchBook(Book[] books, String isbn) inside your QuizMain class and call it like

searchBook(arr,"8344-3452")

在用户 class 中,searchBook(Book[] b, String isbn) 方法接受 Book 数组和 String isbn 值。 但是在调用此方法时,您只传递了一本书 object 而不是 Book 数组。

将 searchBook 实现移动到 QuizMain class 并通过传递 Book 数组来调用它,如下所示的解决方法。

searchBook(arr, "2165-0932");

您可能需要专注于设计 class 及其行为。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM