0

Displaying two random numbers and counting scores for odd and even turns. When one of it reaches to 100, the application stops.

This is my java file of application

public class Board_Play1 extends Activity {

int d=0,a=0,b=0,turn=2;
Random random = new Random();
EditText diceno = (EditText) findViewById(R.id.editText1);
EditText p1 = (EditText) findViewById(R.id.editText2);
EditText p2 = (EditText) findViewById(R.id.editText3);

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


    diceno.setText(String.valueOf(d));  
    p1.setText(String.valueOf(a));
    p2.setText(String.valueOf(b));

    while(a!=100 && b!=100)
    {
        if(turn%2==0)
        {
            Button button = (Button) findViewById(R.id.button1);
            button.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View view) {
                    // TODO Auto-generated method stub
                    d=random.nextInt(6)+1;
                    EditText diceno = (EditText) findViewById(R.id.editText1);
                    diceno.setText(String.valueOf(d));

                }
            }); 
        }
        else
        {

            d=random.nextInt(6)+1;
            diceno.setText(String.valueOf(d));
        }

    if(turn%2==0)
            a+=d;
        else
            b+=d;

    if(a>100)
        a-=d;
    if(b>100)
        b-=d;


        p1.setText(String.valueOf(a));
        p2.setText(String.valueOf(b));
        turn++;
    }
    a=0;b=0;

}


}

It doesn't open and give an error saying Unfortunately your app has stopped. Why is this happening? What can I change?

1 Answer 1

1

Move all this inside onCreate after setContentView

EditText diceno;
EditText p1;
EditText p2 ;
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.board_play1);
diceno = (EditText) findViewById(R.id.editText1);
p1 = (EditText) findViewById(R.id.editText2);
p2 = (EditText) findViewById(R.id.editText3);

findViewById looks for a view in the current view hierarchy. You ned to set the content of the layout to the activity first and then initialize vies by using findViewById.

Also there is no need to re- initialize editText in button onClick. Get rid of the below in the same

EditText diceno = (EditText) findViewById(R.id.editText1);

Also move this

Button button = (Button) findViewById(R.id.button1);

before the while loop. no need to initialize everytime

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.