StringBuilder cannot be converted to String

Tag: java , string , list , arraylist , stringbuilder Author: qingqing520521 Date: 2014-04-23

I have this startup of attribute point

List<Point2D> point = new ArrayList<>();

and when I made this method to test the code and test the calculation and drawing of geometric figures through the site http://www.wolframalpha.com/input/?i=listplot

public String wolfram() {
        String s = "http://www.wolframalpha.com/input/?i=listplot[";
        int i = 0;
        for (int len = point.size(); i < len; i++) {

               //ERROR is here
           s = (new StringBuilder()).append(s).append(point.get(i)).append(i != len 1 ? "," : "").toString();
        }

        s = (new StringBuilder()).append(s).append(",").append(point.get(0)).append("]").toString();
        return s;
    }

and I have error, in this part -> ERROR: Incompatible types: StringBuilder cannot be converted to String

s = (new StringBuilder()).append(s).append(point.get(i)).append(i != len 1 ? "," : "").toString();
Please split up those kind of statements over multiple lines, reusing a StringBuilder variable. Then you can debug, and get readable code as well.
.append(i != len 1 ? "," : "") this is not valid code
Can you describe what this code is suppose do to? Do you realize that each time your loop executes you are creating new StringBuilder?
Is by any chance i != len 1 attempt to test if i is different than len AND 1?
Actions like changing title to describe problem not related with question will not help your situations. Also downvoters are most probably no longer here so your posts will not reach them.

Best Answer

There are several problems with this code, the first being that it doesn't compile and the compiler error message is different than the one reported - shame on you! (It's a parse error, not a type error.)

Secondly, it is abusing StringBuilder. Consider the following code which uses the same StringBuilder object, appending to it numerous times, until a string is obtained at the very end.

public String wolfram() {
    StringBuilder sb = new StringBuilder();
    sb.append("http://www.wolframalpha.com/input/?i=listplot")
      .append("["); // for uniformity
    // note this swapped out, per convention
    int len = point.size();
    // logic fix to loop [1, len) instead of [0, len) ..
    for (int i = 1; i < len; i++) {
       sb.append(point.get(i))
         .append(i != 1 ? "," : ""); // fixed parse error
    }
    // .. so we won't duplicate point 0
    sb.append(",")
      .append(point.get(0))
      .append("]");
    return sb.toString;
}