【发布时间】:2026-01-05 02:35:01
【问题描述】:
我对 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"));
}
}
【问题讨论】:
-
你可以为你的 Item 对象寻找一个数组。读取输入后,您必须将值设置到新 Item 对象的变量中并将其附加到数组中。
-
Java 方法和变量名(按照惯例)以小写字母开头。此外,您的
Initialize方法可能应该是static,Items列表和itemList变量也应该如此。