0

I am a beginner in Java and I have tried to implement a tail and I've made all the others methods, but at the toString() method, the program won't work. Here's my attempt:

class Tail {
    int n;
    Node prim;
    Node last;

    class Node {
        Node next;
        int info;
    }

    Tail() {
        prim = null;
        last = null;
        n = 0;
    }

    public String toString() {
        StringBuilder s = new StringBuilder();
        for (int info : this)
            s.append(info + " ");
        return s.toString();
    //return this.info.toString();
    }

It gives an error if I try to return this.info.toString() . I would appreciate any advice or solution for solving this problem, thanks

  • 'info' is a primitive int. you cannot call 'toString()' on primitive types – usha Oct 24 '16 at 17:06
  • Tail doesn't implement `Iterable`, and isn't an array, so you can't use it in am enhanced for loop like that. – Andy Turner Oct 24 '16 at 17:08
  • Where are the info objects coming from? If you want to use the "for (int info : this)" construction, then Tail needs to implement Iterable – dantiston Oct 24 '16 at 17:09

1 Answers1

0

your code below is incorrect:

for (int info : this)
s.append(info + " ");

'this' refers to the current instance of Tail - which is all of its properties (n, prim, and last) & methods. If you want to overwrite toString() using the three properties refer to this answer for how to write your for loop:

How to get the fields in an Object via reflection?

Community
  • 1
  • 1
donlys
  • 440
  • 6
  • 13