不知道如何将字符串添加到arraylist并使其粘贴

时间:2017-06-06 18:49:31

标签: java arrays arraylist

我是java的新手,我试图通过创建TestAddRemove程序来测试我学到的东西。从本质上讲,它应该让您选择两个阵列中的一个,并允许您添加公司名称,删除公司名称并读取您正在寻找的公司是否在其中一个阵列中。

我的主要问题是添加到数组部分。每次我使用Add类添加公司都可以,但是当我再次检查数组时,数组是空的。

主要问题 n:如何在主程序中向一个数组添加companyName并让它坚持下去?

这是我的代码:

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);
            }

其余代码用于删除和测试方法,一旦我了解如何添加companyName,我认为我可以理解。

这是Add Class:

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;
    }

}

对此的任何帮助都会很棒,谢谢和欢呼!

1 个答案:

答案 0 :(得分:3)

运行Java应用程序会生成一个新的JVM容器。这样的容器有自己的内存,在其中存储程序的状态。当应用程序终止时,JVM将关闭并丢弃所有现有状态。当您第二次运行该程序时,它在不同的JVM中运行,完全不知道以前的任何运行。

关于您的问题,要访问先前运行中创建的公司列表,您需要向应用程序添加某种持久层,例如数据库或您可以在其中存储公司的文件

最简单的解决方案是将列表存储在文本文件中,其中每行代表一个公司,在应用程序关闭之前,然后在应用程序启动时再次加载文件。