As we know the following code is to Random Number
Random generator = new Random();
number = generator.nextInt(VALUE) + 1;
and i make this code to Random generator if the button click
button1 = (Button)findViewById(R.id.buttonblack);
if(v==button1) {
// Here, we are generating a random number
Random generator = new Random();
number = generator.nextInt(5) + 1;
// The '5' is the number of values
// Here, we are checking to see what the output of the random was
switch(number) {
case 1: if(bla.. bla.. bla.. == 1){
//Do some blaa. blaa. blaa. logic
}
else if(bla.. bla.. bla.. == 2){
//Do some blaa. blaa. blaa. logic
}
break;
//and so on..
My question is how to make Random Generator method is automatically Random every 2 second then increasingly faster, not by clicking a button
and how to make random stop if some button clicked, example
buttonstop = (Button)findViewById(R.id.buttonstop);
buttonstop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
//Stop Random generator
}
});
Anyone can Answer? Thank's
use it which starts from 2 seconds to faster by 20 milliseconds
private Handler mHandler = new Handler();
int ms=2000; //2secs.
Define a Runnable:
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
// get random number here
// You could do this call if you wanted it to be periodic:
ms=ms-20; //20ms faster
mHandler.postDelayed(this, ms);
}
};
mHandler.postDelayed(mUpdateTimeTask, 100);
Related
This question already has answers here:
Java random always returns the same number when I set the seed?
(7 answers)
Closed 3 years ago.
I am trying to set the background color of a view using a timer to change the color every few seconds, but often a color is set twice in a row due to the fact that the random number referring to a specific color is generated twice. How can I change the code to avoid generating the same random number twice in a row?
final Runnable runnable = new Runnable() {
#Override
public void run() {
Random rand = new Random();
int n = rand.nextInt(3);
n += 1;
switch (n){
case 1:
colorView.setBackgroundColor(Color.GREEN);
break;
case 2:
colorView.setBackgroundColor(Color.MAGENTA);
break;
case 3:
colorView.setBackgroundColor(Color.CYAN);
break;
}
}
};
The only way is to make a test if the old number equals to the newest generated.
Random rand = new Random();
int n = rand.nextInt(3);
n += 1;
while (n == oldValue) {
n = rand.nextInt(3);
n += 1;
}
switch (n){
...
}
oldValue = n; //The oldValue should be global
Try this:
Set<Integer> generated = new HashSet<>();
int randomMax = 3;
final Runnable runnable = new Runnable() {
#Override
public void run() {
Random rand = new Random();
int n = rand.nextInt(randomMax);
while (generated.contains(n) && generated.size() < randomMax) {
n = rand.nextInt(randomMax);
}
if (generated.size() == randomMax) {
throw new Exception("all numbers already generated")
}
generated.add(n);
n += 1;
switch (n){
case 1:
colorView.setBackgroundColor(Color.GREEN);
break;
case 2:
colorView.setBackgroundColor(Color.MAGENTA);
break;
case 3:
colorView.setBackgroundColor(Color.CYAN);
break;
}
}
};
You can store the integer that was created the last time in a variable 'temp' and compare it to the integer that is created in the current step:
final Runnable runnable = new Runnable() {
#Override
public void run() {
if(tempInt == null){
int tempInt = 0;
int n = 0;
}
Random rand = new Random();
while(n == tempInt){
n = rand.nextInt(3);
n += 1;
}
tempInt = n;
switch (n){
case 1:
colorView.setBackgroundColor(Color.GREEN);
break;
case 2:
colorView.setBackgroundColor(Color.MAGENTA);
break;
case 3:
colorView.setBackgroundColor(Color.CYAN);
break;
}
}
You can do something like this
//set it as a global variable
int previousRandomNumber=0; //set it as 0 for first time
final Runnable runnable = new Runnable() {
#Override
public void run() {
int currentRandomNumber=new Random.nextInt(3);
currentRandomNumber+=1;
while(currentRandomNumber == previousRandomNumber){
currentRandomNumber = new Random.nextInt(3);
currentRandomNumber+=1;
}
/*store the current number as the previous number to check with next the generated number is the same or not*/
previousRandomNumber=currentRandomNumber;
switch (n){
case 1:
colorView.setBackgroundColor(Color.GREEN);
break;
case 2:
colorView.setBackgroundColor(Color.MAGENTA);
break;
case 3:
colorView.setBackgroundColor(Color.CYAN);
break;
}
}
};
I am currently trying to build a dice rolling app in Android.
I managed to build my basic layout and methods with ease but I am currently stuck with the following issue:
I have two ImageView's on my screen and I need to make them change simultaneously 3 times, a basic simulation of a dice rolling, before the final dice face is presented to the user.
So far I tried it this way:
public void rollDiceAnim() {
////// diceone anim
final android.os.Handler handler = new android.os.Handler();
Runnable runnable = new Runnable() {
int counter = 0;
#Override
public void run() {
if (counter<4) {
counter++;
Log.e("Counter value",counter+"!");
int diceOneAnim = (int) ((Math.random() * 6) + 1);
ImageView dice1_img = (ImageView) findViewById(R.id.dice1_img);
switch (diceOneAnim) {
case 1:
dice1_img.setImageResource(R.drawable.d1);
break;
case 2:
dice1_img.setImageResource(R.drawable.d2);
break;
case 3:
dice1_img.setImageResource(R.drawable.d3);
break;
case 4:
dice1_img.setImageResource(R.drawable.d4);
break;
case 5:
dice1_img.setImageResource(R.drawable.d5);
break;
case 6:
dice1_img.setImageResource(R.drawable.d6);
break;
}
handler.postDelayed(this, 150);
} else {
rollDice();
}
}
};
/////////
///// dice two anim
final android.os.Handler handler2 = new android.os.Handler();
Runnable runnable2 = new Runnable() {
int counter2 = 0;
#Override
public void run() {
if (counter2<4) {
counter2++;
Log.e("Counter value",counter2+"!");
int diceTwoAnim = (int) ((Math.random() * 6) + 1);
ImageView dice2_img = (ImageView) findViewById(R.id.dice2_img);
switch (diceTwoAnim) {
case 1:
dice2_img.setImageResource(R.drawable.d1);
break;
case 2:
dice2_img.setImageResource(R.drawable.d2);
break;
case 3:
dice2_img.setImageResource(R.drawable.d3);
break;
case 4:
dice2_img.setImageResource(R.drawable.d4);
break;
case 5:
dice2_img.setImageResource(R.drawable.d5);
break;
case 6:
dice2_img.setImageResource(R.drawable.d6);
break;
}
handler2.postDelayed(this, 500);
} else {
rollDice();
}
}
};
////////////////////////
handler.postDelayed(runnable, 100);
handler2.postDelayed(runnable2, 100);
}
I have made two runnable objects, each iterating randomly, changing a set of dice faces before presenting the final one.
The problem is when running the two:
handler.postDelayed(runnable, 100);
handler2.postDelayed(runnable2, 100);
They do not run at the same time. After the first handler is finished, the second handler still has some work to do.
I've tried using threads instead of handlers, but my app just crashes.
I think you can try combining that two jobs into a same Runnable.
I would highly suggest checking out the Android API about AsyncTask. It a better way to work with asynchronous request especially if you have more than one.
i am creating an app, that in the class i have this random:
public class Ejemplo extends Activity implements OnClickListener {
int ran=(int)(1*Math.random()) +1;
and also have this counter
int contador= 0; // this is just to know how many time i won
then i have 2 buttons a1 and a2
and in my onClick
switch (v.getId()) {
case R.id.a1:
if(ran == 1){
a1.setText("WIN");
contador= contador + 1;
}
else{
a1.setText("0");
}
a1.setClickable(false);
break;
case R.id.a2:
if(ran == 2){
a2.setText("WIN");
contador= contador + 1;
}
else{
a2.setText("0");
}
a2.setClickable(false);
break;
so the problem is that when i press the button: New Game the random is going to have the same number of the random, and i cant just call again the activity bc i dont want to reset my counter: contador.
How i can just reset my random, so it doesnt always select the same button?
just use a Random instead of Math.random it's easier to use, you can have like this:
Random random = new Random(); // random generator
// then inside your onClick this code
if(random.nextBoolean()){
// win
} else {
// lose
}
https://developer.android.com/reference/java/util/Random.html
edit:
it's really much simpler than what you trying to do:
public class Ejemplo extends Activity implements OnClickListener {
Random random = new Random(); // random generator
// then inside the click listener:
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.a1:
if(random.nextBoolean()){
a1.setText("WIN");
contador= contador + 1;
gano();
}
else{
a1.setText("0");
}
a1.setClickable(false);
break;
Put int ran=(int)(1*Math.random()) +1; in the onClick rather than declaring it as an instance variable in the activity. So everytime a click happens, your ran variable will have a different value.
I have a question that I really don't know if it's possible realize it. This is the situation; I have five methods and one button. Actually if I want call a method tapping the button I write:
btnore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
//i call the method I need
Met_one();
}
});
What I need is do something like:
btnore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// a random function call the methods.
Random = random of the methods(Met_one, Met_two,Met_three,Met_four,Met_five)
}
});
So in this way when I tap the button sometimes it does a kind of action and sometimes another one at random. It's it possible?
I think the best solution is to use switch with random numbers
Something like this:
Random random = new Random();
int numberOfMethods = 4;
switch(random.nextInt(numberOfMethods)) {
case 0:
method1();
break;
case 1:
method2();
break;
case 2:
method3();
break;
case 3:
method4();
break;
default:
method1();
}
In java Math.random() * 5 This would return a value in the range [0,5].when you press the Button you can invoke it.
inside the onCreate
Button btn1=(Button)findViewById(R.id.button1);
btn1.setOnClickListener(btnOnClickListener);
and
Button.OnClickListener btnOnClickListener=new Button.OnClickListener()
{
#Override
public void onClick(View v) {
if(v==b1)
{
// your Math.random() * 5 function can invoke.
}
}
Yes this is possible. If you have fixed number methods, the probability is going to be 1/n. Eg, with 5, probability is 0.2. You can have something like this, where rand is re-generated every time the button is clicked:
if (rand < 0.2)
Met_one()
else if (rand < 0.4)
Met_two()
else if (rand < 0.6)
Met_three()
... etc
I am trying to write and application which, when a button is pressed, will display all the prime numbers from 23 to 499. Now, I know I have my algorithm correct, so that is not the issue as I can run it using S.o.pln in some other Java Development program. The issue I believe lies in my use of a thread as I've never used one before, or maybe my use of a runnable. I could also be where I am appending an integer to a TextView, but, as I am new, I have no idea. Any help is greatly appreciated and if you need anymore context I will be happy to provide it. Thanks...
public class PrimeNumbers extends Activity implements OnClickListener {
Button whatPrime, howManyPrime, resetPrime;
TextView numPrime, ctPrime;
int prime = 23, factor, ct = 0;;
StringBuilder strBuPrime;
String strPrime;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.primenumbers);
initialize();
whatPrime.setOnClickListener(this);
howManyPrime.setOnClickListener(this);
resetPrime.setOnClickListener(this);
}// end onCreate
private void initialize() {
// TODO Auto-generated method stub
whatPrime = (Button) findViewById(R.id.bPrime);
howManyPrime = (Button) findViewById(R.id.bPrimeCount);
resetPrime = (Button) findViewById(R.id.bPrimeReset);
numPrime = (TextView) findViewById(R.id.tvPrimeNumbers);
ctPrime = (TextView) findViewById(R.id.tvPrimeNumbersCount);
}// end initialize
Runnable findPrimes = new Runnable() {
#Override
public void run() {
while (prime <= 499 && prime >= 23) {
factor = 3;
while (prime % factor != 0) // if true start testing
// other
// factors
{
while (factor <= (Math.sqrt(prime))) // testing
// other
// factors
{
if (prime % factor == 0) // factor found, leave
// while
{
factor = 2000;
}
factor++;
}
if (factor != 2001) // no factor found but left
// while, print
// prime, add 1 to counter
{
strPrime = Integer.toString(prime);
strBuPrime.append(strPrime + '\n');
}
factor = 1; // leave while as 1 is a factor of
// everything
}
prime += 2; // test next prime
}
numPrime.post(new Runnable() {
#Override
public void run() {
numPrime.setText(strBuPrime);
}
});
}
};
Thread threadPrimes = new Thread(findPrimes);
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {
case R.id.bPrime:
threadPrimes.start();
break;
case R.id.bPrimeCount:
ctPrime.setText("There are " + ct
+ " prime numbers from 23 to 499.");
break;
case R.id.bPrimeReset:
numPrime.setText("");
ctPrime.setText("");
break;
}
}// end onClick
}
logcat would help, but you are probably overdoing it with the post(Runnable) to append the values to your TextView. Try using a StringBuilder to concatenate everything and set the text all at once. (Or at least in larger chunks.)
You should try using AsyncTask http://developer.android.com/reference/android/os/AsyncTask.html
I think your tread is still running in the UI threadpool and causes the UI to lockup.
Android will kill your thread if you lock the UI for ~2-3 seconds.
AsyncTask will also allow you to display a status bar or spinning ring while the runnable does the work.