Question

I created an app that generate random number between 2 given values and and its working good it dose what it say but if i entered 11 digit number in the max value (or min value) the app crashes how can I fix it is there another way to generate random number to support big values here is the code

        Button gen = (Button)findViewById(R.id.button);
        final EditText mini = (EditText)findViewById(R.id.mini);
        final EditText maxi = (EditText)findViewById(R.id.maxi);
        final TextView res = (TextView)findViewById(R.id.result);

        final Random r = new Random();
        final int[] number = {0};

        gen.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
                int minn = Integer.parseInt(mini.getText().toString());
                int maxx = Integer.parseInt(maxi.getText().toString());

                if (minn>=maxx){
                   maxi.setText(String.valueOf(minn));
                   mini.setText(String.valueOf(maxx));
                   maxx = Integer.parseInt(maxi.getText().toString());
                   minn = Integer.parseInt(mini.getText().toString());
                   number[0] = minn + r.nextInt(maxx - minn + 1);
                   res.setText(String.valueOf(number[0]));
               }else{
                   number[0] = minn + r.nextInt(maxx - minn + 1);
                   res.setText(String.valueOf(number[0]));
               }
               getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
            }   
       });
} 
Was it helpful?

Solution

You have to use long or double instead of Integer. Because Integer doesn't support that much large value.

long minn = Long.parseInt(mini.getText().toString());
           long maxx = Long.parseInt(maxi.getText().toString());

or

double minn = Double.parseInt(mini.getText().toString());
               double maxx = Double.parseInt(maxi.getText().toString());

OTHER TIPS

This is occuring because the Integer class doesn't support values that large. Try using Longs or Floats. That should work.

The max value of int is 2,147,483,647

use long if you need higher values

Set minn and maxx variables to long.

Integer:

  • MAX VALUE = 2147483647
  • MIN VALUE = -2147483648

Long:

  • MAX VALUE = 9223372036854775807
  • MIN VALUE = -9223372036854775808

Find out more: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

If you want to operate on really big numbers, use BigInteger instead.Integer can't handle big numbers and that's the reason why it's failing for you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top