私有方法的返回值

时间:2014-08-08 03:38:08

标签: java

我来了......我的问题是我什么时候输入了......但是显示期间总页数没有返回..

private int totalPages () {
    totalPages = first.getPages() + second.getPages() + third.getPages();
    return totalPages;
}

//Make a subprogram to display the info of author, 
//title, year, and totalPages and return the values
public String printInfo () {
    String info = "Book Title: " + title + "\n";
    info += "Book Author: " + author + "\n";
    info += "Year: " + year + "\n";
    info += "Number of pages: " + totalPages + "\n";
    return info;
}

输出为0 ......为什么??

2 个答案:

答案 0 :(得分:2)

您没有调用totalPages()方法

info += "Number of pages: " + totalPages() + "\n";

答案 1 :(得分:0)

the output is 0... why??

您实际返回的是info += "Number of pages: " + totalPages + "\n";totalPages看起来像是一个实例变量  (因为你已经跨方法使用它了)。实例变量获取默认值,并且整数的默认值为0。这就是你得到0的原因。

要获得所需的值,您必须调用方法totalPages()替代以上回答您甚至可能无法在串联中使用该呼叫。你可以做到

public String printInfo () {
    totalPages();
    String info = "Book Title: " + title + "\n";
    info += "Book Author: " + author + "\n";
    info += "Year: " + year + "\n";
    info += "Number of pages: " + totalPages + "\n";
    return info;
}

另外我建议不要继续使用+运算符。而是使用StringBuilderStringBuffer