gpt4 book ai didi

java - 从类对象创建 Array 或 ArrayList

转载 作者:行者123 更新时间:2023-12-01 08:10:38 25 4
gpt4 key购买 nike

我已经为此工作了一段时间,但似乎不太清楚如何将项目添加到 ArrayList。我想将 grocItem (应该是来自 for 循环的用户输入的 7 个 grocItems)添加到 grocList 的 ArrayList 中:

        public class ItemData{
public ItemData(String name, double cost, int priority){

Main.(ArrayList grocList).add(grocItem);

// Main.groclist.add(grocItem);



}
}

主类:

import java.util.*;


public class Main {

public static List<ItemData> itemData = new ArrayList<ItemData>();
public static void main(String[] args) {
int i=0;
//String name1;
//int priority1;
//double cost1;

String[] item = new String[7];

for (i=0; i<item.length; i++) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter item name " + i);
String name = keyboard.next();
Scanner keyboard2 = new Scanner(System.in);
System.out.println("Enter the price of item " + i);
double cost = keyboard2.nextDouble();
Scanner keyboard3 = new Scanner(System.in);
System.out.println("Enter Priority Number " + i);
int priority = keyboard3.nextInt();

ItemData grocItem = new ItemData(name, cost, priority);
}
//How do I add grocItem to an Array list of other grocItems (6 grocItems from user input array item)
Main.itemData.add(groclist);

}
}

最佳答案

更改代码,在循环内添加方法。

for (i=0; i<item.length; i++)  {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter item name " + i);
String name = keyboard.next();
Scanner keyboard2 = new Scanner(System.in);
System.out.println("Enter the price of item " + i);
double cost = keyboard2.nextDouble();
Scanner keyboard3 = new Scanner(System.in);
System.out.println("Enter Priority Number " + i);
int priority = keyboard3.nextInt();

ItemData grocItem = new ItemData(name, cost, priority);
itemData.add(grocItem ); // add here
}

关于java - 从类对象创建 Array 或 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17753691/

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