0

我的功能:

public int[] generateRandomInteger(){
    int[] arr = new int[100];
    Random randomGenerator = new Random();

    for (int i = 0; i < 100; i++){
        int randomInt = randomGenerator.nextInt(16) + 10;
        arr[i] = randomInt;
    }        
    return arr;
}

问题是:当我在另一个函数中使用arr时,它会生成一个由 100 个整数组成的不同数组。我怎样才能避免这个问题?我只想使用从上面的函数生成的数组。

任何帮助将不胜感激!

4

5 回答 5

1

只需生成一次,并始终使用它。

int[] array = generateRandomInteger();
// operate on it...
// or pass it to another function
modifyArray(array);
System.out.println(Arrays.toString(array));

在哪里

public void modifyArray(int[] array)
{
    for (int i = 0; i < array.length; ++i)
    {
        array[i] += 10;
    }
}
于 2013-08-28T18:31:57.163 回答
1

如果你想让arr变量对所有对象都是通用的。然后使用静态变量

static int[] arr = new int[100];
public void setRandomIntegerArray(){
  Random randomGenerator = new Random();
  for (int i = 0; i < 100; i++){
      int randomInt = randomGenerator.nextInt(16) + 10;
      arr[i] = randomInt;
  }
}
public int[] getRandomIntegerArray(){
    return arr;
}

如果您想让arr每个对象的变量分开。然后使用实例变量

int[] arr = new int[100];
public void setRandomIntegerArray(){
  Random randomGenerator = new Random();
  for (int i = 0; i < 100; i++){
      int randomInt = randomGenerator.nextInt(16) + 10;
      arr[i] = randomInt;
  }
}
public int[] getRandomIntegerArray(){
    return arr;
}
于 2013-08-28T18:39:00.410 回答
0

您可以在创建随机实例时使用种子。如果以相同的顺序对它们进行调用,则使用相同种子创建的每个随机实例都将返回相同的结果。但我同意 Rohit Jain 的观点,即您可能希望保留数组的一个实例。

于 2013-08-28T18:32:08.990 回答
0
private int[] generatedArray = null; //This keeps the array you generated
private int randomIdx = 0; //This keeps track of where you are

//This function controls access to your random numbers.
public int getNextInt() {
  if (this.generatedArray == null) {
    this.generatedArray = generateRandomInteger();
    randomIdx = 0;
  }

  return generatedArray[randomIdx++];
}

//Technically this doesn't need to be in the same class
//We keep it untouched, though, in case you need the functionality as-is
public int[] generateRandomInteger(){
    int[] arr = new int[100];
    Random randomGenerator = new Random();

    for (int i = 0; i < 100; i++){
        int randomInt = randomGenerator.nextInt(16) + 10;
        arr[i] = randomInt;
    }        
    return arr;
}
于 2013-08-28T18:33:37.957 回答
0

你可以用这种方式定义一个单例实例

public class ArrayIntGenerator {
  private int[] array;
  private ArrayIntGenerator()
  {
      this.array = new int[100];
      Random randomGenerator = new Random();
        for (int i = 0; i < 100; i++){
            int randomInt = randomGenerator.nextInt(16) + 10;
            this.array[i] = randomInt;
        }
  }
  private static ArrayIntGenerator instance = null;

  public final static ArrayIntGenerator getInstance() {
    if(null == instance) instance = new ArrayIntGenerator();
    return instance;
  }

  public int[] getArray() {
    return this.array;
  }
}

int[]并访问ArrayIntGenerator.getInstance().getArray()

于 2013-08-28T18:56:44.460 回答