gpt4 book ai didi

java - 更新 Java 中的数组列表方法

转载 作者:行者123 更新时间:2023-12-04 08:32:35 25 4
gpt4 key购买 nike

关闭。这个问题需要debugging details .它目前不接受答案。












想改善这个问题吗?更新问题,使其成为 on-topic对于堆栈溢出。

9 个月前关闭。




Improve this question




我试图制作一个类似于这个 removeMenu 方法的代码,但我想制作另一种方法来更新我订购的菜单中产品的数量。
餐厅 Controller 代码:

Menu coffee = new Menu("Coffee", 30);
Menu icedTea = new Menu("Iced Tea", 50);
Menu hotChoco = new Menu("Hot Chocolate", 30);
/*
constructor ommittet.
*/
private ArrayList<Menu> menulist;

public void removeMenu(Menu menumodel) {
for (Menu temp : menulist) {
if (temp.equals(menumodel)) {
menulist.remove(temp);
break;
}
}
}

public void updateMenu(int updateQuant) {
//menulist.set(3, updateQuant);
}
}

}
餐厅类
RestaurantController controller1 = new RestaurantController();
private void DeleteProductActionPerformed(java.awt.event.ActionEvent evt) {
selectedProduct = controller1.getMenulist().get(JTableOrderReceived.getSelectedRow());
if (selectedProduct != null) {
int ans = JOptionPane.showConfirmDialog(this, "The selected product will be removed! ", "DELETE PRODUCT", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (ans == JOptionPane.YES_OPTION) {
controller1.removeMenu(selectedProduct);
refTable();
}
}
}
private void UpdateProduct(java.awt.event.ActionEvent evt) {
selectedProduct controller1.getMenulist().get(JTableOrderReceived.getSelectedRow());
if (selectedProduct != null) {
int parseQuant = (int) selectedProduct.getQuantity();
String uQuant = JOptionPane.showInputDialog(this, "Update quantity " + selectedProduct.getItemName() + "\nPrice: " + selectedProduct.getPrice() + "\nCurrent order: " + parseQuant);
int nQuant = Integer.parseInt(uQuant);
controller1.updateMenu(nQuant);
refTable();
}
}
我在餐厅 Controller 类中的 updateMenu 方法上遇到问题,有人可以帮忙吗?

最佳答案

首先,您必须阅读有关数组列表的基本用法。
您的删除实现有一个错误的假设:

public void removeMenu(Menu menumodel) {
for (Menu temp : menulist) {
if (temp.equals(menumodel)) {
menulist.remove(temp);
break;
}
}
}
等于:
public void removeMenu(Menu menumodel) {
menulist.remove(temp);
}
Arraylist 的实现将使用 hashCode() 和 equals() 来识别 arraylist 中的正确对象并为您删除它。因此,您不必遍历数组。
另请参阅如何从迭代列表中删除对象: Calling remove in foreach loop in Java
要更新数组列表中的对象,您首先必须检索该对象,然后再更新它。这是因为 arrayslist 存储对对象的引用而不是副本。
因此,您的更新方法必须确定要更新的对象,然后相应地设置数量:
在我的示例中,您通过域名识别对象:这里是“菜单名称”,例如。咖啡。
public void updateMenu(int updateQuant, String name) {
for (Menu temp : menulist) {
if (temp.getName().equals(name)) {
temp.setQuant(updateQuant);
break;
}
}
}
此外,您已经在 UpdateProduct EventListener 中获得了正确的对象:
selectedProduct
这是通过 updateMenu 方法找到的相同对象。因此你可以调用
selectedProduct.setQuant(...) 
在这里,它也会更新数组列表。这是因为在不同的变量上存在对对象的引用。两者都引用同一个对象。

关于java - 更新 Java 中的数组列表方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64953026/

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