我正在尝试将数组发送到我的void方法,并对其进行随机排序。改组后,我尝试提取改组后的数组的一部分,然后仅将其发送回main。我已经输入了一条打印语句,向我显示了我将数组发送到其中的方法将它们混洗了,但是我并没有像我想要的那样在“新”数组中得到6个值。
我研究了按值调用,并查看了该方法在我的数组上工作时可能发生的情况,但是我找不到有人问这个特定问题。
public static void main(String [] args)
{
int[] viking = new int[48]; //Create array
for(int k = 0; k < viking.length; k++) //Populate the array with all integers between 0 and 49 (1-48)
{
viking[k] = k + 1;
}
trekk(viking); //Call method to scramble and select the numbers
System.out.println(Arrays.toString(viking));// Here is where I can see that im only getting returned the shuffled numbers, not the ones i "extracted"
//sorter(viking);
//skrivUt(viking, 6);
}
private static void trekk (int[] array)
{
SecureRandom random = new SecureRandom ();
for (int index = array.length - 1; index > 0; index--)
{
int nyIndex = random.nextInt (index + 1);
int endringSjanse = random.nextInt(100); /
if (endringSjanse >= 30 && nyIndex != index)
{
int temp = array[index];
array[index] = array[nyIndex];
array[nyIndex] = temp;
}//End if
}//End for-loop
if (array.length >= 35)
{
int low = 5, high = 48;
int arrIn1 = random.nextInt(high-low) + low;
int arrIn2 = (arrIn1 - 5);
int[] viking = new int[6];
viking = Arrays.copyOfRange(array, arrIn2, arrIn1);
array = null;
array = Arrays.copyOf(viking, viking.length);
}
else
原始数组是:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48]
我希望它随机播放,然后按顺序取出6个值(这样就不会重复任何数字),然后随着该方法完成,我回到main时,我只需要6个随机数:[26,11,12,5,5,27,15]
但是我却得到了这个:
[18, 7, 2, 25, 19, 14, 23, 1, 9, 26, 11, 12, 5, 27, 15, 43, 16, 6, 8, 38, 37, 41, 4, 24, 34, 32, 13, 35, 39, 20, 30, 10, 17, 31, 28, 36, 33, 29, 21, 46, 22, 42, 3, 44, 47, 40, 45, 48]
您的trekk()
方法在该问题中看起来不完整。顺便说一句,您正在将“缩短的” viking
数组(6个元素之一)声明为该方法的if测试。因此,其可见性仅限于if-test,并且在执行trekk()
之后,调用main方法将看到原始的方法(实际上是完整的方法)。
顺便说一下,改写变量名是不好的编程习惯。我建议让trekk()
返回另一个数组并使用该数组。