К сожалению, то, как я решил сделать это, - это добавить цикл, чтобы пользователь мог добавить столько книг, сколько он выберет, прежде чем двигаться дальше. Но так как это цикл, каждый раз, когда пользователь обошел, он по существу переписывает один и тот же массив (т. Е. У него одинаковое имя), прежде чем втянуть его обратно в массив. После большого количества мучительного, это было единственным способом, которым я мог подумать об этом. Код ниже: < /p>
Код: Выделить всё
static int numofbooks = 0;//I think you can ignore these for this question
static int checkedbooks = 0;
static ArrayList AllBooks = new ArrayList(); //this arraylist is the "library" that all the "books" are stored in. It's a static so it can be referenced across every method
public static void Add()
{
String user_answer = new String("yes");//this is for the while loop
Scanner cont = new Scanner(System.in);
Scanner bookscanner = new Scanner(System.in);
while (user_answer.equalsIgnoreCase("yes"))
{
String[] Book = new String[3];//This is the "book" to be stored
System.out.print("Enter book name: ");//the various detes
Book[0] = bookscanner.nextLine();
System.out.print("Enter the author's name: ");
Book[1] = bookscanner.nextLine();
System.out.print("Enter the ISBN: ");
Book[2] = bookscanner.nextLine();
AllBooks.add(Book);//The "book" is pushed into the arraylist
numofbooks++;//ignore
System.out.print("Would you like to add another book? Type yes if so: ");
user_answer = cont.nextLine();//if the user wants, they can do it again
}
}
Подробнее здесь: https://stackoverflow.com/questions/795 ... all-each-a