so the question basically says to Use a for loop to add 10 Circles to the ArrayList each with a random radius in the range of 2-5 and Print a table of all of the Circles in the ArrayList. You can use System.out.println(String.format("%.3f", this.getRadius)); to print the circle dimensions to 3 decimal places. but how does this work.
public class CirclesDriver
{
public static void main(String[] args) {
Random rand = new Random();
// ** Variables constants and objects **
Scanner scanner = new Scanner(System.in);
ArrayList<Circle> circles = new ArrayList<>();
// ** load the array list with circles **
for (int i = 0; i <= 10; i++) {
Circle circle = new Circle();
double radius = rand.nextDouble(5) + 2;
}
// print the whole list
System.out.println("--------------------------------\n");
// ** Make sure your Circle class and ArrayList work with the following driver code **
System.out.println();
Circle c1 = new Circle();
System.out.println("C1: " + c1.getID());
System.out.println("Radius: " + c1.getRadius());
System.out.println("--------------------------------\n");
c1.setRadius(1.5);
System.out.println("C1: " + c1.getID());
System.out.println("Radius: " + c1.getRadius());
System.out.println("Area: " + c1.getArea());
System.out.println("--------------------------------\n");
circles.get(3).setRadius(2.2);
System.out.println("C1: " + circles.get(3).getID());
System.out.println("Radius: " + circles.get(3).getRadius());
System.out.println("Diameter: " + circles.get(3).getDiameter());
System.out.println("--------------------------------\n");
Circle c2 = circles.remove(9);
System.out.println("C2: " + c2.getID());
System.out.println("Radius: " + c2.getRadius());
System.out.println("Circumference: " + c2.getCircumference());
System.out.println("--------------------------------\n");
// ** output
// ** closing message **
System.out.println("\nend of program");
Pass radius to constructor
Simpler to define a constructor that takes the radius as an argument.
Define your
Circle
class. If the main purpose of your class is to communicate data transparently and immutably, write your class as a record. With a record, the compiler by default implicitly creates the constructor, getters,equals
&hashCode
, andtoString
. You can declare a record locally (within a method), or separately.A
DoubleStream
can create a series of randomly generateddouble
values. (The following code is untested)We might be able to reduce
.mapToObj( double d -> return new Circle( d ) )
with.mapToObj( Circle :: new )
, a method reference referring to the constructor.For output, loop the list. Add methods to the
Circle
class to return diameter and circumference.