2012-12-05 19 views
0

我應該編寫一個程序,在禮品註冊表中創建條目。用戶可以輸入所需的禮物和可以購買的商店。一旦用戶表達希望停止輸入新項目,將顯示所有禮品項目&商店的摘要。我的Array程序

Below is a sample output 
Do you wish to make a gift registry list? (y/n): y 
Enter item: watch 
Enter store: Swatch 
Any more items? (y/n): y 
Enter item: ballpen 
Enter store: National Bookstore 
Any more items? (y/n): n 

Gift Registry: 
watch - Swatch 
ballpen - National Boo 

如果我沒有弄錯,我應該使用這個程序的數組?是否可以有一個依賴於計數器的數組長度(用戶輸入的次數)?

到目前爲止,這些都是我的代碼:

package arrays; 
import java.util.*; 
import java.util.List; 
import java.util.ArrayList; 

public class GiftRegistry 
{ 
    public static void main (String[] args) 
    { 
     Scanner input = new Scanner(System.in); 

     String choice; 

     // Declare array num 
     ArrayList<String> items = new ArrayList<String>(); 
     ArrayList<String> stores = new ArrayList<String>(); 

     items.add(items); 
     stores.add(stores); 


     System.out.print("Do you wish to make a gift registry list? (y/n):"); 
     choice = input.nextLine(); 

     while (choice.charAt(0) != 'n') 
     { 
      System.out.print("Enter item: "); 
      items.add(items) = input.nextInt(); 

      System.out.print("Enter store: "); 
      stores.add(stores) = input.nextInt(); 


      System.out.print("Any more items? (y/n):"); 
      choice = input.nextLine(); 
     } 

     System.out.println("Gift regisrty: "); 



     } 
} 

我真的不知道

+1

你正朝着一個好問題的正確方向發展。你解釋了你正在做的事情,並且你已經表現出努力來自己解決它,這是一件非常好的事情。但是你缺少**的描述到底是什麼問題?** – amit

+0

也許嘗試http://codereview.stackexchange.com/ –

+1

代碼不會編譯,因爲在聲明它之前使用'ctr'。對於動態增長的列表,使用'java.util.List'實現。 – jlordo

回答

1

1)您不能插入 「看」 和 「樣品」 爲int文件;

2)爲什麼使用Arrays,當List更好?

編輯:

java.util.List:接口。

java.util.ArrayList:您的案例的最佳實施。

用法:

List<String> list = new ArrayList<String>(); 
list.add("myFirstString"); 
list.add("mySecondString"); 

爲了讀取它在每個循環:

for (String currentValue : list) 
    System.out.println(currentValue); 
+0

顯然我不知道如何使用列表。 :( –

+0

@CeraKik什麼使用?@_Andrea給出了一個簡短的代碼片段也應該有幫助 – exexzian

+0

@sansix我已經發布片段後,他寫了評論...看看編輯部分:) –

0

可以使用ArrayList中,尺寸的動態和自動調整。

0

你是,你應該使用數組的想法正確的 - 但是,Java的標準陣列類型不動態調整 - 換句話說,在這裏:

int[] item = new int[ctr+1]; 
    int[] store = new int[ctr+1]; 

你正在創建到數組對象的引用尺寸1.但當你叫

ctr++; 

你是不是影響了數組的大小 - 你正在影響與該整數CTR,當您使用初始化新的陣列,相關的價值,並不會自動將它與數組關聯。

如果你還想使用原始數組,那麼當所需數量的禮物大於數組的大小時,你必須創建一個新的數組 - 順便說一下,你必須將項目存儲爲字符串

//If the array 'item' is full.... 
String [] oldItemArray = item; 

//You can increase by 1 or more, to add more empty slots 
String [] newItemArray = new String[oldItemArray.length + 1]; 
for (int i = 0; i < newItemArray.length; i++){ 
//...Put each item from the old array into the new one. 
} 
item = newItemArray; 

Java包含針對這些情況一個類型的數據結構,因爲它是如此普遍 - ArrayList中 - 當分配的內存量fillled,我會強烈建議使用它可動態調整:

ArrayList<String> items = new ArrayList<String>(); 
ArrayList<String> stores = new ArrayList<String>(); 
... 
... 
items.add(enteredItem); 
stores.add(storedItem); 

如果您也在詢問有關代碼的其他幾個小問題,請參閱代碼。然而,這是代碼的主要問題。