2012-06-05 50 views
0

我正在編寫一個具有Button的Android應用程序,它調用SelfDestruct()。還有一個TextView,應該顯示12,隨機選擇。但是,如果顯示1,則始終設置爲1,對於2也是如此。它應該始終創建一個隨機數。將TextField的值設置爲隨機數

這是我的代碼,可能有人請幫助我實現這個...

public class MainActivity extends Activity 
{ 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

    } 
    @Override 
    public void SelfDestruct(View View) 
    { 
     TextView tx= (TextView) findViewById(R.id.text); 
     Random r = new Random(); 
     int x=r.nextInt(2-1) + 1; 
     if(x==1) 
     { 
      tx.setText("1"); 
     } 
     else if(x==2) 
     { 
      tx.setText("2"); 
     } 
    } 
} 
+0

你的意思是你想隨機第一次然後總是相同的值? –

回答

0

這會爲你做:

public class MainActivity extends Activity 
{ 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

    } 
    @Override 
    public void SelfDestruct(View View) 
    { 
     TextView tx= (TextView) findViewById(R.id.text); 
     Random r = new Random(); 
     int x=r.nextInt(2) + 1; // r.nextInt(2) returns either 0 or 1 
     tx.setText(""+x); // cast integer to String 
    } 
} 
+0

感謝您的快速回答,似乎我只是隨機失敗, –

+0

您不必做if-else條件。通過在它前面添加一個空字符串來將變量x轉換爲一個字符串。 Java自動數據類型提升會照顧到你的工作:) –

+0

是的,我只是測試和學習;)在這裏很好的支持! –

0

使用此代碼,這應該很好地工作

TextView tx= (TextView) findViewById(R.id.text); 
     Random r = new Random(); 
     int x = r.nextInt(2) % 2 + 1; 
     tx.setText("" +x); 
+0

你不需要事件需要,如果在這裏 – Eric

1

我很確定問題出現在這一行:

r.nextInt(2-1) + 1; 

nextInt(n)返回0(含)和n(不含)之間的數字。這意味着您可以獲得0到.99之間的任何數字,因爲您將1作爲參數傳遞給nextInt()。你總是拿到1這裏,因爲任何數量範圍爲0 - 0.99 + 1強制轉換爲整數將是1

你真的想在1範圍內的數字是什麼 - 2,試試這個:

r.nextInt(2) + 1;