类型中的方法不适用于参数

时间:2015-01-01 04:47:33

标签: java class methods

我是一名基础班级创作教程的新手,并且已经给出了以下说明。

1) Create a new class called Book.
2) Create fields for title, author, numPages, and isbn.
3) Create a method called toString that appropriately describes the book.
4) In the file, BookRunner.java:
  a) Declare two book variables
  b) Instantiate two book objects and set their fields.
  c) Print descriptions of the book objects using their toString methods.

所以我按照指示使用了两个类,你可以看到下面的代码

public class Book {
    public String title;
    public String author;
    public String numPages;
    public String isbn;

    public void toString(String bookName) {
        String description = "Title:" + title + "Author"+ author + "Num. of pages" + numPages + "ISBN" + isbn; 
        System.out.println(description);
    }

public class Ex1_BookRunner {

    public static void main(String[] args) {
        Book firstBook;
        Book secondBook;

        firstBook = new Book();
        secondBook = new Book();

        firstBook.title = "One Piece";
        firstBook.author = "Oda-Sensei";
        firstBook.numPages = "100";
        firstBook.isbn = "123456";

        secondBook.title = "Life of Megan Fox";
        secondBook.author = "Micheal Bay";
        secondBook.numPages = "200";
        secondBook.isbn = "098765";

        toString(firstBook);
        toString(secondBook);
    }
}

在我调用方法toString的最后两行之前,我的代码没有显示任何错误。

我收到以下错误

The method toString() in the type Object is not applicable for the arguments (Book)

我在方法声明中某处发生了一些基本错误吗?我在同一个问题上查看过SO上的其他帖子,但我无法理解所给出的解释,因为它们主要涵盖了我尚未学习的代码语法。

感谢任何帮助:)

4 个答案:

答案 0 :(得分:1)

尝试firstBook.toString(); - 这会产生一个字符串,如果你想看到它,你可以做System.out.println(firstBook.toString());之类的事情。该错误告诉您没有将book作为参数的toString方法。你想要的是调用你创建的Book实例上的toString()方法

答案 1 :(得分:0)

将它们更改为:

firstBook.toString();
secondBook.toString();

您可以在您创建的firstBook和secondBook上调用默认的.toString()方法。但是,由于您没有定义将Book对象作为参数的toString方法,因此将Book对象传递给toString()会产生上述错误。

事实上,您的错误行清楚地解释了这一点:

The method toString() in the type Object is not applicable for the arguments (Book)

答案 2 :(得分:0)

尝试我们的toString方法

 public String toString() {
   String discription= "Title:" + title + "Author"+ author + "Num. of pages" + numPages + "ISBN" + isbn;
    return discription;
}

并且main方法中的print语句也应如下所示

   System.out.println(firstBook.toString());
   System.out.println(secondBook.toString());

我希望有帮助

答案 3 :(得分:0)

同一类中有两个公共类

        public class Book {
//your codes or variables
}
    public class Ex1_BookRunner {
//your code or variables
}

试试这个