0

我应该编写一个在礼物注册表中创建条目的程序。用户可以输入任意数量的礼品以及可以购买的商店。一旦用户表示希望停止输入新商品,将显示所有礼品商品和商店的摘要。

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: ");



        }
 }

我真的不知道怎么

4

4 回答 4

1

1) 您不能将“watch”和“Swatch”插入为int

2) 为什么使用Arrays, 什么时候 aList更好?

编辑:

java.util.List: 接口。

java.util.ArrayList:适合您的情况的最佳实施。

用法:

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

等等

在 for each 循环中阅读它:

for (String currentValue : list)
   System.out.println(currentValue);
于 2012-12-05T21:54:27.887 回答
0

数组的长度是固定的,因此由于无限长度的性质,您不能使用数组。您应该使用一个列表,在您的情况下是一个 ArrayList。

http://docs.oracle.com/javase/6/docs/api/java/util/List.html列表文档 http://docs.oracle.com/javase/6/docs/api/java/util/ ArrayList的 ArrayList.html 文档

于 2012-12-05T21:54:19.380 回答
0

您可以使用 ArrayList,其大小是动态自动调整的。

于 2012-12-05T21:56:22.213 回答
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 - 当分配的内存量被填充时动态调整大小,我强烈建议使用它:

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

如果您也询问它们,代码还有其他几个小问题。然而,这是代码的主要问题。

于 2012-12-05T22:01:43.723 回答