How do I concatenate a String to return to main in JAVA

I am trying to return a string so that it is not printed in the function but rather in the main class.

I have tried to concatenate the string on every character that comes out so that the string keeps growing depending on the inputted number.

public class Main {

    public static void main(String[] args) {
        Diamond print = new Diamond();
        output = print.print(5);
        System.out.print(output);
    }
}
class Diamond {
    public static String print(int n) {
        String concat = "";

        if(!(n % 2 == 0)) {
            for (int i = 1; i < n; i += 2) {
                for (int k = n; k >= i; k -= 2) {
                    System.out.print(" ");
                    concat = concat.(" ");//what i am trying to do :(
                }
                for (int j = 1; j <= i; j++) {
                    System.out.print("*");
                    concat = concat.("*");
                }
                concat = concat.("\n");
                System.out.println();
            }// end loop

            for (int i = 1; i <= n; i += 2) {
                for (int k = 1; k <= i; k += 2) {
                    System.out.print(" ");
                }
                for (int j = n; j >= i; j--) {
                    System.out.print("*");
                }
                System.out.println();
            }// end loop
        }
        return concat;
    }
}

1 answer

  • answered 2017-06-17 19:49 Christopher

    use the concat() method

    String str = "";
    str = str.concat("blabla");
    

    but since your variable name is concat then do like this:

    String concat = "";
    concat = concat.concat("blabla");
    

    however, using StringBuffer is better..

    StringBuffer sb = new StringBuffer();
    
    sb.append("blabla");
    

    then.. for the output, return the string by writing: sb.toString();