2012-06-05 144 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;