[英]How do I store the user input that is indented by a space into the String array and convert the number into int array?
[英]How do I store user input into an array list?
我正在编写一个程序,允许用户输入一本书的详细信息并将它们存储在一个数组列表中。 我的问题是,如何获取用于在数组列表中存储多个值的代码,而不是仅仅覆盖已有的值?
这是我到目前为止...
Scanner input = new Scanner(System.in);
System.out.println("What is the book called?..");
String bTitle = input.nextLine();
System.out.println("Who is the author?..");
String bAuthor = input.nextLine();
System.out.println("How many do you have?..");
int bQuantity = input.nextInt();
System.out.println("How many are out on loan?..");
int bNumOnLoan = input.nextInt();
System.out.println("How many times has it been loaned?..");
int bNumTimesLoaned = input.nextInt();
ArrayList<Book> books = new ArrayList<Book>();
Book object = new Book(bTitle, bAuthor, bQuantity, bNumOnLoan, bNumTimesLoaned);
books.add(object);
但是当我再次运行它时,我之前输入的值已被替换。 任何帮助将不胜感激,因为我很难过。
import java.util.ArrayList;
import java.util.Scanner;
public class BookCapture {
static ArrayList<Book> books = new ArrayList<Book>();
public static void main(String ase[]){
for(int i=0;i<5;i++){
capture();
}
System.out.println(books.toArray());
}
public static void capture(){
Scanner input = new Scanner(System.in);
System.out.println("What is the book called?..");
String bTitle = input.nextLine();
System.out.println("Who is the author?..");
String bAuthor = input.nextLine();
System.out.println("How many do you have?..");
int bQuantity = input.nextInt();
System.out.println("How many are out on loan?..");
int bNumOnLoan = input.nextInt();
System.out.println("How many times has it been loaned?..");
int bNumTimesLoaned = input.nextInt();
Book object = new Book(bTitle, bAuthor, bQuantity, bNumOnLoan, bNumTimesLoaned);
books.add(object);
}
}
class Book{
// your book class
// do override your tostring() method;
}
在上面的代码中,您要求用户输入详细信息 5 次,这会在书籍 ArrayList 对象中捕获。 可以通过询问他想输入更多书来修改 for 循环,使其更加用户友好。
例如修改上面的代码以如下方式询问用户。
按1:如果您想添加另一本书
按2:如果您想查看所有书籍
按 3:如果您想退出程序。
进一步赋值。
阅读有关序列化的一些内容。这将解决在两次运行之间存储数据的问题。然后,修改程序以另外执行以下操作。
按 4:如果您想退出存储的书籍。
按 5:如果您想检索所有存档的书籍:)
使用 .add()不会替换ArrayList 中的内容,它只会向列表添加一个新元素。
这意味着要添加多个项目,只需多次使用.add()
。
然后你可以使用它们的索引来获取这些项目,例如:
ArrayList<String> list = new ArrayList<String>();
list.add("item1");
list.add("item2");
为了获得“item1”,使用list.get(0)
,并获得“item2”,使用list.get(1)
。
此外,Java不会在运行之间保存变量数据。 当程序结束时,存储在任何变量中的所有数据都将丢失。
要在运行之间保存数据,您可以将数据保存到文件中,并在运行开始时从中读取数据。 考虑使用FileWriter和FileReader 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.