This programs creates a method printStars
that prints the given amount of stars and a line break and then uses that in other methods to print a square, rectangle and triangle.
My Code
public class Printing {
public static void printStars(int amount) {
// 39.1
// you can print one star with the command
// System.out.print("*");
// call this command amount times
while (amount > 0) {
System.out.print("*");
amount--;
}
System.out.println("");
}
public static void printSquare(int sideSize) {
// 39.2
int tic = sideSize;
while (tic > 0) {
printStars(sideSize);
tic--;
}
}
public static void printRectangle(int width, int height) {
// 39.3
while (height > 0) {
printStars(width);
height--;
}
}
public static void printTriangle(int size) {
// 39.4
int star = 1;
while (star <= size) {
printStars(star);
star++;
}
}
public static void main(String[] args) {
// Tests do not use main, yo can write code here freely!
// if you have problems with tests, please try out first
// here to see that the printout looks correct
printStars(3);
System.out.println("\n---"); // printing --- to separate the figures
printSquare(4);
System.out.println("\n---");
printRectangle(5, 6);
System.out.println("\n---");
printTriangle(3);
System.out.println("\n---");
}
}
Model Code
public class Printing {
public static void printStars(int amount) {
// 39.1
// you can print one star with the command
// System.out.print("*");
// call this command amount times
int printed = 0;
while (printed < amount) {
System.out.print("*");
printed = printed + 1;
}
System.out.println("");
}
public static void printSquare(int sideSize) {
// 39.2
int printed = 0;
while (printed < sideSize) {
printStars(sideSize);
printed = printed + 1;
}
}
public static void printRectangle(int width, int height) {
// 39.3
int printed = 0;
while (printed < height) {
printStars(width);
printed = printed + 1;
}
}
public static void printTriangle(int size) {
// 39.4
int row = 1;
while (row <= size) {
printStars(row);
row = row + 1;
}
}
public static void main(String[] args) {
// Tests do not use main, yo can write code here freely!
// if you have problems with tests, please try out first
// here to see that the printout looks correct
printStars(3);
System.out.println("\n---"); // printing --- to separate the figures
printSquare(4);
System.out.println("\n---");
printRectangle(5, 6);
System.out.println("\n---");
printTriangle(3);
System.out.println("\n---");
}
}
Comments
This had me buggered for a while and it turned out the error was because I was printing a new line before the while loop in printStars() instead of after it.
The only major difference I can find in my implementation is that I have used the > 0 trick from a few lessons back to remove a variable from printStars().