【问题标题】:Make click button generate random numbers without repeating使点击按钮生成随机数而不重复
【发布时间】:2013-02-14 04:55:08
【问题描述】:

我想制作一个应用程序(仅用于学习目的),它会生成随机消息而不重复。

我在 onCreate 方法中有这段代码:

imgbutton2 = (ImageButton) findViewById(R.id.imgbutton2);

int n=3;
int v1[] = new int[n];
v1[0] = 0;
v1[1] = 0;
v1[2] = 0;

int i, j;

for(i=0;i<n;i++){
    for(j=0; ;j++){
        Random rn = new Random();
        int range = 3;
        int r = rn.nextInt(range) 1;

        if(r != v1[0] & r != v1[1] & r != v1[2]) {
            v1[i] = r v1[i];

            textView1=new TextView(this); 

            switch (r) {
                case 1:
                    textView1 = (TextView) findViewById(R.id.textView1); 
                    textView1.setText("Message 1");
                break;

                case 2:
                    textView1 = (TextView) findViewById(R.id.textView1); 
                    textView1.setText("Message 2");
                break;

                case 3:
                    textView1 = (TextView) findViewById(R.id.textView1); 
                    textView1.setText("Message 3");
                break;
            }
            break;
        }
    }

    imgbutton2.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v){
            Intent i = null;
        }});
    }

我在 imgbutton2 中放置了一个空函数(位于第一个 FOR 内),等待用户点击,然后继续阅读以再次在第一个 FOR 中输入 i=1),但它不起作用。

这个想法是在单击按钮时生成一条新消息。

谁能帮帮我?

【问题讨论】:

  • 看起来你实际上并没有对 onClick 事件做任何事情
  • 您的代码未格式化且难以阅读,并且似乎缺少几个 } 字符。我也不太确定实际发生了什么以及您想要发生什么。愿意编辑和澄清您的问题吗?
  • 我该如何解决?我只想在'for'中暂停一下,点击按钮后生成一条新消息
  • @l46kok 是对的,onclick 上实际上什么也没做
  • 您想在单击按钮时生成一条新消息。但您实际上并没有对按钮的 onClick 事件做任何事情???

标签: android button random numbers click


【解决方案1】:

Android 提供了获取随机数的 API:在您的按钮单击事件中使用此 API 并获取随机数而不会重复。

 Random myRandom = new Random();
 int randomNumber = myRandom.nextInt();
 Log.i("RandomNumber:" + randomNumber);

【讨论】:

    猜你喜欢
    • 2015-07-12
    • 1970-01-01
    • 1970-01-01
    • 2018-07-03
    • 2012-08-30
    • 1970-01-01
    • 2018-09-29
    • 2015-08-26
    相关资源
    最近更新 更多