25.1k views
0 votes
Write code which takes two inputs from the user, a number of sides followed by a side length, then creates a regular polygon with that number of sides and side length.Sample run:Type the number of sides:8Type a side length:7.5regular octagon with side length 7.5Hint: Make sure you use the right data types when taking user input.

1 Answer

4 votes

Answer:

import java.util.Scanner;

public class Polygon {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("Type the number of sides:");

int sides = sc.nextInt();

System.out.println("Type a side length:");

double length = sc.nextDouble();

if (sides== 5){

System.out.println("Pentagon, length "+length);

} else if (sides == 6){

System.out.println("Hexagon, length "+length);

} else if (sides == 7){

System.out.println("Heptagon length "+length);

} else if (sides == 8){

System.out.println("Octagon, length "+length);

} else if (sides == 9){

System.out.println("Nonagon, length "+length);

} else if (sides == 10){

System.out.println("Decagon, length "+length);

} else if (sides == 11){

System.out.println("Undecagon, length "+length);

} else if (sides == 12){

System.out.println("Dodecagon, length "+length);

} else {

System.out.println("Please choose a valid number.");

}

}

}

Step-by-step explanation:

The Java source code defines a class called 'Polygon' the main method of the class prompts for user inputs for the sides and length variables. The nested if-statement prints the type of polygon with respect to the number of sides.

User TheSchwa
by
7.9k points

No related questions found

Welcome to QAmmunity.org, where you can ask questions and receive answers from other members of our community.