2011-11-06 2 views
2

이전에 ShoppingList라는 shoppingItems 배열이 생성되었습니다. 각 쇼핑 항목은 사용자가 입력하고 이름, 우선 순위, 가격 및 수량을 묻습니다. 이제 나는 arraylist와 같은 일을하려고 노력하고 있지만 문제가 있습니다. 내가 배열사용자 입력이있는 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()? 
} 

고맙습니다! 나는 지금 그것을 완전히 이해한다. 이전에 항목을 우선 순위별로 정렬하기 위해 이전에 bubblesort를 사용했습니다.

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; 
      } 
     } 
    } 
} 

이 방법을 사용할 수 있습니까? 예를 들어 어떤 것들은 바뀔 것입니다. 길이는 .size()입니까? 또는 나는 이것을 할 수 없다?

+0

두 가지 방법으로 구현하고 있습니다. 첫 번째 버전에서 인스턴스 변수를 배열로 가졌습니다. 지금은'ArrayList'를 사용하여 똑같은 일을하지 않으시겠습니까? –

+0

'Collections.sort (shoppingList)'를 사용하여'List'를 정렬 할 수 있습니다. 게시 한 버블 정렬 코드를 사용하고 싶지 않습니다. 이것을 사용하려면'shoppingList.toArray (new ShoppingItem [shoppingList.size()])'를 사용하여 목록에서 배열을 가져올 수 있습니다. – Gray

답변

0

ArrayList는 배열처럼 작동하지만 동적으로 크기가 조정됩니다. someArray [2] 대신에 요소를 얻으려면 someArrayList.get (2)를 사용하고 요소를 추가하려면 (array list 끝에) someArrayList.add (newElementHere)를 호출하면됩니다. 그래서 나는 shoppingList라는 ShoppingItems 목록을 만드는 코드를 (단 하나의 메소드로) 변경했다.이 부분은 7 개 항목에 대한 for 루프를 수행한다. ShoppingItem의 새 인스턴스를 만들 때마다 해당 인스턴스에 대해 readInput 메서드를 수행 한 다음 shoppingList의 끝에 추가합니다. ArrayList를 캡슐화하고 (예 : askForItems(), sort(), display() 등) 호출 할 수있는 메소드를 제공하는 ShoppingList라는 새로운 클래스를 만드는 것을 고려해 볼 수 있습니다.

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(); 
    } 
} 
관련 문제