题目是产生25个随机值,并用if-else分类比较紧随两组随机数的大小
我的代码是下面这样的:
import java.util.*;
public class ex_1
{
public static void compareRand()
{
Random r = new Random(100);
int a = r.nextInt();
int b = r.nextInt();
System.out.println("a = " + a + ", b = " + b);
if(a < b)
System.out.println("a < b");
else if (a > b)
System.out.println("a > b");
else
System.out.println("a = b");
}
public static void main(String[] args)
{
for(int i = 0; i < 25; i++)
compareRand();
}
}
可问题来了,运行结果却是
a = -1193959466,b =-119395466
a<b
a = -1193959466,b =-119395466
a<b
...
------解决思路----------------------
import java.util.*;
public class ex_1
{
public static void compareRand(Random r)
{
int a = r.nextInt(100);
int b = r.nextInt(100);
System.out.println("a = " + a + ", b = " + b);
if(a < b)
System.out.println("a < b");
else if (a > b)
System.out.println("a > b");
else
System.out.println("a = b");
}
public static void main(String[] args)
{
Random r = new Random(100);
for(int i = 0; i < 25; i++)
compareRand(r);
}
}
你这个多个Random对象