Coding Exercise 26: Diagonal Star

2021. 4. 3. 22:16Java programming

Write a method named printSquareStar with one parameter of type int named number.

 

If number is < 5, the method should print "Invalid Value".

 

The method should print diagonals to generate a rectangular pattern composed of stars (*).

 

This should be accomplished by using loops.

 

public class DiagonalStar {
	
	
	public static void printSquareStar(int number){
		
		if(number < 5) {
			System.out.println("Invalid Value");
		} else {
			for (int row = 0; row < number; row++) {
				for (int column = 0; column < number; column++) {
					if (row == 0 || column == 0 || row == (number-1)|| column == (number-1)
                    	|| row == column || (row + column) == (number-1)) {
						System.out.print("*");
					} else {
						System.out.print(" ");
					}	
				}
				System.out.println();			
			}
		}
	}
}

To be fair, I don't know how I got this and from where I managed to solve this exercise.

 

A lot of processes of trial and error as well as looking at others solutions as a guide on this topic with a little bit of luck helped heaps.

'Java programming' 카테고리의 다른 글

Coding Exercise 28: Paint Job  (0) 2021.04.04
Coding Exercise 27: Input Calculator  (0) 2021.04.03
Coding Exercise 25: Largest Prime  (0) 2021.04.02
Coding Exercise 24: Flour Park Problem  (0) 2021.04.01
Coding Exercise 23: Number to Words  (0) 2021.03.31