vendredi 23 juin 2017

Java Random is print out the same number every time

I have a simple block of that there is a random number, when pressing a button the text replacing with that number.

Random r = new Random();
int numb = r.nextInt(10);

this works fine, while

Random r = new Random(10);
int numb = r.nextInt(10);

this prints always 3. The number is always 3 if I put 10 in to the paranthesis of Random. Why it's always equals to 3? Here the whole code in Android Studio

package com.flafel.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.Random;

public class MainActivity extends AppCompatActivity {

    TextView text;
    Button buton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        text = (TextView) findViewById(R.id.text1);
        buton = (Button) findViewById(R.id.button);

        buton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Random r = new Random(10);
                int numb = r.nextInt(10);

                switch (numb)
                {
                    case 1: text.setText("Number is 1");
                        break;
                    case 2: text.setText("Number is 2");
                        break;
                    case 3: text.setText("Number is 3");
                        break;
                    case 4: text.setText("Number is 4");
                        break;
                    case 5: text.setText("Number is 5");
                        break;
                    case 6: text.setText("Number is 6");
                        break;
                    default:
                        text.setText("Number is bigger than 6 or equals 0.");
                        break;
                }

            }
        });



    }
}

I worked with Python so far and I couldn't understand this behaviour.




Aucun commentaire:

Enregistrer un commentaire