Project Solution: Generating an X Pattern in Java
☰Fullscreen
Table of Content:
Project Solution: Generating an X Pattern in Java
Java Source Code:
import java.util.Scanner; public class XPattern { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n; // Prompt the user to enter the size of the X System.out.print("Enter the size of the X: "); n = scanner.nextInt(); // Calculate the dimension of the square matrix int m = 2 * n - 1; // Loop through each row for (int i = 1; i <= m; i++) { // Loop through each column for (int j = 1; j <= m; j++) { // Print '*' if the current position is on either diagonal if (i == j || j == (m - i + 1)) { System.out.print("*"); } else { // Print space otherwise System.out.print(" "); } } // Move to the next line after each row System.out.println(); } } }
Explanation:
-
Input Handling:
- The program starts by creating a
Scanner
object to read user input. - It prompts the user to enter the size of the X pattern (
n
).
- The program starts by creating a
-
Pattern Calculation:
- The size of the square matrix (
m
) is calculated as2 * n - 1
. - Nested loops are used to iterate through each row and column of the matrix.
- The size of the square matrix (
-
Pattern Generation:
- The condition
if (i == j || j == (m - i + 1))
checks if the current position is on one of the diagonals of the X. - If the condition is true, a star (
*
) is printed; otherwise, a space ( - After printing all columns for a row, the program moves to the next line.
- The condition
-
Output:
- The program prints the X pattern based on the user input.
Sample Output:
For an input of n = 3
, the program produces the following output:
* * * * * * * * *
Testing and Validation:
- Input Validation: Ensure the program correctly handles edge cases like
n = 1
and large values ofn
. - Sample Outputs: Run the program with various inputs and capture the outputs to include in your documentation.
Documentation:
- Comment each section of your code to explain its purpose.
- Write a brief report detailing how the program works, including screenshots of different test cases.
By following this structure, you will be able to create a comprehensive project that demonstrates your understanding of Java programming concepts, especially nested loops and conditional statements.