2017-06-06 21 views
0

我是新來的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; 
    } 

} 

任何幫助將是真棒,感謝和歡呼聲!

+0

提供的代碼似乎工作正常。你有沒有嘗試設置斷點和調試代碼?你如何運行應用程序?數據不會在多次運行之間持續存在。 –

+0

它運行良好,我第一次運行它,所有的字符串都在數組中。但是,當我再次運行程序時,我以前輸入到數組中的字符串不在那裏。 應用程序應該在數組中存儲字符串。當我再次運行程序並向該數組添加更多字符串時,以前輸入的字符串和新輸入的字符串都應該在那裏。 – Mike95

+1

如果您再次運行該程序,則完全不知道以前運行中設置的任何狀態。這就是你需要持久層的地方,比如數據庫。運行時的字符串只存儲在當前JVM的內存中,並在容器關閉時被丟棄。 –

回答

3

運行Java應用程序會產生一個新的JVM容器。這樣一個容器有它自己的內存,它爲你的程序存儲狀態。當應用程序終止時,JVM關閉並放棄所有現有狀態。當您第二次運行該程序時,它將在不同的JVM中運行,但完全不瞭解之前的運行情況。

關於您的問題,要訪問上一次運行中創建的公司列表,您需要爲您的應用程序添加某種持久層,如數據庫或可存儲公司的文件。

最簡單的解決辦法是將列表存儲在一個文本文件,其中每一行代表一個公司,在應用程序關閉前,然後在應用程序啓動時再加載該文件。

+0

好的,我明白了。所以它運行該程序時不考慮任何以前的運行。感謝盧西亞諾,感謝答案。 – Mike95

相關問題