Hello,

So I'm trying to make an example for myself of object orientated programming in Java with two classes.

One contains all the calculations to determine the x, y, and z coordinates of a given box and also contains a getCount() method that counts the amount of objects that have been made while the other is just a main class that will create new objects from this boxCalc class.

Anyway, the problem I'm having is just using math.random().

The first object I created was made beautifully, no errors, plus I added some print statements to validate that it was made.

The second box object is where I tried to use math.random() to make random x, y, and z coordinates for the new box.

I'm obviously only getting 51.0 for the y and z coordinate for the second box. Should I use the 'new' operator to ensure that the computer is making a random number each time?

The only reason I apply the expression to multiply by 50 and add 1 is because of a similar example I saw on StackOverflow to ensure a random number is produced each time.

Here's my code for the BoxCalc class:

Code:import java.util.Random; class BoxCalc { // Make a variable to count how many objects you have created: static int count = 0; // Make a temporary x center but make it random later on: double xCoord; double yCoord; double zCoord; BoxCalc(double x, double y, double z) { xCoord = x; yCoord = y; zCoord = z; ++count; } // Make a method that will return the count of how many objects were // created: static int getCount() { return count; } }

Here's my code for the BoxMain class:

Code:import java.lang.*; public class BoxMain { public static void main(String[] args) { // Create a Box object from the BoxCalc class // with dimensions for x,y,z: (15, 25, 30) BoxCalc firstBox = new BoxCalc(15, 25, 30); // Print the current count of how many objects you created: System.out.println("Number of objects created = " + BoxCalc.getCount()); // Print firstBox's x-coordinate: System.out.println("firstBox's X-Coordinate = " + firstBox.xCoord); // Create another box object that has random values for each // coordinate: // Use the Random class in Java: int x = (int)Math.random(); // Manipulate the current x value by multiplying by 50 and adding 1 // to ensure a truly random number: x = (x * 50) + 1; // Do the same for y and z: int y = (int)Math.random(); y = (x * 50) + 1; int z = (int)Math.random(); z = (x * 50) + 1; // Make a new box using these random numbers: BoxCalc secondBox = new BoxCalc(x, y, z); // Print out the X-coordinate of the secondBox: System.out.println("secondBox's x = " + secondBox.xCoord); // Print out the y coordinate: System.out.println("secondBox's y = " + secondBox.yCoord); // Print out the z coordinate: System.out.println("secondBox's z = " + secondBox.zCoord); // Print out the count of how many objects have been created: System.out.println("Amount of objects created = " + BoxCalc.getCount()); } }

Tweet This+ 1 thisPost To Linkedin