Reputation: 13
I'm creating a program which generates a random car with a random price, year, colour, etc... I know how to randomize the year by using Math.random, but I'm not sure how to get a random colour. I think making an array full of colours and picking a random element from the array, but I'm not sure how to do that. Any help is greatly appreciated
Upvotes: 1
Views: 2636
Reputation:
You can use the Random
method (import java.util.Random;). Here's an example to make a random company, and you can copy this for the model, color, price, etc.
String[] Company = {"Honda", "Toyota", "Ford", "Chevrolet", "Lexus", "Jeep"}// add whatever companies you want here
Random rand = new Random();
int NumberOfAnswers = Company.length;
int pick = rand.nextInt(NumberOfAnswers);
String CompanyChoice = Company[pick];
System.out.println("The company of your car is " + CompanyChoice);
Repeat this for the model, color, or whatever else you want. Note: you do not need to repeat Random rand = new Random();
, because it only needs to be declared once.
Upvotes: 1
Reputation: 153
I think that the most convenient way is making an enum with a method to produce a random element. This way we achieve encapsulation and reuse.
public enum Colour {
Red,
Orange,
Green;
private static final List<Colour> VALUES =
Collections.unmodifiableList(Arrays.asList(values()));
private static final Random RANDOM = new Random();
public static Colour randomColour() {
return VALUES.get(RANDOM.nextInt(VALUES.size()));
}
}
Upvotes: 0