1

In python, to print

******
 *****
  ****
   ***
    **
     *

     *
    **
   ***
  ****
 *****
******

We would code the following:

for e in range (11,0,-1):
    print((11-e) * ' ' + e * '*')

print ('')
for g in range (11,0,-1):
    print(g * ' ' + (11-g) * '*')

My question is, can this be done in Java as well? Java doesn't let you multiply a string (int) times, e.g. 4 * " ", so how can we implement this in java?

huge important edit: guys sorry I screwed up the example output up there. i.e. I drew the asterisk triangle wrong. I redid the asterisk drawing. but i'm going to close this question and re-post it since this one's not gaining much activity.

3 Answers3

2

I haven't used Java in a while so I'm sorry if this code is rusty

but can't you do something like:

public int printAsterisks(int numOfAsterisks){
  if(numOfAsteriks == 0)
    return 0;
  for(int i = numOfAsteriks;i > 0 ; i--){
    System.out.print("*");

  }
  System.out.println("")//Without this all asteriks would be printed on one line

  return printAsteriks(--numOfAsterisks); //Recursively finish printing the asteriks 
}

I personally prefer recursion whenever possible but there's many different right answers. I'll be here if it doesn't work the first tiem

Dominic
  • 107
  • 1
  • 10
1
    String str = "******";

    for (int i = 5; i >= 0; i--) {
        System.out.println(str=str.substring(0, i));
    }
    for (int i = 0; i <= 5; i++) {

        System.out.println(str+= "*");
    }
0

You can write that in python with one loop because the formular for that pattern is y = abs(x - 5) where y is the number of stars and x is the iteration number in the loop (starting from zero). So continuing with that to Java:

class Demo {
    public static void main(String[] args) {
        for(int i=0; i<13; i++) {
            int repeats = Math.abs(i - 5); // formula: y = abs(x - 5)
            while (repeats-- > 0)
                System.out.print("*");
            System.out.println("");
        }
    }
}
dopstar
  • 1,478
  • 10
  • 20