随机化字符串而不重复

时间:2014-12-30 09:56:01

标签: string random duplicates

我有5种不同的语言字符串,我试图让它们随机而没有任何重复,并且一旦它们被挑选就重复这句话。

到目前为止我已经

final String [] mySays = {" x"," y"," ž" ," a"," B",}

@覆盖             public void onClick(查看v){                 //将数字更改为"表示"                 int aNumber =(int)(Math.random()* 5);                 textOne.setText(mySays [aNumber的]);

我可以添加什么?

非常感谢任何帮助。

编辑:

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;


public class MainActivity extends ActionBarActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final List<String> myStrings = new ArrayList<String>(){{
        add("a");
        add("b");
        add("c");
        add("d");
        add("e");
    }};

   List<String> dupeList = new ArrayList<String>(){{addAll(myStrings);}};
    Random r = new Random();

    public String pick(){
            String retval="";
    int pos;
    switch (dupeList.size()){
        case 1: 
            retval = dupeList.get(0);
            dupeList.clear();
            dupeList.addAll(myStrings);
            return retval;
        default:
            pos = r.nextInt(dupeList.size());
            retval = dupeList.get(pos);
            dupeList.remove(pos);
            return retval;
    }
}

1 个答案:

答案 0 :(得分:0)

这是一种使用ArayList模拟&#34;挑出帽子的方法&#34;你想做的事情。 ArrayList很方便,因为你可以轻松删除元素,然后从列表左边的内容中随机选择。

List<String> myStrings = new ArrayList<String>() {{
    add("A");
    add("B");
    add("C");
    add("D");
    add("E");
}};
List<String> dupeList = new ArrayList<String>() {{addAll(myStrings);}};
Random r = new Random();

public String pick() {
    String retval = "";
    int pos;
    switch (dupeList.size()) {
        case 1:
            retval = dupeList.get(0);
            dupeList.clear();
            dupeList.addAll(myStrings);
            return retval;
        default:
            pos = r.nextInt(dupeList.size());
            retval = dupeList.get(pos);
            dupeList.remove(pos);
            return retval;
    }
}

所以一旦你定义了这个pick()方法,你就可以调用它来每次都设置文本。

 `text1.setText(pick());`