【问题标题】:Setting the value of a TextField to a Random number将 TextField 的值设置为随机数
【发布时间】:2012-06-05 15:45:01
【问题描述】:

我正在编写一个具有Button 调用SelfDestruct() 的Android 应用程序。还有一个TextView 应该显示12,随机选择。但是,如果它显示1,则始终设置12 也是如此。它应该始终创建一个随机数。

这是我的代码,谁能帮我实现这个...

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");
        }
    }
}

【问题讨论】:

  • 你的意思是你希望它第一次随机然后总是相同的值?

标签: java android random if-statement


【解决方案1】:

我很确定问题出在这一行:

r.nextInt(2-1) + 1;

nextInt(n) 返回一个介于 0(包括)和 n(不包括)之间的数字。这意味着您可以获得 0 到 .99 之间的任何数字,因为您将 1 作为参数传递给 nextInt()。你总是在这里得到 1,因为 0 - .99 + 1 范围内的任何数字转换为整数都是 1。

你真正想要的数字在 1 - 2 的范围内,试试这个:

r.nextInt(2) + 1;

【讨论】:

    【解决方案2】:

    这对你有用:

    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
        }
    }
    

    【讨论】:

    • 感谢您的快速回答,看来我只是随机失败了,
    • 您也不必执行 if-else 条件。只需通过在变量 x 前面附加一个空字符串来将变量 x 转换为字符串。 Java 自动数据类型提升将为您完成工作:)
    【解决方案3】:

    使用这段代码,应该可以完美运行

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

    【讨论】:

    • 如果这里还有其他情况,你不需要
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-17
    • 1970-01-01
    • 1970-01-01
    • 2022-12-01
    • 2019-11-02
    • 2013-10-20
    • 2021-04-16
    相关资源
    最近更新 更多