2011-07-02 95 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

對索引進行隨機排列,然後用它來選取序列中的下一個字符串。