0

I need to make a method that randomly chooses one of the strings in my "carmake" array. I am stuck in my setCarMake method. The same applies for the color of the car(that method will be made after i finish this one). Here is my current code.

public class Cars {

    public String[] carmake = {"Audi", "BMW" , "Mercedes-Benz", "Lexus", "Volkswagen"};
    public String[] carcolor = {"Black", "Yellow", "Red", "Grey"};
    //
    public int caryear;
    public int speed;

    public void setCarMake(){
        Random rand = new Random(14335);
        carmake.rand.nextInt(carmake.length);
    }

    public int GetYear(){
        int max = 2015;
        int min = 1999;

        Random rand = new Random();
        caryear = rand.nextInt((max-min)+1) + min ;
        return caryear;
    }

    public void execute(){
        System.out.println(caryear + " " + carmake);
    }
}

Please help!

1
  • setCarMake() does not return a value. You need to set the return type to String and add a return statement. Commented Oct 31, 2015 at 20:49

3 Answers 3

4

This is wrong:

carmake.rand.nextInt(carmake.length);

Because it means that rand is an method of carmake array?? Doesn't make sense, right? That's what dot . operator does. They are used to access method.

Try this:

int carMakeRandomIndex = new Random().nextInt(carmake.length);
return carmake[carMakeRandomIndex];

Also, please follow the naming convention.

Sign up to request clarification or add additional context in comments.

3 Comments

@ChuckBIhekwaba Check working demo . Show how you are calling that method
how do i print the car name as a string? it only returns the index number not the name.
@ChuckBIhekwaba If you return carMakeRandomIndex, it will return index, if you return carmake[carMakeRandomIndex], it will return car name at that index. Show your code if you still have trouble and I will take a look at it
2

I think you just need to get a random number in the range of the array (0 to carmake.length - 1) and then use that as the array index.

rand.nextInt(carmake.length); //This should work

Comments

1

Here is an approach to obtain a random element from the carmake array:

final int randomIndex = rand.nextInt() % rcarmake.length;
return carmake[randomIndex];

3 Comments

the expression rand.nextInt() % rcarmake.length may be biased in the sense that not all index values appear with the same probability.
[Ljava.lang.String;@677327b6 - that is the output for your code. Similar thing happened to me earlier.
@ChuckBIhekwaba this is not the output of his code snippet. Your trying to print 'carmake', not the returned random String.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.