-2

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;
    }
}
learningbyexample
  • 1,527
  • 2
  • 21
  • 42

1 Answers1

0

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();

Christopher
  • 425
  • 3
  • 9
  • `StringBuilder` is recommend in this case instead of `StringBuffer`. In fact `StringBuffer` is very rarely needed. See the last paragraph of the description in its [javadoc](https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html) – janos Jun 17 '17 at 20:04