创建一个对象数组

时间:2016-10-20 01:20:35

标签: java arrays file object

我对java很新,但我理解编程概念。我正在做一个交易游戏。我希望能够在.txt文件中列出我想要的每个项目并读取列表,为每个项目创建一个Item()对象的实例。我知道如何阅读输入,然后将它们排序成一个很难弄清楚的数组。

阵列是正确的方法吗?或者还有其他方法来处理我的商品信息吗?

public class Item {
    File itemList = new File("Items.txt");
    ArrayList<Item> Items = new ArrayList<>();

    String line = "";
    String name = "";
    int price = 0;
    int ID = 0;

    public void setItem (String theName, int thePrice, int theID)
    {
    name = theName;
    price = thePrice;
    ID = theID;
    }
    public void Initialize () throws FileNotFoundException
    {
        Scanner scan = new Scanner(itemList);
        do
        {
            do
            {

                line = scan.nextLine();
                while (!line.startsWith("#")) {line = scan.nextLine();}
                if (line.matches(".*\\d+.*"))
                {
                    price = Integer.parseInt(line);
                }else
                {
                    name = line;
                }
            }while(!line.equals(""));
            Items.add(new Item());
            ID++;
        }while (!line.equals("end"));
    }
}

1 个答案:

答案 0 :(得分:0)

有几种方法可以存储您的项目,也许最简单的方法是使用数组列表。

ArrayList<Items> items = new ArrayList<Items>();

假设您使用输入数据创建新项目:

/*This goes in a loop where you read in currentInputData*/
items.add(new Item(currentInputData));

有关操纵ArrayLists的更多信息,请参阅javadoc:https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html

相关问题