dimanche 16 mai 2021

Problem with running a number ID generator code in JAVA [closed]

I'm trying to design a number (ID) generator system that generate numbers between 0-99999999 (8-digits) that supports two functions: a. int getNumber(); b. int requestNumber();

This is my code and no errors show but it won't run. Hopefully someone can help me make it run, as I don't know what I'm doing wrong.

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

class IDGenerator{
    //set to store assigned numbers
    Set<Integer> set;
    static final int MAX = 99999999;
    IDGenerator(){
        set = new HashSet<Integer>();
    }

    public int getNumber(){
        //Generate a random number until the number generated is not assigned
        Random random = new Random();
        int gen = random.nextInt(MAX+1);
        while (requestNumber(gen)==0){
            gen = random.nextInt(MAX+1);
        }
        return gen;
    }

    public int requestNumber(int n){
        //Check if it is already in the set
        if(!set.contains(n)){
            set.add(n);
            return 1;
        }
        return 0;
    }

}

class Main{
    public static void main(String[] args) {
        IDGenerator generator = new IDGenerator();
        for(int i=1;i<=10;i++){
            System.out.println(generator.getNumber());
        }
    }
}



Aucun commentaire:

Enregistrer un commentaire