2011-11-06 90 views
2

以前创建了一个名为ShoppingList的shoppingItem数组。每个购物项目由用户输入并被询问名称,优先级,价格和数量。现在我试图用数组列表来做同样的事情,但我遇到了麻烦。带用户输入的ArrayList

这是我的主要当我有阵列

public static void main(String[] args) { 
    ShoppingList go = new ShoppingList(); 
    go.getElement(); 
    go.Sort(); 
    System.out.println("hello"); 
    go.displayResults(); 
} 

和getElement方法是这样的:

public void getElement(){ 
    System.out.println("You can add seven items to purchase when prompted "); 
    shoppingList = new ShoppingItem[numItems]; //creation of new array object 
    for (int i = 0; i<= numItems - 1; i++) { 
     shoppingList[i] = new ShoppingItem(); //shopping item objects created 
     System.out.println("Enter data for the shopping item " + i); 
     shoppingList[i].readInput(); 
     System.out.println(); 
    } 
} 

现在用ArrayList的,我只是失去了。

public static void main(String[] args) { 
    ArrayList<ShoppingItem>ShoppingList = new ArrayList<ShoppingItem>(); 
    ShoppingList //how do i call the getElement which then calls readInput()? 
} 

谢谢!我现在完全明白。我用了一个以前冒泡进行优先排序项目:

public void Sort(){ 
    boolean swapped = true; 
    int j = 0; 
    ShoppingItem tmp; 
    while (swapped) { 
     swapped = false; 
     j++; 
     for(int i = 0; i < shoppingList.length - j; i++) { 
      if (shoppingList[i].getItemPriority() > shoppingList[i+1].getItemPriority()) { 
       tmp = shoppingList[i]; 
       shoppingList[i] = shoppingList[i+1]; 
       shoppingList[i + 1] = tmp; 
       swapped = true; 
      } 
     } 
    } 
} 

我仍然可以使用这种方法,对吧?只是某些事情会改变,例如.. .length会是.size()?或者我无法做到这一点?

+0

您正在以两种不同的方式实施它;在第一个版本中,你有一个实例变量作为数组 - 为什么现在不要只用'ArrayList'做同样的事情? –

+0

您可以使用'Collections.sort(shoppingList)'对'List'进行排序。你不想使用你发布的冒泡排序代码。如果你想使用它,那么你可以使用'shoppingList.toArray(new ShoppingItem [shoppingList.size()])'从列表中获取数组。 – Gray

回答

0

ArrayList的工作原理与数组类似,但动态调整大小。你可以使用someArrayList.get(2)来代替someArray [2]来获取元素,并且添加元素(到数组列表的末尾),只需调用someArrayList.add(newElementHere)即可。所以我改变了你的代码(只有1个方法),它创建了一个名为shoppingList(你有这个部分)的ShoppingItem列表,然后它为7个项目执行for循环。每次创建一个ShoppingItem的新实例时,都会对其执行readInput方法,然后将其添加到shoppingList的末尾。我会考虑创建一个名为ShoppingList的新类,它封装了ArrayList并为您提供调用的方法(如askForItems(),sort(),display()等),但下面的代码应该让您开始有希望。

public static void main(String[] args) 
{ 
    ArrayList<ShoppingItem> shoppingList = new ArrayList<ShoppingItem>(); 

    System.out.println("You can add seven items to purchase when prompted "); 
    for (int i = 0; i <7; i++) { 
     ShoppingItem item = new ShoppingItem(); //shopping item objects created 
     System.out.println("Enter data for the shopping item " + i); 
     item.readInput(); 
     shoppingList.add(item); 
     System.out.println(); 
    } 
}