How to make an asterisk triangle in java

Asked

Viewed 1,247 times

0

I want to get the following output:

n:4

+

++

+++

++++

That is, I insert an "n" and I will get a kind of triangle in which the base corresponds to a number of asterisks that is requested by input. I made the following code but this just hits the number of lines and not elements per line:

System .out . println("Indique um número inteiro positivo:");
    int n = scanner.nextInt();
    int triangulos = 0;
    int i ;
    for(i=0; triangulos < n ; triangulos++)
    {
        System.out.println("n:" + n);
        System.out.println("*");
    }
  • The triangle is half over. It doesn’t have to be a full triangle?

  • Another for to generate the asterisks

  • 2

    Your asterisks have missing legs

1 answer

1


System.out.println("Indique um número inteiro positivo:");
int n = scanner.nextInt();
System.out.println("n: " + n);
for(int i = 0; i <= n ; i++) {
    String out = "";
    for (int j = 0; j < i; j++) {
        out.concat("*");
    }
    System.out.println(out);
}

In the first iteration we cover the n

On the second we add "*" i times as we iterate n

  • No append in String class.

  • Sorry, my error, append() would be a method of the Stringbuilder class, the equivalent of String is the Concat method()

  • Yes in fact in Java 7 does not exist. As I do not know which version q he is using. I admit q is 8.

  • Just use +(out+="*") that makes it compatible with any version. Or adapt directly to Stringbuilder

  • Yes indeed, but when we use the + operator in the compilation there is the automatic exchange for Stringbuilder. In a loop if we use this operator we will be losing performance.

  • https://answall.com/questions/71517/concatenar-strings-em-java-loops-stringbuilder-ou

  • 1

    There is no difference in performances that are meaningful, for a code so simple that it is necessary to use stringbuilder. It becomes a resource awakening until.

  • In reality with the + operator at each iteration a new Stringbuilder object will be created and concatenated to the initial string. As seen on: https://stackoverflow.com/questions/32909369/using-stringbuilder-with-for-loop

  • Another interesting link: http://www.pellegrino.link/2015/08/22/string-concatenation-with-java-8.html

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.