write a program to implement rhombus pattern reading the limit from the user
1 Answers
This question have the following answers.
Here's a Java program that reads an integer limit from the user and prints a rhombus pattern based on that limit.
import java.util.Scanner;
public class RhombusPattern {
public static void printRhombus(int n) {
// Upper part of the rhombus
for (int i = 0; i < n; i++) {
// Print leading spaces
for (int j = 0; j < n - i - 1; j++) {
System.out.print(" ");
}
// Print stars
for (int j = 0; j < 2 * i + 1; j++) {
System.out.print("*");
}
System.out.println();
}
// Lower part of the rhombus
for (int i = n - 2; i >= 0; i--) {
// Print leading spaces
for (int j = 0; j < n - i - 1; j++) {
System.out.print(" ");
}
// Print stars
for (int j = 0; j < 2 * i + 1; j++) {
System.out.print("*");
}
System.out.println();
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter the limit (an integer): ");
int limit = scanner.nextInt();
if (limit <= 0) {
System.out.println("Please enter a positive integer.");
} else {
printRhombus(limit);
}
} catch (Exception e) {
System.out.println("Invalid input. Please enter a valid integer.");
} finally {
scanner.close();
}
}
}
Explanation:
printRhombus(int n) Method:
Upper Part: Loops from 0 to n-1, prints leading spaces, and then prints stars.
Lower Part: Loops from n-2 to 0, prints leading spaces, and then prints stars.m
main(String[] args) Method:
Reads the integer limit from the user using Scanner.
Checks if the limit is positive and calls printRhombus().
Handles invalid inputs using a try-catch block and closes the Scanner in the finally block to prevent resource leaks.
Usage:
- Compile the program with
javac RhombusPattern.java. - Run it using
java RhombusPattern. - Enter a positive integer when prompted to see the rhombus pattern.