如何在方法中添加多个return语句?

时间:2015-01-09 10:15:16

标签: java arrays object return return-value

我尝试使用gettersetter方法返回某些对象的某些值。现在我不能在单个方法中返回多个值。在这种情况下,我是否需要为每个return.创建不同的方法?如果没有,我该如何解决?

我的代码:

    package books;

public class BooksObject {
    //variable for book 1

    String name1 = "The brief history of time";
    String isbn1 = "111";
    String[] authName1 = {"S. Hawking", " Hawking's friend"};

//variable for book 2
    String name2 = "100 years of solitude";
    String isbn2 = "222";
    String[] authName2 = {"G. Marquez", "Marquezs friend"};

    //All setters
    public void setBook1(String n_1, String i_1, String[] a_N1) {
        name1 = n_1;
        isbn1 = i_1;

        String[] authName1 = a_N1;
    }

    public void setBook2(String n_2, String i_2, String[] a_N2) {
        name2 = n_2;
        isbn2 = i_2;

        String[] authName2 = a_N2;
    }

    //All getters method
    public String getBook1() {
        return name1;

        //return isbn1; //shows error
        //return String[]authName1;//Shows error
    }

}

[注意:我当然要在我的主类中调用所有这些方法。我只是没有在这里发布。]

2 个答案:

答案 0 :(得分:9)

您应该创建一个包含3个属性的Book类,并且您的getter将返回Book实例。

而不是

String name1 = "The brief history of time";
String isbn1 = "111";
String[] authName1 = {"S. Hawking", " Hawking's friend"};

你有

Book book1 = new Book ("The brief history of time", "111", {"S. Hawking", " Hawking's friend"});

然后:

public Book getBook1() {
    return book1;
}

您可以通过拥有图书数组(BooksObject)而不是每本图书的不同变量来进一步改善Book[]。那么每本书都不需要单独的getBooki方法。

答案 1 :(得分:1)

我认为你应该改变你的代码,如下所示:

public class Book
{
    private String name;

    private String isbn;

    private String[] authors;

    /* constructor */

    public Book(String name, String isbn, String[] authors) {
        this.name = name;
        this.isbn = isbn;
        this.authors = authors;
    }

    /* setter */

    public void setName(String name) {
        this.name = name;
    }

    public void setIsbn(String isbn) {
        this.isbn = isbn;
    }

    public void setAuthors(String[] authors) {
        this.authors = authors;
    }

    /* getter */

    public String getName() {
        return name;
    }

    public String getIsbn() {
        return isbn;
    }

    public String[] getAuthors() {
        return authors;
    }
}



public class Main
{
    public static void main(String[] args) {
        Book book1 = new Book(
            "The brief history of time",
            "111",
            new String[]{"S. Hawking", " Hawking's friend"}
        );
        Book book2 = new Book(
            "100 years of solitude",
            "222",
            new String[]{"G. Marquez", "Marquezs friend"}
        );
    }
}
相关问题