Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android The Solution

Anna Kulczycka
Anna Kulczycka
16,174 Points

After getting to a high number count is reversed to minus then it zeroes and crashes

I wanted to try something slightly different so used a function where I double the displayed number. When I tested it it all seems fine - however when I get to a high number ( 1073741824 to be precise), the next number displayed is -2147483648 - then it sets the number to zero , and there's no more response after that.

I'm not sure why that is, are there any restrictions that it might be useful to know about when working with high numbers? Or is there something else I'm doing incorrectly?

My code public class MainActivity extends AppCompatActivity {

int addNumber = 1;


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




    // initialize and cast
final TextView counter = (TextView) findViewById(R.id.myNum);

    Button plusOne = (Button) findViewById(R.id.addNumbButton);

    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //HERE ADD CODE TO MAKE YOUR BUTTON DO SOMETHING
            addNumber += addNumber;
            counter.setText(""+ addNumber);
            //counter.setText("" + addNumber);

        }
    };

    plusOne.setOnClickListener(listener);





}

}

1 Answer

It is because The int data type is a 32-bit signed two's complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647

When the number was 1073741824, after the button click, the next number should be double of that which is 2147483648 which is 1 higher than the max value

You can use long to increase the limit because it is a 64-bit two's complement integer