Java 如何从用户输入更改数组列表中的值?
我有一个arraylist,在我的鞋库课下面。我还有另一个名为Shoe的类,它有这个数组列表中变量的setter和getter 鞋类图书馆类Java 如何从用户输入更改数组列表中的值?,java,arrays,Java,Arrays,我有一个arraylist,在我的鞋库课下面。我还有另一个名为Shoe的类,它有这个数组列表中变量的setter和getter 鞋类图书馆类 public class ShoeLibrary { private ArrayList<Shoe> shoes; public ShoeLibrary() { shoes = new ArrayList<Shoe>(); shoes.add(new Shoe("Shoe 1", 100)); // the in
public class ShoeLibrary {
private ArrayList<Shoe> shoes;
public ShoeLibrary() {
shoes = new ArrayList<Shoe>();
shoes.add(new Shoe("Shoe 1", 100)); // the integer represents stock
shoes.add(new Shoe("Shoe 2", 200));
shoes.add(new Shoe("Shoe 3", 300));
}
公共类鞋库{
私人ArrayList鞋;
公共鞋库{
shoes=新阵列列表();
添加(新鞋(“鞋1”,100));//整数表示库存
鞋。添加(新鞋(“鞋2”,200));
鞋。添加(新鞋(“鞋3”,300));
}
在我的MainActivity GUI类中,我有一个输入对话框,它接受用户输入的整数值,然后将其添加到篮子中
我需要一种方法来更新编号(库存)当用户输入此值时,在数组列表中。我将如何执行此操作。我假设我的注释是正确的,并编写了一些基本代码来说明如何执行此操作。您需要更改此设置以适应您的情况,并从GUI中获取客户数据。您还需要执行错误检查
public class Sandbox { //opens class
public static void main(String[] args) {
ArrayList<Shoe>shoes = new ArrayList<Shoe>();
shoes.add(new Shoe("Shoe 1", 100)); // the integer represents stock
shoes.add(new Shoe("Shoe 2", 200));
shoes.add(new Shoe("Shoe 3", 300));
Shoe temp;
String shoeSelected = "Shoe 3"; // you need to use the customer's input here
int numSeleted = 20; // again, you need this data from the customer input
for (int i = 0; i < shoes.size(); i++) {
temp = shoes.get(i);
if(temp.name == shoeSelected) {
shoes.get(i).setQuantity(temp.quantity - numSeleted);
System.out.println(shoes.get(i).name);
System.out.println(shoes.get(i).quantity);
}
}
System.out.println("wait");
}
}
class Shoe {
String name;
int quantity;
public Shoe(String name, int quantity) {
this.name = name;
this.quantity = quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
公共类沙盒{//打开类
公共静态void main(字符串[]args){
ArrayListshoes=新的ArrayList();
添加(新鞋(“鞋1”,100));//整数表示库存
鞋。添加(新鞋(“鞋2”,200));
鞋。添加(新鞋(“鞋3”,300));
鞋温;
String shoeSelected=“Shoe 3”//您需要在此处使用客户的输入
int numSeleted=20;//同样,您需要来自客户输入的数据
对于(int i=0;i
Shoe 1是一种类型,100是数量吗?如果是这样,那么您希望从列表中获取鞋,然后在Shoe类中使用setter来更改数量。如果这是您所说的,那么我可以提供一些代码帮助。@ChrisSharp是的,这是正确的。下面的答案是否有帮助?或者您回答错了吗?@ChrisSharp是的,谢谢。如果答案是,你能把它标记为答案吗?为什么你要把arraylist和代码放在main方法中?因为我不知道你的类是如何设置的,也没有你的GUI界面。我把它放在那里是为了向你演示如何修改列表中的项目。调用和列表可以来自anywh嗯。