我测试了随机数生成器,它在应用程序之外工作正常。这是一段相当标准的代码。我创建了getter和setter,并且NetBeans没有抱怨传递给应用程序的任何内容,但是随机数应该是“0”。我想更多地了解getter和setter以及类。我可能指错了。
//这是类代码
public class RandomGen {
int minSeed = 100;
int maxSeed = 999;
int num;
public static void RandomNum(int minSeed, int maxSeed) {
Random rand = new Random();
int num = rand.nextInt(maxSeed - minSeed) + 1;
}
public void setMin(int minSeed) {
this.minSeed = minSeed;
}
public void setMax(int maxSeed) {
this.maxSeed = maxSeed;
}
public int getNum() {
return num;
}
}
这是我的应用程序中main的代码
RandomGen rnumber = new RandomGen();
int rnum = rnumber.getNum();
int bigSeed = rnumber.maxSeed;
int smallSeed = rnumber.minSeed;
System.out.println("Random Number = " + rnum);
System.out.println("MaxSeed = " + bigSeed);
System.out.println("MinSeed = " + smallSeed);
这是打印的退货
Random Number = 0
MaxSeed = 999
MinSeed = 100
答案 0 :(得分:1)
您已创建了一个局部变量,因此请使用全局
num = rand.nextInt(maxSeed - minSeed) + 1;
根据您的代码,您需要调用static
方法来初始化num
以及
RandomGen rnumber = new RandomGen();
RandomGen.RandomNum(rnumber.minSeed, rnumber.maxSeed);
//^^^^^^^^^^^^^^^^^^^^^
int rnum = rnumber.getNum();
int bigSeed = rnumber.maxSeed;
int smallSeed = rnumber.minSeed;
注意:构造函数不能是static
,不能有任何返回类型
static int num; // global to class, different from the `num` inside RandomNum
public static void RandomNum(int minSeed, int maxSeed)
{
Random rand = new Random();
// local variable
// changes here, can only be seen inside RandomNum method
//int num = rand.nextInt(maxSeed - minSeed) + 1;
num = rand.nextInt(maxSeed - minSeed) + 1;
}
答案 1 :(得分:0)
首先
static int num; // must also be static
第二
public static void RandomNum(int minSeed, int maxSeed)
{
Random rand = new Random();
num = rand.nextInt(maxSeed - minSeed) + 1; // remove the declaration you try to make it local variable
}
答案 2 :(得分:-2)
这是不正确的。
试试这个:
import java.util.Random;
public class RandomGen {
private Random random;
private int minRange;
private int maxRange;
public static void main(String[] args) {
int minRange = (args.length > 0) ? Integer.parseInt(args[0]) : 100;
int maxRange = (args.length > 1) ? Integer.parseInt(args[1]) : 200;
int numValues = (args.length > 2) ? Integer.parseInt(args[2]) : 10;
RandomGen randomGen = new RandomGen(minRange, maxRange);
for (int i = 0; i < numValues; ++i) {
System.out.println(randomGen.getNextIntInRange());
}
}
public RandomGen(int minRange, int maxRange) {
this(minRange, maxRange, null);
}
public RandomGen(int minRange, int maxRange, Long seed) {
this.minRange = minRange;
this.maxRange = maxRange;
this.random = (seed == null) ? new Random() : new Random(seed);
}
public int getNextIntInRange() {
return this.minRange + this.random.nextInt(this.maxRange-this.minRange)+1;
}
}