Search code examples
javaarraysstringassert

How to choose a random element in this array only once across all declared objects in main?


I would like these objects to print the random names in the array only once across all the objects declared in main. My problem is that it would show the names twice or more.

public class Fighters {

    private static String[] names = { "Terminator", "Slicer","Ninja", "cow", "Robot", "littlegirl" };
    private static int id = 0;

    public Fighters(){
        id++;
        name = names[(int) (Math.random() * names.length)];
    }

    public String toString(){
        return String.format(id+" Name:%-5s, name);
    }
}

In main() I have these objects

Fighters a1 = new Fighters();
System.out.println(a1.toString());

Fighters a2 = new Fighters();
System.out.println(a2.toString());

Fighters a3 = new Fighters();
System.out.println(a3.toString());

Solution

  • If you want to keep your name assignment in the Fighter class, use a static variable to hold the list of used names. You need to make sure you have not created more Fighters than the names array. Otherwise this will loop indefinitely. I will leave it up to you to figure that part. This should at least get you on the right track.

    import java.util.ArrayList;
    
    public class Fighter {
    
        private String name;
    
        private static String[] names = { "Terminator", "Slicer","Ninja", 
                 "cow", "Robot", "littlegirl" };
        private static int id = 0;
        private static ArrayList<String> usedNames = new ArrayList<String>();
    
    
        public void Fighters(){
            id++;
            String checkedName = "";
            do{
                checkedName = names[(int) (Math.random() * names.length)];
                if(!usedNames.contains(checkedName)) break;
            }
            while(true);
            name = checkedName;
            usedNames.add(name);
        }
    
        public String toString(){
            return String.format(id+" Name:%-5s, name");
        }
    
    }