开发者

program crashing when i use Random() function

I am using Random() function in my application.When i click on button i have to display a random number in 0-8 range as the text of my button.But when it runs if i click on this button the program will crash.given below is my code snippet.

 Random scorenumber=new Random();
 OnClickListener clickball=new OnClickListener() {

        @Override
        public vo开发者_如何学编程id onClick(View v) {
            score=scorenumber.nextInt(8);
            id=v.getId();

                       if(id==R.id.ball2)
            {
                ball2.setText(score);
            }
            else if(id==R.id.ball3)
            {
                ball3.setText(score);
            }
 }


You are calling void setText (int resid) here. This will crash when Android does not find a string resource with the same ID as the contents of the score variable. Use setText(Integer.toString(score));.


First off I tend to use the onClick atribute in my XML documents. It doesn't mean you have to but I have found that it make my code neater.

android:onClick="button"

So my Java would look like this to start my method.

public void button(View v){
    //Stuff goes here.
}

I say this only because I think your button is broken. Try having it do something else. Like count up from 1. If it fails then you button is bad. If it works then something is wrong with you code for random numbers. Which I can't seem to make out what you are trying to do.

In regards to that. Where are you getting ball3 and ball2? When is scorenumber hitting them?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜