nesbak203
nesbak203

Reputation: 1

app is getting crashed-random number generator

This is my java file of Random number generator. Whenever I run the app it get crashed. Help me out!

public class MainActivity extends AppCompatActivity {

    int  k;

    public void lol(View v) {

        EditText e1 = (EditText) findViewById(R.id.e1);
        EditText e2 = (EditText) findViewById(R.id.e2);
        TextView t = (TextView) findViewById(R.id.t);
        int h = Integer.parseInt(String.valueOf(e1));
        int i = Integer.parseInt(String.valueOf(e2));
        Random u = new Random();

        k = h + u.nextInt(i);
        t.setText(k);
    }
}

Upvotes: 0

Views: 118

Answers (3)

You could also try something like the following (note that this is Xamarin for Android so it's C#, not Java):

public void lol(View v)
    {
        EditText e1 = (EditText)FindViewById(Resource.Id.e1);
        EditText e2 = (EditText)FindViewById(Resource.Id.e2);
        TextView t = (TextView)FindViewById(Resource.Id.t);

        int h, i, k;

        // TryParse tries to parse the text as an integer and returns a value
        // indicating whether or not it succeeded
        // e1.Text is equivalent to a call to e1.getText()
        if (int.TryParse(e1.Text, out h) && int.TryParse(e2.Text, out i))
        {
            Random u = new Random();

            k = h + u.Next(i);
            // This is equivalent to doing a call to t.setText(...)
            t.Text = k.ToString();
        }
    }

So, basically, you check to make sure that it actually is an int before you try to use it. Also, this is a better way to get the value of the text from EditText.

Upvotes: 0

Mithun Sarker
Mithun Sarker

Reputation: 4023

You are getting this error probably your random number is less than 0 (zero) . It is better to generate random number in range like this

Random rn = new Random();
int range = maximum - minimum + 1;
int randomNum =  rn.nextInt(range) + minimum;

Upvotes: 0

Sanjeet
Sanjeet

Reputation: 2403

You need to get the text from EditText. Also you need to use try catch block while parsing string to Integer or else it may throw RuntimeException if String can't be parsed to int.

public void lol(View v) {

    EditText e1 = (EditText) findViewById(R.id.e1);
    EditText e2 = (EditText) findViewById(R.id.e2);
    TextView t = (TextView) findViewById(R.id.t);
    String e1Text = e1.getText().toString();
    String e2Text = e2.getText().toString();
    try{
        int h = Integer.parseInt(String.valueOf(e1));
        int i=Integer.parseInt(String.valueOf(e2));
        Random u = new Random();


        k = h + u.nextInt(i);
        t.setText(k);
    }catch(Exception e){
        //some exception
    }
}

Upvotes: 2

Related Questions