Question

I have to make a program that add Strings to each other as many as argument in method says. Program is not working and i dont know why. Thanks for your time. The problem is in the main in ap.append(" ma kota", 3).append( " i psa", 2);. I cant make changes to the main.

public class Appender {
    private StringBuffer sb;

    public Appender(){
        sb = new StringBuffer();
    }

    public Appender(String s){
        sb = new StringBuffer(s);
    }

    public StringBuffer append(String str, int n) {
        while(n > 0){
            sb.append(str);
            n--;
        }
        return sb;
    }

    public String toString(){
        String s = sb.toString();
        return "" + s;
    }
}

And this is my main :

public class Main {
    public static void main(String[] args) {
        Appender ap = new Appender("Ala");
        ap.append(" ma kota", 3).append( " i psa", 2);
        System.out.println(ap);
        ap.append(" ojej", 3);
        System.out.println(ap);
    }
}
Was it helpful?

Solution 2

public StringBuffer append(String str, int n) {
    while(n > 0){
        sb.append(str);
        n--;
    }
    return sb;
}

should change to

public Appender append(String str, int n) {
    while(n > 0){
        sb.append(str);
        n--;
    }
    return this;
}

because StringBuffer does not have method append(String s, int n)

OTHER TIPS

The append(String appended, int n) method belongs to Appender, not StringBuilder so you have to return it, instead of the sb

public class HelloWorld{

     public static void main(String []args){
        System.out.println("Hello World");
         Appender ap = new Appender("Ala");
        ap.append(" ma kota", 3).append( " i psa", 2);
        System.out.println(ap);
        ap.append(" ojej", 3);
        System.out.println(ap);
     }
     public static class Appender {
        private StringBuffer sb;

        public Appender(){
            sb = new StringBuffer();
        }

        public Appender(String s){
            sb = new StringBuffer(s);
        }

        public Appender append(String str, int n) {
            while(n > 0){
                sb.append(str);
                n--;
            }
            return this;
        }

        public String toString(){
            return sb.toString();
        }

    }
}

You should return this(current object) from com.test.FunPrime.Appender.append(String, int)

like

public Appender append(String str, int n) {
        while(n > 0){
            sb.append(str);
            n--;
        }
        return this;
    }

You can also use org.apache.commons.lang.StringUtils#repeat for this.

For example repeat for 5 times:

String result = StringUtils.repeat("repeat this string", ", ", 5);

The version without the second argument (the separator ", ") is also available.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top