I appreciate the OP is new to Java, so methods might be considered "advanced", however I think it's worth using this problem to show how you can attack a problem by breaking it into pieces.
Let's think about writing a method to print a single line, telling the method which number line it is:
public void printTriangleLine(int rowNumber) {
// we have to work out what to put here
}
We have to print some number of spaces, then some number of stars.
Looking at the example, I can see that (if the first row is 0) it's (5-rowNumber) spaces and (2*rowNumber + 1) stars.
Let's invent a method that prints the rows of characters for us, and use it:
public void printTriangleLine(int rowNumber) {
printSequence(" ", 5 - rowNumber);
printSequence("*", 2 * rowNumber + 1);
System.out.println();
}
That won't compile until we actually write printSequence(), so let's do that:
public void printSequence(String s, int repeats) {
for(int i=0; i<repeats; i++) {
System.out.print(s);
}
}
Now you can test printSequence on its own, and you can test printTriangleLine on its own. For now you can just try it out by calling those methods directly in main()
public static void main(String [] args) {
printSequence("a",3);
System.out.println();
printTriangleLine(2);
}
... run it and verify (with your eyes) that it outputs:
aaa
*****
When you get further into programming, you'll want to use a unit testing framework like jUnit. Instead of printing, you'd more likely write things like printTriangleLine to return a String (which you'd print from higher up in your program), and you would automate your testing with commands like:
assertEquals(" *****", TriangleDrawer.triangleLine(2));
assertEquals(" *", TriangleDrawer.triangleLine(0))
Now we have the pieces we need to draw a triangle.
public void drawTriangle() {
for(int i=0; i<5; i++) {
printTriangleLine(i);
}
}
The code we have written is a bit longer than the answers other people have given. But we have been able to test each step, and we have methods that we can use again in other problems. In real life, we have to find the right balance between breaking a problem into too many methods, or too few. I tend to prefer lots of really short methods.
For extra credit:
- adapt this so that instead of printing to System.out, the methods return a String -- so in your main() you can use
System.out.print(drawTriangle())
- adapt this so that you can ask drawTriangle() for different sizes -- that is, you can call
drawTriangle(3)
or drawTriangle(5)
- make it work for bigger triangles. Hint: you will need to add a new "width" parameter to printTriangleLine().