我正在开发一个程序,它将对象存储在LinkedList中,然后通过搜索所述对象的字段来搜索列表中的特定对象以匹配它们并创建价格,但我无法弄清楚如何实际完成此任务。我附上了代码片段,以了解我正在做的事情的基础,并且非常感谢任何帮助。
public class Database {
LinkedList<ProduceItem> list = new LinkedList<ProduceItem>();
public Database() throws FileNotFoundException{
String name = "PriceList.txt";
File file = new File(name); //Create file object
Scanner inputFile = new Scanner(file); //Create Scanner object to read from file
String line = null; //String for input
while(inputFile.hasNextLine()){ //While loop to sort through the file
line = inputFile.nextLine(); //Read line from file
if(line.charAt(0) == 'V'){
StringTokenizer tokenizer = new StringTokenizer(line, ",");
Vegtable veg = new Vegtable();
tokenizer.nextToken(); //Burn first token to eliminate identifier
veg.setCode(tokenizer.nextToken());
veg.setName(tokenizer.nextToken());
veg.setPrice(Float.parseFloat(tokenizer.nextToken()));
list.add(veg);
}
else{
StringTokenizer tokenizer = new StringTokenizer(line, ",");
Fruit fru = new Fruit();
tokenizer.nextToken();
fru.setCode(tokenizer.nextToken());
fru.setName(tokenizer.nextToken());
fru.setPrice(Float.parseFloat(tokenizer.nextToken()));
list.add(fru);
}
}
inputFile.close();
}
}
答案 0 :(得分:0)
你可以做这样的事情
for(ProduceItem item : list) {
if(item.name.equals(searchKey) {
//perform calculations or display to screen here
}
}