Skip to content
Advertisement

Creating a parameterized constructor to determine upper bound for randomized side lengths

Im working on a project for class and we have to create a Triangle class that will hold the lengths of each side of the triangle. I created a default constructor that gives each side of the triangle a random length no more than 6. Were asked to create a parameterized constructor that allows the caller to determine the upper bound for the randomized side length, if the supplied upper bound is invalid, this constructor should default to the range used in the default constructor.

Next step is we have to create another parameterized constructor that allows the caller to directly specify the three side length & if any of the three lengths is invalid, all lengths should be randomly generated using the range used in the default constructor.

Im not sure how to get this. This is what i have so far…

import java.util.Random;

public class Triangle {
    int side1;
    int side2;
    int side3;

   //Default Constructor
    public Triangle() {
        Random rng = new Random();
        side1 = rng.nextInt(6)+1;
        side2 = rng.nextInt(6)+1;
        side3 = rng.nextInt(6)+1;
    }

   //toString method
    public String toString() {
        return new String (" " + side1+ " x " +side2+ " x " +side3);
    }

    //Parameterized Constructor
    Triangle (int side11, int side22, int side33) {
        side1 = side11;
        side2 = side22;
        side3 = side33;
    }
}

Advertisement

Answer

I’d move the code in the no parameter constructor out to a method that receives that max bound, then use something like the below:

public Triangle() {
    initSides(6);
}

public Triangle(int max) {
    this(); // call the no parameter constructor
    if (max > 0) {
        initSides(max);
    }
}

public Triangle (int side1, int side2, int side3) {
    this(); // call the no parameter constructor
    if ((side1 > 0) && (side2 > 0) && (side3 > 0)) {
        this.side1 = side1;
        this.side2 = side2;
        this.side3 = side3;
    }
}

private void initSides(int max) {
    Random rng = new Random();
    side1 = rng.nextInt(max)+1;
    side2 = rng.nextInt(max)+1;
    side3 = rng.nextInt(max)+1;
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement