0

I am working on a section of code for an assignment I am doing atm, and I am completely stuck with 1 little bit.

I need to convert the contents of an array list into a string, or the form of a string, which will be able to be imput into toString() in order for it to be printed to the screen.

public String toString(){
    String full;
    full = (this.name + this.address + "\n" + "Student Number = " + this.studentId);
    for (int i = 0; i < cs.size(); i++) {
        full.append(cs[i]);
    return full;

The piece of above code is where i attempt to combine 3 varaibles and the contents of an array list into a single string with formatting.

Unfortunatly it creates an error "The type of the expression must be an array type but it resolved to ArrayList"

Thanks for any help.

Jake

4

6 に答える 6

5

cs is array list, so you have to do get operation, not [] (which is for array access)

It should be like:

full.append(cs.get(i));

Not

full.append(cs[i]);

EDIT: As assylis said, full should be StringBuilder not just String, because String doesn't support append() method.

StringBuilder full = new StringBuilder();

于 2012-09-11T14:21:05.383 に答える
2

You are attempting to access an ArrayList as though it is a primitive array (using the square brackets around the index). Try using the get(int index) method instead.

i.e.,

cs.get(i);
于 2012-09-11T14:22:14.683 に答える
2

Apache Commons StringUtils has different varieties of join() methods that mean you don't have to write this yourself. You can specify the separator and even the prefix/suffix.

I would recommend you look at Apache Commons, not just for this but for lots of other useful stuff.

于 2012-09-11T14:26:12.130 に答える
0

You cannot index an ArrayList like an array, you need the get(index) method. Even better, use the enhanced for loop, since it's not recommended to index over a list, as the implementation may change to LinkedList.

I also suggest using a StringBuilder for efficiency:

public String toString() {
    StringBuilder full = new StringBuilder();
    full.append(this.name);
    full.append(this.address);
    full.append("\n");
    full.append("Student Number = ");
    full.append(this.studentId);
    for (String s: cs)
        full.append(s);
    return full.toString();
}
于 2012-09-11T14:23:52.823 に答える
0

Just use "cs.get(i)" in place of "cs[i]". as cs is an ArrayList not an Array.

and also use full = full + cs.get(i); and not full.append(cs.get(i));

as String type dont have a append method.

于 2012-09-11T14:32:32.097 に答える
0

Just a note, since you don't put any spacers between each element of the ArrayList it might be unreadable. Consider using Guava's Joiner class.

So instead of

 for (...)
   s.append(y);

if would be

   a.append(Joiner.on(" ").join(yourList));

The Joiner is also more efficient than the for loop since it uses a StringBuilder internally.

于 2012-09-11T14:49:38.197 に答える