이전에 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()입니까? 또는 나는 이것을 할 수 없다?
두 가지 방법으로 구현하고 있습니다. 첫 번째 버전에서 인스턴스 변수를 배열로 가졌습니다. 지금은'ArrayList'를 사용하여 똑같은 일을하지 않으시겠습니까? –
'Collections.sort (shoppingList)'를 사용하여'List'를 정렬 할 수 있습니다. 게시 한 버블 정렬 코드를 사용하고 싶지 않습니다. 이것을 사용하려면'shoppingList.toArray (new ShoppingItem [shoppingList.size()])'를 사용하여 목록에서 배열을 가져올 수 있습니다. – Gray