public static void main (String[] args) throws java.lang.Exception{
ArrayList friends = new ArrayList<>(asList("Danny", "Benni", "Marcus", "Pat"));
ArrayList Places = new ArrayList<>(asList("Paris", "Brasil", "Miami", "Jamaica"));
ArrayList Gifts = new ArrayList<>(asList("Snacks", "Photos", "Instrument", "Whine"));
ArrayList[] travelgoals = new ArrayList<>{Places, Gifts};
for (int b = 0; b > friends.length; b++){
if(b > Places.length) {
System.out.println(Places.get().Random((0), Places.length);
}if (b > Gifts.length) {
System.out.println(Gifts.get().Random((0), Gifts.length);
}
}else {
System.out.println("Looks like you got off scottfree!");
}
}
你好,我想用字符串数组在位置上打印随机目标,尽管我认为还远远没有完成。
答案 0 :(得分:0)
您要查找的属性是“大小”。
ArrayList和数组在这方面是不同的。您可以通过“ arr.length”获得数组的长度,并通过“ arrList.size()”获得ArrayList的长度(或大小)。
要在大小范围内生成随机索引,也可以使用Random类的nextInt方法。
下面是与您尝试执行的代码类似的代码,该代码为每个朋友随机选择礼物和地点。
public static void main (String[] args) throws java.lang.Exception{
ArrayList<String> friends = new ArrayList<>(Arrays.asList(new String[]{"Danny", "Benni", "Marcus", "Pat"}));
ArrayList<String> places = new ArrayList<>(Arrays.asList(new String[]{"Paris", "Brasil", "Miami", "Jamaica"}));
ArrayList<String> gifts = new ArrayList<>(Arrays.asList(new String[]{"Snacks", "Photos", "Instrument", "Whine"}));
Random rand = new Random();//This is the Random class that can be used to generate random number. In this case Integers
//just a for loop iterating through all friends
//This will pick a random element from each of places and gifts
//You can get an element of a list by using the get
//method(arrList.get(index))
for(String friend : friends){
System.out.println(places.get(rand.nextInt(places.size())));
System.out.println(gifts.get(rand.nextInt(gifts.size())));
}
}
编辑:使用地图添加了一种更具可扩展性的方法,因为如果您继续增加属性,将很难进行维护。
Map<String, ArrayList<String>> mapOfProperties = new HashMap<>();
mapOfProperties.put("friends",Arrays.asList(new String[]{"Danny", "Benni", "Marcus", "Pat"}));
mapOfProperties.put("places",Arrays.asList(Arrays.asList(new String[]{"Paris", "Brasil", "Miami", "Jamaica"}));
mapOfProperties.put("gifts",Arrays.asList(new String[]{"Snacks", "Photos", "Instrument", "Whine"}));
Set<String> keysOfMap = mapOfProperties.keySet();
Random rand = new Random();
for(int i=0;i<map.get("friends").size();i++){
for(String keyName : keysOfMap){
int keyIndex = rand.nextInt(mapOfProperties.get(keyName).size());
//can put mapOfProperties.get(keyName) in a temp arrayList as well
System.out.print(mapOfProperties.get(keyName).get(keyIndex));
}
}