Answer:
public class StarPattern {
public static final int MAX_ROWS = 7;
public static void main(String []args){
for (int row = 1; row <= MAX_ROWS; row++) {
int numOfSpaces = getNumberOfSpaces(row);
int numOfStars = MAX_ROWS - (getNumberOfSpaces(row) * 2);
String spaces = printSpaces(numOfSpaces);
String stars = printStars(numOfStars);
System.out.println(spaces + stars);
}
}
public static int getNumberOfSpaces(int row) {
int rowOffset = (MAX_ROWS / 2) + 1;
return Math.abs(row-rowOffset);
}
public static String printSpaces(int num) {
String result = "";
for (int i = 0; i < num; i++) {
result += " ";
}
return result;
}
public static String printStars(int num) {
String result = "";
for (int i = 0; i < num; i++) {
result += "*";
}
return result;
}
}
Explanation:
So it sounds we need to make a diamond shape out of asterisks like this:
*
***
*****
*******
*****
***
*
There are 7 rows and each row has up to 7 characters. The pattern is also symmetrical which makes it easier. Before writing any code, let's figure out how we are going to determine the correct amount of spaces we need to print. There are a lot of ways to do this, but I'll just show one. Let's call the 4th row y=0. Above that we have row 3 which would be y=-1, and below is row 5 which is y=1. With 7 rows, we have y=-3 through y=3. The absolute value of the y value is how many spaces we need.
To determine the number of stars, we just double the number of spaces, then subtract this number from 7. This is because we can imagine that the same amount of spaces that are printed in front of the stars are also after the stars. We don't actually have to print the second set of spaces since it is just white space, but the maximum number of characters in a row is 7, and this formula will always make sure we have 7.
I hope this helps. If you need help understanding any part of the code, jsut let me know.