问题
I am very new to Programming and am trying to make a program that takes a number from an EditText then generates and Array which is then shuffled and the shuffled numbers come out on toast. This is what my code looks like. I have tried reading through a number of other posts on shuffling arrays but I haven't been able to get this to work.
public class Home extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
final EditText editText1 = (EditText) findViewById(R.id.editText1);
Button goButton = (Button) findViewById(R.id.goButton);
goButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
String no = editText1.getText().toString();
int no2 = Integer.parseInt(no);
int[] integerArray = new int[no2];
for (int i = 0; i < no2; i++)
integerArray[i] = i;
Collections.shuffle(Arrays.asList(integerArray));
{
Toast msg= Toast.makeText(getApplicationContext(), integerArray[no2], Toast.LENGTH_LONG);
msg.show();
}
}
});
}
}
Thank you in advance for any help. Tom
回答1:
Actually you don't use the array that you shuffled, but the integer array that you created. Try instead :
List<Integer> myArray = new ArrayList<Integer>(Arrays.asList(integerArray));
Collections.shuffle(myArray);
And then
Toast msg= Toast.makeText(getApplicationContext(), myArray.get(no2-1), Toast.LENGTH_LONG);
msg.show();
Another better approach would be to directly create the List.
List<Integer> myArray = new ArrayList<Integer>(no2);
for (int i = 0; i < no2; i++)
myArray.add(i);
Collections.shuffle(myArray);
来源:https://stackoverflow.com/questions/16724084/shuffling-an-array-in-android