简体   繁体   English

java-如何使用方法从数组中返回随机字符串?

[英]java - How to return random String from an array using methods?

I need to make a method that randomly chooses one of the strings in my "carmake" array. 我需要制定一种方法,在我的“ carmake”数组中随机选择一个字符串。 I am stuck in my setCarMake method. 我陷入了setCarMake方法。 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! 请帮忙!

This is wrong: 这是错误的:

carmake.rand.nextInt(carmake.length);

Because it means that rand is an method of carmake array?? 因为这意味着rand是carmake数组的一种方法? 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. 另外,请遵循命名约定。

我认为您只需要获取数组范围内的随机数(0到carmake.length-1),然后将其用作数组索引即可。

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

Here is an approach to obtain a random element from the carmake array: 这是一种从carmake数组中获取随机元素的方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM