gpt4 book ai didi

java - ArrayList 不会添加超过一项

转载 作者:行者123 更新时间:2023-12-01 19:29:17 24 4
gpt4 key购买 nike

我正在尝试创建一个 String[] 的 ArrayList,但无法让它添加多个项目。最终我想从 ArrayList 中提取项目并将它们发送到 JTable。该程序有 5 个独立的类,但以下是此问题的适用代码:

    static JComboBox<String> foodChoice;
DefaultTableModel foodList;
static String[] newFood;
static List<String[]> foodData;
JTextField newFoodText, portionText, carbsText;

public Main() {
void createFood() {

String[] foodProperties = new String[3];
foodProperties[0] = newFoodText.getText();
foodProperties[1] = portionText.getText();
foodProperties[2] = carbsText.getText();
Main.createFood(foodProperties);
}

static void createFood(String[] foodArray) {
foodData = new ArrayList<String[]>();
foodData.add(foodArray);
foodChoice.addItem(foodArray[0]);
}

void addFoodToTable() {

String[] s = new String[3];
s = (String[]) foodData.get(foodChoice.getSelectedIndex());
System.out.println(foodData.get(0));
System.out.println(foodData.get(1));
}
单击按钮即可调用

addFoodToTable。所以我遇到的问题是(基于系统输出)我将获得指向 ArrayList 中第一个条目的指针地址,但随后出现空指针异常,表明当它尝试打印时它超出了长度 0 的范围第二个要安慰。这显然是在调用 createFood() 3 或四次以填充 foodData 后发生的。如果需要,我可以提供额外的代码,但将其全部放入这篇文章中实在太多了。谢谢!

最佳答案

每次调用 createFood 时都会清除 foodData 删除此行:

foodData = new ArrayList();

并将初始化移至静态级别,如下所示:

static JComboBox<String> foodChoice;
DefaultTableModel foodList;
static String[] newFood;
static List<String[]> foodData = new ArrayList<String[]>();
JTextField newFoodText, portionText, carbsText;

public Main() {
void createFood() {

String[] foodProperties = new String[3];
foodProperties[0] = newFoodText.getText();
foodProperties[1] = portionText.getText();
foodProperties[2] = carbsText.getText();
Main.createFood(foodProperties);
}

static void createFood(String[] foodArray) {
foodData.add(foodArray);
foodChoice.addItem(foodArray[0]);
}

void addFoodToTable() {

String[] s = new String[3];
s = (String[]) foodData.get(foodChoice.getSelectedIndex());
System.out.println(foodData.get(0));
System.out.println(foodData.get(1));
}

关于java - ArrayList<String[]> 不会添加超过一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60270809/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com