Java Programming: Create a class ( Shapes ) that prompts the user to select a sh
ID: 3588522 • Letter: J
Question
Java Programming:
Create a class (Shapes) that prompts the user to select a shape to be drawn on the screen.
Objects: Diamond, Hexagon, Pentagon, Pyramid with an x inside
Depending on the user’s choice, you will then ask for the number of rows, columns or any requirements needed to draw the shape.
Finally, you will display the shape selected by the user to the screen.
Put main separately in other class, and used just for texting.
Your class needs to check for a correct user input.
Your class should have a method to display the shape.
Your class should have at least one global variable.
Use the asterisk character to draw the shape.
*****************************************************
Submit the UML diagram and Java files
Explanation / Answer
import java.util.Scanner;
public class Shape
{
Scanner sc;
public static String shapeType;
Shape()
{
sc = new Scanner(System.in);
System.out.println("select one among Diamond, Hexagon, Pentagon, Pyramid");
shapeType = sc.next();
switch(shapeType)
{
case "Diamond":
drawDiamond();
break;
case "Hexagon":
drawHexagon();
break;
case "Pentagon":
drawPentagon();
break;
case "Pyramid":
drawPyramid();
break;
default:
System.out.println("invalid input");
}
}
public void drawDiamond()
{
int n, c, k, space=1;
System.out.println("Enter number of rows");
n=sc.nextInt();
space=n-1;
for(k=1; k<=n; k++)
{
for(c=1;c<=space;c++)
{
System.out.print(" ");
}
space--;
for(c=1;c<=2*k-1;c++)
{
System.out.print("*");
}
System.out.print(" ");
}
space=1;
for(k=1;k<=n-1;k++)
{
for(c=1;c<=space;c++)
{
System.out.print(" ");
}
space++;
for(c=1;c<=2*(n-k)-1;c++)
{
System.out.print("*");
}
System.out.println("");
}
}
public void drawHexagon()
{
int i,j,k;
for(i=4;i<=8;i++)
{
for(k=8-i;k>0;k--)
{
System.out.print(" ");
}
for(j=1;j<=i;j++)
{
System.out.print("*");
}
for(int y=1;y<i;y++)
{
System.out.print("*");
}
System.out.println();
}
int m,n,l,p;
for(m=7;m>=4;m--)
{
for(p=8-m;p>0;p--)
{
System.out.print(" ");
}
for(n=1;n<=m;n++)
{
System.out.print("*");
}
for(l=1;l<m;l++)
{
System.out.print("*");
}
System.out.println();
}
}
public void drawPentagon()
{
}
public void drawPyramid()
{
System.out.println("Enter the depth of pyramid");
int depth = sc.nextInt();
int s=depth,m;
for(int i=1;i<=depth;i++)
{
m=s;
while(s>0)
{
System.out.print(" ");
s--;
}
for(int j=1;j<=i;j++)
{
System.out.print("* ");
}
System.out.println(" ");
s=m-1;
}
}
}
Main Class:
public class TestShape()
{
public static void main(string args[])
{
Shape obj=new Shape();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.