如何将一个数组中的所有值输入另一个数组的随机索引?

时间:2014-11-01 21:16:38

标签: java arrays

我无法弄清楚如何将存储在数组(case_value)中的所有金额输入到另一个数组中(例如)。我正在尝试随机执行此操作。我的程序确实运行但从未完成。这就是我到目前为止所拥有的。万一你无法猜测,我试图复制交易的格式或没有交易。此外,如果有任何方法可以使我的代码更有效,我将不胜感激。谢谢你的帮助。

import java.util.Scanner;
import java.lang.Math;
public class DOND
{
public static void main (String [] args)
{
Scanner sc = new Scanner (System.in);

int [] cases=new int [26]; //array for the cases
int [] case_value=new int [26]; //array for the money amounts
int b=0;

case_value[0]=1; // all the money amounts
case_value[1]=2;
case_value[2]=5;
case_value[3]=10;
case_value[4]=25;
case_value[5]=50;
case_value[6]=75;
case_value[7]=100;
case_value[8]=200;
case_value[9]=300;
case_value[10]=400;
case_value[11]=500;
case_value[12]=750;
case_value[13]=1000;
case_value[14]=5000;
case_value[15]=10000;
case_value[16]=25000;
case_value[17]=50000;
case_value[18]=75000;
case_value[19]=100000;
case_value[20]=200000;
case_value[21]=300000;
case_value[22]=400000;
case_value[23]=500000;
case_value[24]=750000;
case_value[25]=1000000;

for (int i=0;i<26;i++) //distributing the money
{
while (cases[b]==0); //checks if case is filled 
{
int r=(int)(Math.random()*26); //randomizes money amounts in case
if (cases[r]==0)
{
b=r;
cases[r]=case_value[i]; //inserts money amount in case
}
} 
}

for (int i=0;i<26;i++) //outputs value in cases
{
System.out.println(cases[i]); 
}

}
}

2 个答案:

答案 0 :(得分:0)

如果您只想改变输入,为什么不使用内置的Collection.shuffle方法?

// Fill up array with input
final List<Integer> list = new ArrayList<>(array.length);
for (int i = 0; i < array.length; i++) {
    list.add(array[i]);
}

Collections.shuffle(list);
// Work with this shuffled list

答案 1 :(得分:0)

因为您需要对数组中的内容进行随机播放,并且需要将这些内容存储在其他数组中。我建议你使用下面的方法。

Step1)将数据放入一个数组中。 Step2)随机播放该数组中的内容。 Step3)现在将每个项目添加到不同的数组中。

要随机播放您可以使用的内容。

// Implementing Fisher–Yates shuffle
  static void shuffleArray(int[] ar)
  {
    Random rnd = new Random();
    for (int i = ar.length - 1; i > 0; i--)
    {
     int index = rnd.nextInt(i + 1);
      // Simple swap
     int a = ar[index];
     ar[index] = ar[i];
     ar[i] = a;
    }
  }

你可以在Random shuffling of an array找到这个 请不要重复问题。这可能是重复的。