Reputation: 139
The final piece of my project is to make two testing arrays, grades[] and grades2[] equal each other randomly to test my equals method statements. How do I use the java.util.Random correctly? Or if there is another method, I would love to hear it...
In this code, the program will forever output that the two objects are different (obviously) since the contents of the arrays are randomly generated. How do I make it to where they are randomly equal to each other?
public class GradeBookClient
{
public static GradeBook classRoom1, classRoom2;
public static void main( String [] args )
{
//Create two new arrays for testing the equals() method
int[] grades = new int[100];
int[] grades2 = new int[100];
for ( int i = 0; i <= grades.length-1; i++ )
{
grades[i] = (int) Math.floor(Math.random()*101);
}
for ( int i = 0; i < grades2.length; i++ )
{
grades2[i] = (int) Math.floor(Math.random()*101);
}
classRoom1 = new GradeBook (grades);
System.out.println( "The class size is " + classRoom1.getStudent() + " students." + "\n" + classRoom1.toString() );
classRoom2 = new GradeBook (grades2);
System.out.println( "The class size is " + classRoom2.getStudent() + " students." + "\n" + classRoom2.toString() );
if ( classRoom1.equals( classRoom2 ))
System.out.println("Classroom 1 has the same grades and class size as Classroom 2.");
else
System.out.println("Classroom 1 and Classroom 2 have different grades and class sizes.");
}
}
Upvotes: 1
Views: 2149
Reputation: 4623
Create the first array using Random
. Then, if you decide it should be equal to the second array, simply instantiate a new array of the same type and size and copy each position one by one.
Upvotes: 1
Reputation: 3967
I don't know if I got it right because it's not that clear, but maybe you should go with something like this:
//Create two new arrays for testing the equals() method
int[] grades = new int[100];
int[] grades2 = new int[100];
for ( int i = 0; i <= grades.length-1; i++ )
{
int value = (int) Math.floor(Math.random()*101);
grades[i] = value;
grades2[i] = value;
}
so that you can have two equal arrays filled with the same random values
Upvotes: 2
Reputation: 14278
if you want to make the contents of the two array equal:
seed
Random rand = new Random(seed);
if your seed
is equal then rand.nextInt()
will generate same sequence of numbers.
Upvotes: 3
Reputation: 500683
How do I make it to where they are randomly equal to each other?
You could first decide whether or not they should be equal. If they should be, just copy grades
into grades2
instead of generating grades2
independently of grades
.
Upvotes: 3
Reputation: 30548
This is an oxymoron. If it is random you can't make it equal to each other.
Edit: If you want to create two identical arrays which are randomly filled then you should fill an array with random numbers then copy it with System.arraycopy()
or something like that.
Upvotes: 3