-1

我目前正在制作一个购物商店应用程序,我有 6 个课程。1 用于定义商店中产品字段的产品,另一个用于购物篮,一个用于 GUI,其余用于侦听器。

我需要能够运行一个通过数组列表运行并在其上运行 to.String 方法并将其作为字符串返回的方法。这是我目前所拥有的,

private ArrayList<OrderItem> basket = new ArrayList<OrderItem>();

public String createArrayText () {
    for (int i = 0; i < OrderItem.size(); i++){
        if (i == OrderItem.size() - 1){
            return ordersText ;
        }
    }
}

ordersText是我在购物车类顶部创建的变量。

这是我第一次开始使用它,但是我在 .size 上遇到错误,并且显然缺少一些关键组件。

额外的一件事是创建的每个项目都添加到数组列表中,每个项目都有一个唯一的订单号。

4

2 回答 2

2
Arrays.toString(basket);

那是你要找的吗?如果没有,您需要更好地解释一下。

于 2013-08-15T01:13:37.163 回答
0

You generally speaking loop over a List like this (Java 7, it's called enhanced for loop):

for (TYPE TEMP_NAME : COLLECTION) {
}

That's the overall syntax. TYPE is the type of item in the list, yours are Object's in the given code. TEMP_NAME is the temporary name you want each entry to be referred as. COLLECTION is the list/array/stack/queue or other Collection.

Concretely:

for (Object o : basket) {
    // if basket contains 10 entries the line will run 10 times. each new run contains a different object with name o
}

Normally when building strings it's preferred to use StringBuilder. We can skip that as it's "only" performance that you gain from it. We'll do it with a regular String. So:

  1. Create an empty string that will get longer and longer
  2. Loop the collection/array/list
  3. Append each object's .toString() to the string from 1)

e.g.

String myReturnString = "";
for (Object o : basket) {
    myReturnString = myReturnString + " // " + o.toString();
}
return myReturnString;

Notes:

Your loop with an index is fine. You can do it that way too, if you want to.

The line of code that appends the string has a " // " separator between each entry. You can pick whatever you like. You can also simplify it to be myReturnString += " // " + o.toString();

于 2013-08-15T01:17:59.737 回答