Untitled
unknown
plain_text
a year ago
4.1 kB
10
Indexable
import java.util.Scanner; // Add Scanner class to allow user input from console
public class Main {
public static void main(String[] args) {
// Create a Scanner object to read user input
Scanner scanner = new Scanner(System.in);
// Ask the User for Input - What Shape?
System.out.println("Enter the shape (triangle, diamond, rectangle, heart):");
String shape = scanner.nextLine().toLowerCase();
// Ask the User for the size of the shape
System.out.println("Enter the size:");
int size = scanner.nextInt();
// Ask the User for what type of Character to use for the Shape
System.out.println("Enter the character to use for the shape:");
char ch = scanner.next().charAt(0);
// Prints Shape depending on user Choice
switch (shape) {
case "triangle":
printTriangle(size, ch);
break;
case "diamond":
printDiamond(size, ch);
break;
case "rectangle":
printRectangle(size, ch);
break;
case "heart":
printHeart(size, ch);
break;
default:
System.out.println("Invalid shape entered!");
break;
}
}
// Method to print a right-aligned triangle
public static void printTriangle(int size, char ch) {
for (int i = 1; i <= size; i++) // I is initialized for the Size of the Triangle
{
for (int j = 1; j <= size - i; j++) {
System.out.print(" ");
}
for (int k = 1; k <= 2 * i - 1; k++) {
System.out.print(ch);
}
System.out.println();
}
}
// Method to print a diamond
public static void printDiamond(int size, char ch) {
int n = size / 2 + 1; // N is initialized for the Size of Diamond
// Upper part of the diamond
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n - i; j++) {
System.out.print(" ");
}
for (int k = 1; k <= 2 * i - 1; k++) {
System.out.print(ch);
}
System.out.println();
}
// Lower part of the diamond
for (int i = n - 1; i >= 1; i--) {
for (int j = 1; j <= n - i; j++) {
System.out.print(" ");
}
for (int k = 1; k <= 2 * i - 1; k++) {
System.out.print(ch);
}
System.out.println();
}
}
// Method to print a rectangle
public static void printRectangle(int size, char ch) {
for (int i = 1; i <= size; i++) // I is initialized for the size of Rectangle
{
for (int j = 1; j <= size; j++) {
System.out.print(ch);
}
System.out.println();
}
}
// Method to print a heart shape
public static void printHeart(int size, char ch) {
// Adjust size to ensure the heart is proportional
int n = size / 2;
// Upper part of the heart (two lobes)
for (int i = n / 2; i <= n; i++) {
for (int j = 1; j < n - i; j++) {
System.out.print(" ");
}
for (int j = 1; j <= 2 * i + 1; j++) {
System.out.print(ch);
}
for (int j = 1; j <= (n - i) * 2; j++) {
System.out.print(" ");
}
for (int j = 1; j <= 2 * i + 1; j++) {
System.out.print(ch);
}
System.out.println();
}
// Lower part of the heart
for (int i = n; i >= 0; i--) {
for (int j = 1; j < n - i; j++) {
System.out.print(" ");
}
for (int j = 1; j <= (i * 2) + 1; j++) {
System.out.print(ch);
}
System.out.println();
}
}
}
Editor is loading...
Leave a Comment