写作课我错过了什么?

时间:2016-02-13 08:02:45

标签: java

到目前为止,我有一个项目,这是我想要的输出:

测试1

enter image description here

测试2

enter image description here

以下是方向。“编写一个名为Book的类,其中包含标题,作者和页面的实例数据。定义Book构造函数以接受和初始化此数据。包括所有实例数据的setter和getter方法。包括一个toString方法,返回如下字符串:

Author: name of the author in one word

Title: title in one word

Pages: number of pages

示例:

Author: Lewis

Title: Java

Pages: 806

编写BookTester类以从键盘获取作者,标题,页面,创建书籍对象并将上述内容打印到屏幕上。我如何得到答案,以显示我的图片Test1和Test 2中显示的预期输出?另外,我错过了什么?

预订

    public class Book {
        String author;
        String title;
        int pages;

        public Book(String a, String t, int p) {
        author = a;
        title = t;
        pages = p;
    }

        public String toString() {
        String output;
        output = ("Author: " + author + "\n");
        output = ("Title: " + title + "\n");
        output = ("Pages: " + pages + "\n");
        return output;
    }
}

BookTester

    import java.util.*;
    public class BookTester {
    public static void main(String[] args) {
    String author;
    String title;
    int pages;
    Scanner scan = new Scanner(System.in);
    author = scan.nextLine();
    title = scan.nextLine();
    pages = scan.nextInt();
    Book book1 = new Book(author, title, pages);
    System.out.println(book1);
     }
     }

3 个答案:

答案 0 :(得分:2)

CB.CloudUser:
    document: Object
        _id: "id",
        image: CB.CloudFile
            document: Object
                _id: "id",
                _type: "file"

你应该连续(+)每个值。否则将返回最后一个值(表示 @Override public String toString() { String output =""; output += "Author: " + author + "\n"; output += "Title: " + title + "\n"; output += "Pages: " + pages + "\n"; return output; } )。

答案 1 :(得分:1)

试试这个:

public String toString() {
    String output = "Author: " + author + "\n" + "Title: " + title + "\n" + "Pages: " + pages + "\n";
    return output;
}

您不断更换返回的Output字符串,而不是添加它。

答案 2 :(得分:0)

程序无效,因为您正在重写 toString 方法中的输出:

public Class Product
{
  // Here is all the properties you want to discribed.
  // This property is same as the property available in your JSON file.
}

必须采取一些措施来解决这个问题。

public String toString() {
    String output;
    output = ("Author: " + author + "\n");
    output = ("Title: " + title + "\n");
    output = ("Pages: " + pages + "\n");
    return output;
}

不要忘记 @override ,这是一个很好的做法,

最终推荐: 使用IDE的功能生成toString方法总是一个好主意。不要手工编码。

例如,我发现您正在使用Eclipse,如果您只需右键单击源代码并选择Source>此IDE就可以这样做。生成toString