![](/img/trans.png)
[英]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.