162k views
5 votes
Help with entry level Java code!!

Create a Java program that displays a menu with shape options. Using a while loop prompt the user to choose a shape from a to c; however, if the user enters a wrong choice then keep prompting. Thereafter, using an if-elseif structure draw the shape using asterisks (*) based on the user's choice.

Help with entry level Java code!! Create a Java program that displays a menu with-example-1
User Ewout
by
8.3k points

1 Answer

6 votes

Here's the Java program that displays a menu with shape options and prompts the user to choose a shape using a while loop. It then draws the selected shape using an if-elseif structure:

import java.util.Scanner;

public class DrawShapes {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

while (true) {

System.out.println("Choose a shape: ");

System.out.println("a. Square");

System.out.println("b. Triangle");

System.out.println("c. Diamond");

String choice = scanner.nextLine();

if (choice.equals("a")) {

drawSquare();

break;

} else if (choice.equals("b")) {

drawTriangle();

break;

} else if (choice.equals("c")) {

drawDiamond();

break;

} else {

System.out.println("Invalid choice. Please try again.");

}

}

}

public static void drawSquare() {

for (int i = 1; i <= 5; i++) {

for (int j = 1; j <= 5; j++) {

System.out.print("* ");

}

System.out.println();

}

}

public static void drawTriangle() {

for (int i = 1; i <= 5; i++) {

for (int j = 1; j <= i; j++) {

System.out.print("* ");

}

System.out.println();

}

}

public static void drawDiamond() {

int n = 5;

int spaces = n - 1;

for (int i = 1; i <= n; i++) {

for (int j = 1; j <= spaces; j++) {

System.out.print(" ");

}

for (int j = 1; j <= 2 * i - 1; j++) {

System.out.print("*");

}

System.out.println();

spaces--;

}

spaces = 1;

for (int i = 1; i <= n - 1; i++) {

for (int j = 1; j <= spaces; j++) {

System.out.print(" ");

}

for (int j = 1; j <= 2 * (n - i) - 1; j++) {

System.out.print("*");

}

System.out.println();

spaces++;

}

}

}

User Dan Mertz
by
8.2k points