-4

I have 2 EditText. The user will enter the minimum number in the first EditText and the maximum in the second EditText.

There is one TextView to show the generated number and a Button to click after entering the minimum and maximum numbers

How to generate a number between 2 numbers the user entered and show it in TextView ?

Alexis C.
  • 91,686
  • 21
  • 171
  • 177
Smaika
  • 1,187
  • 4
  • 12
  • 20

1 Answers1

4

Create a random number in the interval [0, max - min], and add min to it.

Random r = new Random();
int number = min + r.nextInt(max-min+1); //add +1 because nextInt generate in the half-open range [0, n).

For example if min = 10 and max = 20 :

  1. r.nextInt(20-10+1) will generate a random number between 0 and 10
  2. You add 10 to this number
  3. You get a random number in the range [10 - 20]

Check the Random class.

To show it in your TextView, use String.valueOf :

myTextView.setText(String.valueOf(number));
Alexis C.
  • 91,686
  • 21
  • 171
  • 177
  • I got it working but how can I set up min value as EditText1 and max as EditText2 ? – Smaika Jan 11 '14 at 06:56
  • @user3182651 See this : http://stackoverflow.com/questions/14212518/is-there-any-way-to-define-a-min-and-max-value-for-edittext-in-android – Alexis C. Jan 11 '14 at 08:19