洗牌Android中的数组 [英] Shuffling an Array in Android
问题描述
我很新的编程,我试图做一个程序,它需要一个数量从一个EditText然后生成和数组,然后洗牌,洗牌的数字出来敬酒。
这就是我的code模样。
我试图通过一些其他职位的洗牌阵列读,但我一直没能得到这个工作。
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
推荐答案
其实你不使用你的洗牌数组,但您创建的整型数组。
尝试,而不是:
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);
然后
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);
这篇关于洗牌Android中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!