发送随机生成的数字进行查看

时间:2016-09-16 13:39:56

标签: java android

如何生成随机数然后将其发送到模拟器?

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import java.util.Random;

public class MainActivity extends AppCompatActivity{

    TextView number1;

        public static void main(String[] args) {

            Random generator = new Random();
            int number1 = generator.nextInt(13);
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        number1 = (TextView)findViewById(R.id.number1);

        number1.setText(Float.toString(number1));
    }
}

3 个答案:

答案 0 :(得分:0)

将数字生成器移动到onCreate()方法并删除main()。您还应该更改int变量名称。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Random generator = new Random();
    int number = generator.nextInt(13);

    number1 = (TextView)findViewById(R.id.number1);
    number1.setText(Integer.toString(number));
}

答案 1 :(得分:0)

正在生成随机数并将其设置为int number1的值,该值仅存在于Main()方法的上下文中。

生成随机数作为onCreate方法的一部分。 (n.b.未经测试的代码)

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Random generator = new Random();
    int myRandomInteger= generator.nextInt(13);

    number1 = (TextView)findViewById(R.id.number1);
    number1.setText(Integer.toString(myRandomInteger));
}

答案 2 :(得分:0)

您应该摆脱main方法 - 根据生命周期 - 将调用onCreate方法,在此期间您可以调用随机数生成器 - 然后将返回值设置为你的TextView

请参阅以下建议的更改:

public class MainActivity extends AppCompatActivity{

    TextView number1;
    //removed the main function from here -
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      number1 = (TextView)findViewById(R.id.number1); 
      //call the method that gets a random number - and set this to the Text field   
        number1.setText(getRandomNumber());
    }

   //I have moved the code from your main function into this "helper" method
   private int getRandomNumber(){
      Random generator = new Random();
      int number1 = generator.nextInt(13);
      return number1;       
   }
}

尝试一下,让我知道这是否有帮助。