dimanche 6 octobre 2019

I can't get a 4 digits random number in JAVA

I'm really new to java. I need to create a method that creates 4 digits random number like 0050, 0100, 9999. So each digit of that number has a limit from 0 to 9!

Here is what I found:

package randomNumber;

import java.util.HashSet;
import java.util.Random;
import java.util.Set;

public class RandomNumber {

    public static Set<Integer> getRandom(Set<Integer> setInt){

        setInt = new HashSet<Integer>();
        for (int i = 0; i < 4; i++){
            Random random = new Random();
            i = random.nextInt(10);     
            setInt.add(i);          
        };

        return setInt;
    }




    public static void main(String[] args) {
        System.out.println(getRandom(null));

    }

}

So I didn't really understand why in the main I had to set the variable in the getRandom method to "null". System.out.println(getRandom()); didn't work out. I'd appreciate if someone coult explain that to me

Anyway I was happy that I had no error messages until I run the code several times. I have either 1 digit number, or 2 digits number and sometimes 3 digits number but it seems that I can never have a 4 digits number whereas I have indicated in my for loop that i < 4. I can't maintain the results to 4 digits. Why?

I'm lost! If anyone can help me, I would be gratefull. I'm also wondering if I'm using the right method as I need a four digits number and I used a hashset which give me ideally a 4 elements table. Is there another way than a hashset?

Thanks guys!




Aucun commentaire:

Enregistrer un commentaire