我正在为初学者的Java课程制作一个卡路里计数器程序,我真的无法掌握ArrayList
字的方式。基本上,该计划由七个类组成:Food
,FoodEaten
,Activity
,ActivityPerformed
,Tracker
,TrackerGUI
和{{1 }}
这些是GUI的以下命令:
添加食物:创建一个新对象并将其放入foodBase TrackerApp
;
ArrayList
追踪食物:检查食物是否在食物基地public void addFood(String foodName, double calories) {
foodBase.add(new Food(foodName, calories));
}
。如果是,则将对象添加到foodEaten ArrayList
Arraylist
打印报告:打印public Food getFood(String name){
for(int i = 0; i < foodBase.size(); i++) {
if(foodBase.get(i).getName().equals(name))
return foodBase.get(i)
}
}
public void trackFood(String foodName, double servings) {
Food f = getFood(name);
foodEaten.add(new FoodEaten(Food f, calories));
}
数组
FoodEaten
我有三个public String printReport() {
String lifestyleReport = "";
lifestyleReport +=(Food Consumed: \n");
lifestyleReport += getFoodEaten();
lifestyleReport +=(Total Calories Consumed: this.caloriesGained + kcal \n");
}
:foodField,caloriesField,quantityField
JTextFields
以及以下内容:
private JTextField foodField;
private JTextField caloriesField;
private JTextField quantityField;
和
public class Food implements ActionListener {
public void actionPerformed (ActionEvent ae) {
double calories = Double.parseDouble(caloriesField.getText().replaceAll(",",""));
String newFood = activityField.getText();
if(calories < 0) {
textArea.append("Calories cannot be negative. \n\n");
}
else {
tracking.addFood(newFood, calories);
textArea.append(newFood + " with " + calories + " calories added to database! \n");
}
}
}
现在很明显我做错了什么(因为这一切都没有用)。
如何让一切正常?