2011-07-02 96 views
0

我在这里用在计算器这个问题,创建没有问题的一个随机字符串:d (Show random string)相同的字符串隐藏/删除随机字符串?

有些时候显示出来,这就是烦人。

所以我想要字符串只显示一次每个会话,我已经有一个退出会话按钮,杀死类。所以可以说我有1-3的数字。数字2先出现,然后是1,因为只剩下一个数字,只有3可以显示。

我的按钮代码为“下一个按钮”。目前它杀死了班级并重新开始!我怎样才能改变它,所以它只显示一个新的字符串?

private void onButtonClick(Button clickedButton) { 
    Intent startIntent = null; 
    if (clickedButton.getId() == R.id.quit) { 
     startIntent = new Intent(this, mainmenu.class); 
     finish(); 
    } 

    else if (clickedButton.getId() == R.id.next) { 
     startIntent = new Intent(this, play.class); 
     startActivity(startIntent); 
     finish(); 
    } 

    if (startIntent != null) { 
     startIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); 
     startActivityIfNeeded(startIntent, 0); 
    } 
} 
private void setupbutton() {   
    View.OnClickListener onClickHandler = new View.OnClickListener() {   

     public void onClick(View v) { 
      onButtonClick((Button)v);    
     } 
    }; 
    Button button = (Button)findViewById(R.id.quit); 
    button.setOnClickListener(onClickHandler); 

    button = (Button)findViewById(R.id.next); 
    button.setOnClickListener(onClickHandler); 

回答

0

相同的字符串出现,因为随机数发生器生成随机数!它可以连续多次生成相同的数字。

有很多可能性,仅举二:

  1. 把所有字符串数组,将它洗。然后通过一个取出一个元素开始的指数之一:

    List strings = new ArrayList<String>(getResources().getStringArray(R.array.myArray)); 
    Collections.shuffle(list); 
    
  2. 将所有的字符串在一个阵列中,选择与随机索引的字符串并删除字符串:

    Random rgenerator = new Random(); 
    
        ArrayList<String> strings = new ArrayList<String>(getResources().getStringArray(R.array.myArray));     
        int index = rgenerator.nextInt(strings.size()); 
        String randomString = strings.get(index); 
        strings.remove(index); 
    

编辑: 好吧,我看到...

你必须记住哪些字符串尚未被使用。存储字符串列表和榜上无名静态的,这样可以节省创建活动play的不同实例之间的状态:

private static ArrayList<String> myString; 

然后改变你的构造有点:

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.play); 
    setupbutton(); 

    if (myString == null || myString.size() == 0) { 
     Resources res = getResources(); 
     myString = new ArrayList(Arrays.asList(res.getStringArray(R.array.myArray))); 
    } 

    // get a random string 
    int rand = rgenerator.nextInt(myString.size()); 
    String q = myString.get(rand); 

    // remove the last used string from the list 
    myString.remove(rand); 

    TextView tv = (TextView) findViewById(R.id.text1); 
    tv.setText(q); 
} 
+0

没有按”工作!得到错误。我已经有一个随机生成的东西,我添加了“String randomString = strings.get(index); strings.remove(index);”并将字符串更改为MyString。 – JeppeHP

+0

啊哈,所以最新的错误?你的代码是什么样的。你是否努力帮助自己? – thaussma

+0

http://karlsson1337x.com/prtscr.jpg我删除了添加的代码,因为我正在尝试其他功能。而图片上的代码只是我班的一部分!谢谢。 – JeppeHP

0

对索引进行随机排列,然后用它来选取序列中的下一个字符串。