我需要使用我的主方法中的数组并将其传输到我的 getBook 方法,然后将新创建的对象返回到主方法中的数组。
我决定将数组转移到下一个方法,方法是与扫描程序相同的方式进行操作,直到我需要在错误时调用该方法。
public class BookShopApplication
{
public static void main(String[] args)
{
Scanner kybd = new Scanner (System.in);
Book [] books = new Book [10];
for (int i = 0; i > books.length; i++)
{
books[i] = getBook(kybd, Book books[])
}
}
public static Book[] getBook(Scanner kybd, Book books[])
{
System.out.println("What is the title of the next book?");
String readTitle = kybd.nextLine();
System.out.println("What is thr title of thje next book?");
String readAuthor = kybd.nextLine();
if (readAuthor == null)
{
for (int i = 0; i < books.length; i++)
{
books[i] = new Book();
books[i].Book(readTitle);
}
}
else
{
for (int i = 0; i < books.length; i++)
{
books[i] = new Book();
books[i].Book(readAuthor, readTitle);
}
}
return books;
}
}
我需要的结果是将书籍返回到数组并存储。
假设你的Book
类看起来有点类似于这样:
class Book
{
private String title;
private String author;
public void setTitle(String title)
{
this.title = title;
}
public void setAuthor(String author)
{
this.author = author;
}
}
尝试单独实例化书籍并将它们存储在Book
对象数组中更有意义。
public static void main(String[] args) {
Scanner kybd = new Scanner (System.in);
Book [] books = new Book [10];
// < is needed not >
for (int i = 0; i < books.length; i++)
{
// book[] is empty, it has an index of 10 with no nodes
// You need to create the instance to pass into the method
books[i] = getBook(kybd, new Book());
}
}
// This should only take the book it is working with
public static Book getBook(Scanner kybd, Book book)
{
System.out.println("What is the title of the next book?");
String readTitle = kybd.nextLine();
System.out.println("What is the title of the next book?");
String readAuthor = kybd.nextLine();
if (!readAuthor.isEmpty())
{
book.setTitle(readTitle);
}
if(!readTitle.isEmpty())
{
book.setAuthor(readAuthor);
}
return book;
}
你也有很多语法错误 - 使用 .isEmpty()
方法而不是使用 === null
.
更新:您从未在循环中实际创建Book
实例。另外,for (int i = 0; i > books.length; i++)
- 它应该是<
而不是>
.
此代码现在应该可以工作了。
好吧,你确实有一些语法错误:
首先,在你的 for 循环中,books[i] = getBook(kybd, Book books[])
应该替换为 books[i] = getBook(kybd, books)
(要将变量作为参数传递给方法,只需使用它的名称!
其次,在方法签名中,将public static Book[] getBook(Scanner kybd, Book books[])
替换为public static Book[] getBook(Scanner kybd, Book[] books)
(注意,它是Book[] books
,而不是Book books[]
(。
希望这有帮助!
另外,正如 Jaquarh 评论的那样,您缺少一个分号!
编辑:此外,正如Jaquarh指出的那样,您的方法getBooks
应该返回一本书,而不是数组。否则,该行 books[i] = getBook(kybd, Book books[])
会崩溃。
for (int i = 0; i > books.length; i++)
{
books[i] = getBook(kybd,books);
}
应该做这个技巧,不会导致错误
这也是无效的:
for (int i = 0; i < books.length; i++)
{
books[i] = new Book();
**books[i].Book(readTitle);**
}
}
else
{
for (int i = 0; i < books.length; i++)
{
books[i] = new Book();
**books[i].Book(readAuthor, readTitle);**
编辑