Reset random generator Android - java

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.

Related

Random number generator repeatedly returns 0s [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last year.
Improve this question
I'm currently taking an online course in Java using Android Studio. As part of the course we had an exercise to build Higher or Lower number guessing game. The initial code I wrote worked just fine (despite being a bit wordy, but I'm still learning), it generated a random number and everything worked right with all the correct messaging. Here is the working code.
import java.util.Random;
public class MainActivity extends AppCompatActivity {
Random ran = new Random();
int gameStart = 1 + (int) (Math.random() * (30));
public void buttonClick(View view) {
EditText number = (EditText) findViewById(R.id.number);
Button button = (Button) findViewById(R.id.button);
int num = Integer.parseInt(number.getText().toString());
if (num == gameStart) {
Toast.makeText(this, "Correct!", Toast.LENGTH_SHORT).show();
} else if (num > gameStart) {
Toast.makeText(this, "Lower", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Higher", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
But then the instructor has introduced extra code to make game restart if the answer is correct with a new number by making Random a method and adding it in the initial if statement. In the video it worked but when I added it and compiled the only number Random generates is 0. I have tried everything but for the love of god can't get it to work correctly. Can someone please have a look at the changes below and spot what could be creating this issue? What needs to be ammended?
public class MainActivity extends AppCompatActivity {
int gameStart;
public void gameRestart() {
Random ran = new Random();
int gameStart = 1 + (int) (Math.random() * (30));
}
public void buttonClick(View view) {
EditText number = (EditText) findViewById(R.id.number);
Button button = (Button) findViewById(R.id.button);
int num = Integer.parseInt(number.getText().toString());
if (num == gameStart) {
Toast.makeText(this, "Correct!", Toast.LENGTH_SHORT).show();
gameRestart();
}
int gameStart;
public void gameRestart() {
Random ran = new Random();
int gameStart = 1 + (int) (Math.random() * (30));
}
you never alter the value of instance variable gameStart, so it keeps the default value, which is 0.
You create a local variable gameStart in your constructor, which isn't used afterwards.
Alter your code to this to set the instance variable:
int gameStart;
public void gameRestart() {
Random ran = new Random();
gameStart = 1 + (int) (Math.random() * (30));
}
EDIT: as #AndyTurner remarked: you 're also not using your ran instance of the Random class, so you can delete that variable as well.
public void gameRestart() {
Random ran = new Random();
int gameStart = 1 + (int) (Math.random() * (30));
}
Here, I suppose you want to store your random value inside the member variable called gameStart.
It is not the case because you redefine a local variable with the same number in the method. You just have to delete the int before your variable (and delete the ran line because unused)
public void gameRestart() {
gameStart = 1 + (int) (Math.random() * (30));
}
you can try this;
final int random = new Random().nextInt(50) + 30;
// it will generate random number between 30 & 80

How to capture click between several operations, 3,4,5,6, X, 2?

I'm programming a game of cards in Java and everything is going well, but I've come up with an unforeseen reason why I think I can not think of what to use and I want to know what idea to follow. I go:
My game:
My game consists of 6 players, I am always the Player 1 and the other players the computer, therefore I have done with 6 JLabel in a JFrame, each Jlabel means the card that throws jug1 ... jug6, and in the code I take the order of which player wins the hand with an array of integers equal to [3,4,5,6,1,2] assuming player 3 was won by hand.
My problem:
Taking the above arrangement as a reference [3,4,5,6,1,2], it means that in the next hand players [3,4,5,6] must show their card before Player 1, and After Player 1 shows his card, he must show Player 2.
I know how to show the cards of the first four players, but how can I make my program wait for me to click on my selected card and then continue with the last card of Player 2, my main question is how to receive that click Of Player 1 between players, before or after.
Here a fragment:
public void Tirar(JLabel [] label_cartas_en_mesa) //director function
{
cartas_en_mesa = new Vector<Baraja>();
for ( int i =0; i < 6; i++ )
{
switch( orden_de_tiro [i] )
{
case 1: { Tirar_Jugador1(label_cartas_en_mesa, i); break; }
case 2: { Tirar_Jugador2(label_cartas_en_mesa, i); break; }
case 3: { Tirar_Jugador3(label_cartas_en_mesa, i); break; }
case 4: { Tirar_Jugador4(label_cartas_en_mesa, i); break; }
case 5: { Tirar_Jugador5(label_cartas_en_mesa, i); break; }
case 6: { Tirar_Jugador6(label_cartas_en_mesa, i); break; }
default:break;
}
}
}
public void Tirar_Jugador1(JLabel [] label_cartas_en_mesa, int pos)
{ //decision_jug1 = true when I clicked a card and then break a loop.
while(decision_jug1==false) //My wrong idea to wait, I think..
{ }
label_cartas_en_mesa[pos].setIcon( new ImageIcon( Jug1_Barajas.get(pos_baraja_jug1).getImagen() ) );
cartas_en_mesa.add( Jug1_Barajas.get(pos_baraja_jug1) );
Jug1_Barajas.remove(pos_baraja_jug1);
decision_jug1 = false;
}
public void Tirar_Jugador2(JLabel [] label_cartas_en_mesa, int pos)
{
label_cartas_en_mesa[ pos ].setIcon( new ImageIcon( Jug2_Barajas.get(0).getImagen()));
cartas_en_mesa.add( Jug2_Barajas.get(0) );
Jug2_Barajas.remove(0);
}
public void Tirar_Jugador3(JLabel [] label_cartas_en_mesa, int pos)
{
label_cartas_en_mesa[ pos ].setIcon( new ImageIcon( Jug3_Barajas.get(0).getImagen()));
cartas_en_mesa.add( Jug3_Barajas.get(0) );
Jug3_Barajas.remove(0);
}
public void Tirar_Jugador4(JLabel [] label_cartas_en_mesa, int pos)
{
label_cartas_en_mesa[ pos ].setIcon( new ImageIcon( Jug4_Barajas.get(0).getImagen()));
cartas_en_mesa.add( Jug4_Barajas.get(0) );
Jug4_Barajas.remove(0);
}
public void Tirar_Jugador5(JLabel [] label_cartas_en_mesa, int pos)
{
label_cartas_en_mesa[ pos ].setIcon( new ImageIcon( Jug5_Barajas.get(0).getImagen()));
cartas_en_mesa.add( Jug5_Barajas.get(0) );
Jug5_Barajas.remove(0);
}
public void Tirar_Jugador6(JLabel [] label_cartas_en_mesa, int pos)
{
label_cartas_en_mesa[ pos ].setIcon( new ImageIcon( Jug6_Barajas.get(0).getImagen()));
cartas_en_mesa.add( Jug6_Barajas.get(0) );
Jug6_Barajas.remove(0);
}
regards,
Alex
you can have an array of players, all of them including you.
the player may have several members and methods, the 2 methods i want to focus on are play() and isHuman(), in your Game class? there is a method playHand(int) which will control the process:
assume the players array (or list) is
//it contains 6 objects, one of them is You.
List<Player> players = new ArrayList<Player>();
players.add(player1);// add all 6 players...
//make sure when u add human to set isHuman(true)...
and we need to have a method that we will call when it's the Human (you) turn in game, assume it's notifiyHumanPlayer(int)
we also need a local member (class scope) variable the points to the current player.
private int CURRENT_PLAYER = 0;
so your code may look like this:
the method that starts the hand (the round)
private void playHand(int startingPlayerIndex){
for(int i=startingPlayerIndex; i<players.size();i++){
CURRENT_PLAYER = i;
if(!players.get(i).isHuman()){
//not human
notifiyPlayer(i);
players.get(i).play();
}else{
//human
notifiyPlayer(i);
//no call to play();...
break;
}
}//for loop
//when loop ends, all players were done, do what you do at end of each hand...
calculateHandWinner();
}
Shows a simple indicator (arrow) or play some sound...
private void notifiyPlayer(int myIndex){
//it may show an arrow or indeicator on/next player icon, to show which who's playing now
showTurnIndecator(myIndex);
}
when it's your turn, just the onClick of any card you have
private void humanPlayerOnClick(){
//this is the onClick() of the human (when human clicks on any of the cards)
//write the code for drawing a card from human's hand
// now we need to see if human was last player, or not,
if(CURRENT_PLAYER+1 >= players.size()){
//all players were done, do what you do at end of each hand...
calculateHandWinner();
}else{
//still more players after human in the array
playHand(CURRENT_PLAYER+1); // same loop but it will start from the player next to human.
}
}
private void calculateHandWinner(){
//do your logic here ...
//re arrange players list...
playHand(0);//start next hand from first player...
}
not sure if this will suite your current structure you may take something useful out of it.

Can't modify variable inside onClick method

So, I have created a java class to implement onClickListener and inside this class I have written the onClick public method. Outside of this method, I have created an int object and I want to modify this object inside the onClick method. I have researched a lot by also checking other similar SO questions and I have tried many things, like creating the object as a public int, or making it a private int and have another method to change it and then call this method inside onClick. However, nothing seems to work.
The code shown below has the int object created as a private int and named turn. To change it inside onClick, I have first created a public method named changeTurn that modifies it and then I call this method inside onClick.
public class TicTacToe implements View.OnClickListener {
Button buttons[] = new Button[9];
TextView result;
public TicTacToe(Button[] buttonList, TextView text) {
buttons = buttonList;
result = text;
}
//public void
private int turn = 1; // The object that needs to be modified in onCLick
#Override
public void onClick(View v) {
Button b = (Button) v;
if((((Button) v).getText() != "X") && (((Button) v).getText() != "O")) {
if(this.turn == 1) {
b.setText("X");
changeTurn(); // ***Should change the value of turn***
result.setText("Turn is: " + this.turn);
}
if(this.turn == 2) {
b.setText("O");
changeTurn(); // ***Should change the value of turn***
result.setText("Turn is: " + turn);
}
}
}
public void changeTurn() {
if(this.turn == 1) {
this.turn = 2;
}
if(this.turn == 2) {
this.turn = 1;
}
}
}
From what I've tried, the program goes only inside the first if every time I click any of my 9 buttons, whose setOnClickListeners are connected to this onClick method. Also, the value of turn is always 1 when I print it out, which basically means that its value is not changed by changeTurn inside the onClick method.
General info on the application: I'm trying to make a tic-tac-toe game in a 3x3 grid with 9 buttons. Since there would be 2 players, I'm trying to use this turn integer to keep track of whose turn it is to press a button. If turn is 1, the button's text gets changed to X and if turn is 2, it changes to O. Right now, every time I press a button, it always changes to X.
I would really appreciate any help or ideas.
You're setting the turn to 2 and then immediately setting it back to 1.
// turn == 1
if(this.turn == 1) { // true
this.turn = 2; // turn == 2
}
if(this.turn == 2) { // now true!
this.turn = 1; // turn == 1
}
The easiest thing to do is to only enter the second block if the first is skipped, i.e.:
if(this.turn == 1) {
this.turn = 2;
} else if(this.turn == 2) {
this.turn = 1;
}
Alternatively, if you're expecting to expand the block with more turn numbers, use switch:
switch(this.turn) {
case 1:
this.turn = 2;
break;
case 2:
this.turn = 1;
break;
}
The only trouble with switch is if you forget a break statement you end up with an unpredictable mess.
Finally, a quick bit of advice: if you're trying to create a loop of numbers (1 .. n then back to 1) then you should consider the modulus operator (%) like x = x % n + 1;
try use it like this
final private int[] turn = {0}
Then change code to
if(turn[0] == 1) {
b.setText("X");
turn[0]=2; // ***Should change the value of turn***
result.setText("Turn is: " + turn);
}
if(turn[0] == 2) {
b.setText("O");
turn[0]=1; // ***Should change the value of turn***
result.setText("Turn is: " + turn);
}

Random Generator automatically Random

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);

Call random methods in Android

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

Categories