Agu*_*Val 0 java random android arraylist
我有一个 ArrayList,我想随机获取一个元素,删除该元素并在没有删除的元素的情况下进行另一个随机。我怎样才能做到这一点?我曾尝试过,但没有成功。
谢谢。
主要活动:
public class MainActivity extends AppCompatActivity {
Button button;
TextView textView;
ArrayList<Integer> list = new ArrayList<Integer>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
textView = (TextView)findViewById(R.id.textView);
list.add(0);
list.add(1);
list.add(2);
list.add(3);
}
public void button(View view) {
Random rand = new Random();
int randomElement = list.get(rand.nextInt(list.size()));
if (list.isEmpty()) {
textView.setText("Empty");
} else if (randomElement == 0) {
textView.setText("Red");
list.remove(randomElement);
} else if (randomElement == 1) {
textView.setText("Blue");
list.remove(randomElement);
} else if (randomElement == 2) {
textView.setText("Yellow");
list.remove(randomElement);
} else if (randomElement == 3) {
textView.setText("Green");
list.remove(randomElement);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我知道你想做什么,但我建议采用不同的方法 - 将颜色放入列表中。
public enum Colors {
GREEN, RED, YELLOW;
}
...
List<Colors> list = new ArrayList<Colors>(Arrays.asList(Colors.values()));
Random rand = new Random();
...
public void button(View view) {
if (list.isEmpty()) {
textView.setText("Empty");
} else {
Colors randomElement = list.remove(rand.nextInt(list.size()));
textView.setText(randomElement.name());
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1816 次 |
| 最近记录: |