我是新來的java,我試圖通過創建一個TestAddRemove程序來測試我學到了什麼。從本質上講,它應該讓你選擇兩個數組中的一個,並允許你添加公司名稱,刪除公司名稱,並閱讀你正在尋找的公司是否在其中一個數組中。不知道如何將字符串添加到arraylist並使其堅持
我的主要問題是添加到數組部分。每次我使用Add類添加公司時,它都可以工作,但是當我再次檢查數組時,數組是空的。
主要問題 n:如何在主程序中將公司名稱添加到數組中並讓它粘住?
這裏是我的代碼:
public class TestAddRemove
{
static Scanner sc = new Scanner(System.in);
static ArrayList<String> fileOne = new ArrayList<String>();
static ArrayList<String> fileTwo = new ArrayList<String>();
:
: //Some other stuff
:
String tryAgain = "Y";
String answer;
String fileAnswer;
System.out.println("Welcome to the company tester; this program tests whether the company"
+ "you input is a company we already received donations from or a company we have"
+ "spoken to already, but declined to donate.");
while (tryAgain.equalsIgnoreCase("Y"))
{
System.out.println("Do you want to test, add or remove a company name? ");
answer = sc.next();
String companyName;
if (answer.equalsIgnoreCase("add"))
{
System.out.println("Which file do you want to add to?");
fileAnswer = sc.next();
if (fileAnswer.equalsIgnoreCase("fileOne"))
{
Add file = new Add(fileOne);
System.out.println("Enter the company name you want to add. ");
companyName = sc.next();
file.addCompany(companyName);
}
else
{
Add file = new Add(fileTwo);
System.out.println("Enter the company name you want to add. ");
companyName = sc.next();
file.addCompany(companyName);
}
代碼的其餘部分是用於刪除和測試方法,我想我會明白,一旦我知道如何添加公司名稱。
這裏的添加類:
public class Add
{
Scanner sc = new Scanner(System.in);
ArrayList<String> file;
public Add(ArrayList<String> fileOne)
{
this.file = fileOne;
}
public void addCompany (String companyName)
{
file.add(companyName);
}
public ArrayList<String> getFile()
{
return file;
}
}
任何幫助將是真棒,感謝和歡呼聲!
提供的代碼似乎工作正常。你有沒有嘗試設置斷點和調試代碼?你如何運行應用程序?數據不會在多次運行之間持續存在。 –
它運行良好,我第一次運行它,所有的字符串都在數組中。但是,當我再次運行程序時,我以前輸入到數組中的字符串不在那裏。 應用程序應該在數組中存儲字符串。當我再次運行程序並向該數組添加更多字符串時,以前輸入的字符串和新輸入的字符串都應該在那裏。 – Mike95
如果您再次運行該程序,則完全不知道以前運行中設置的任何狀態。這就是你需要持久層的地方,比如數據庫。運行時的字符串只存儲在當前JVM的內存中,並在容器關閉時被丟棄。 –