2

尝试将书籍附加到书籍的类列表时出现错误。关于为什么或我能做些什么来解决它的任何想法?

        //For each book in a class...
        for (int k = 0; k < rows.size(); k++) {
            Book book = new Book()

            //Assign the values to a new book object
            book.id            = rows[k].getProperty("ISBN")
            book.title         = rows[k].getProperty("title")
            book.author        = rows[k].getProperty("author")
            book.required      = rows[k].getProperty("required_optional")
            book.purchaseType  = rows[k].getProperty("rental_purchase")
            //book.purchasePrice = rows[k].getProperty("purchase_price")
            //book.rentalPrice   = rows[k].getProperty("rental_fee")

            //Append the book to the books list object in the particular class
            classes[i].books[k + 1] << book
        }
4

4 回答 4

4

不是通过[]use访问getAt,而是?Operator 将工作:

classes?.getAt(i)?.books?.getAt(k+1) << book

或者

classes?.getAt(i)?.books[k+1] << book
于 2015-10-05T06:19:16.480 回答
2
rows.each { row ->
  Book book = new Book(...)
  classes[i].books << book
}
于 2013-02-06T20:32:26.387 回答
0

我不确定“类”是什么,但如果它是一个包含“书”的列表,你可以这样做

classes << book

或者

classes.add(book)
于 2013-02-07T12:35:15.903 回答
0

如果没有完整的代码,很难知道会发生什么。试试这段代码,它会告诉你哪个值为空:

// first check if classes[i] is null, add error handling if it is
if (classes[i]!=null) {
    //For each book in a class...
    for (int k = 0; k < rows.size(); k++) {     
        def books = classes[i].books[k + 1]
        if (books!=null) {
            // you can set values directly here
            def row = rows[k]
            Book book = new Book(
                id: k.getProperty("ISBN"),
                title: k.getProperty("title")
                // ...
            )
            //Append the book to the books list object in the particular class
            books << book
        } else {
            println "books is null, do something clever"
        }
    }
} else {
    println "classes[i] is null, do something clever"
}

我没有测试它,你可以用一些时髦的东西来缩短它。这只是为了让你开始

于 2013-02-06T17:23:47.233 回答