Wednesday, January 21, 2015

java - How to generate a random number in a range

activity_main.xml code snippet

<TextView
 android:id="@+id/text_view"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="Random Range: 1-10"
 android:textSize="35sp"
 android:textColor="#ff0000"
 >
</TextView>
<Button
 android:id="@+id/push_button"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="Generate Random Number"
 android:onClick="perform_action"
 android:textSize="20sp"
 >
</Button>
MainActivity.java code snippet

public void perform_action(View v)
{
 /*
  the following example code demonstrate us how can we
   generate a random number within a range

   if we set the range within nextInt() method to 1 to 10
   then the system will generate a random number between 1 to 10
   including both 1 and 10.
  */

 //define a new Random class
 Random r = new Random();

 //minimum number to generate as random number
 int minNumber = 1;

 //maximum number to generate as random number
 int maxNumber = 10;

 //get the next random number within range
 int randomNumber = r.nextInt((maxNumber-minNumber)+minNumber)+minNumber;

 //reference the textview widget
 TextView tv = (TextView) findViewById(R.id.text_view);

 //display the random number to textview
 tv.setText(String.valueOf(randomNumber));
}
Imported Class

import android.view.View;
import android.widget.TextView;
import java.util.Random;
More android examples