我的项目的最后一部分是让两个测试数组 grades[] 和 grades2[] 随机相等以测试我的 equals 方法语句。如何正确使用 java.util.Random?或者如果有另一种方法,我很想听听......
在这段代码中,程序将永远输出两个对象不同(显然),因为数组的内容是随机生成的。我如何使它们随机地彼此相等?
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.");
}
}
最佳答案
这是矛盾的。如果它是随机的,你不能让它彼此相等。
编辑:如果你想创建两个随机填充的相同数组,那么你应该用随机数填充一个数组,然后用 System.arraycopy()
或类似的东西复制它。
关于java - 如何使两个数组随机相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20023003/