36.9k views
8 votes
Write a method that takes a RegularPolygon as a parameter, sets its number of sides to a random integer between 10 and 20 inclusive, and sets its side length to a random decimal number greater than or equal to 5 and less than 12. Use Math.Random() to generate random numbers.

User Celsiuss
by
4.2k points

2 Answers

2 votes

Final answer:

To manipulate a RegularPolygon object in Java, use Math.random() combined with calculations to set the number of sides to a random integer between 10 and 20 and the side length to a random decimal between 5 and less than 12. Ensure the RegularPolygon class has the necessary setter methods.

Step-by-step explanation:

To write a method that operates on a RegularPolygon object and sets its number of sides and side lengths to random values within specified ranges, you can use the Math.random() function in Java. The Math.random() function returns a double value greater than or equal to 0.0 and less than 1.0. You'll first determine the range for the number of sides (which is 10 to 20) and the range for the side length (which is 5 to 12 but not including 12).

The calculation for the random number of sides would be ((int)(Math.random() * (max - min + 1)) + min), where min is 10 and max is 20. Similarly, the calculation for the random side length would be ((Math.random() * (max - min)) + min), with min being 5 and max being 12. The RegularPolygon's properties can then be set with these values.

Here's an example method:

public void setSidesAndLength(RegularPolygon polygon) {

int numberOfSides = (int)(Math.random() * (20 - 10 + 1)) + 10;

double sideLength = (Math.random() * (12 - 5)) + 5;

polygon.setNumberOfSides(numberOfSides);

polygon.setSideLength(sideLength);

}

In this method, numberOfSides is randomly set between 10 and 20, and sideLength is randomly set between 5 and just below 12. You should ensure that the RegularPolygon class has setNumberOfSides and setSideLength methods available for this code to work.

User Andriy Sholokh
by
3.8k points
9 votes

Answer:

import java.lang.Object

import java.lang.Math

public class RegularPolygon extends java.lang.Object{

public void randomize(RegularPolygon c){

int min = 10, max1 = 20;

double min1 = 5, max1 = 12;

double range = (max - min) + 1;

double range1 = (max1 -min1) + 1

int side = (Math.random() * range) + min;

double len = (Math.random() * range1) + min1;

c.setNumSides(side);

c.setSideLength( len);

}

public static void main(String[] args) {

RegularPolygon r = new RegularPloygon();

randomize(r);

}

}

Step-by-step explanation:

The randomize method accepts a regular polygon class as its only parameter and assigns a random number of sides and the length of these sides with the 'Math.random' function.

User Alaa Gamal
by
4.2k points