【问题标题】:I am trying to get a random item from an array that is in an ArrayList我正在尝试从 ArrayList 中的数组中获取随机项
【发布时间】:2017-08-03 19:59:18
【问题描述】:

我正处于创建我认为本质上应该是一个简单的小程序的开始阶段。但是,我对 java 很陌生,所以事实证明它比预期的要困难。这就是我将编译的内容,除了最后的打印部分。首先,我不明白为什么不呢?其次,我需要创建一个随机生成器来从 arrayList 中的一个数组中随机选择一个项目。我一直在尝试很多东西,但就是无法让它发挥作用。我想我什至对将代码放在哪里感到困惑。帮助!

import java.util.*;

public class RestaurantSelector1 {

    //public static class Tribeca4star{
    final static String[] italian = {"Pepolino Restaurant", "Locanda Verde", "Scalini Fedeli", "Gran Morsi", "Ecco", "Tutto il Giorno", "The Odeon", "Mamo Restaurant", "Petrarca Cucina E Vino", "Osteria Morini"};
    final static String[] japanese = {"Shigure", "Sushi Azabu", "Ichimura", "Brushstroke", "Takahachi Tribeca Restaurant", "Ninja New York", "DOMODOMO", "Sushi of Gari", "Hirohisa", "Blue Ribbon"};
    final static String[] french = {"Bouley", "Batard", "Racines", "The Odeon", "MAMO Restaurant", "La Sirene", "Le Coucou", "Balthazar", "Taureau", "L'Appart"};
    final static String[] american = {"American Cut Steakhouse", "Marc Forgione", "The Bennett", "Little Park", "The Odeon", "Yves", "Tribeca Grill", "Atera", "Batard", "Brandy Library"};
    final static String[] chinese = {"Mr. Chow", "Macao", "Khe-Yo"};
    final static String[] spanish = {"Tablao", "Sazon", "Despana", "Estancia 460", "Westside Coffee Shop", "Anejo Tribeca", "Terra Wine Bar", "Darlene", "Sophia's Cuban Cuisine", "Amada"};
    final static String[] cafe = { "Arcade Bakery", "Galerie de Cafe", "The Wooly Daily", "Cafe Belle", "Baked", "Laughing Man Coffee and Tea","La Colombe Coffee", "Kuro-Obi at Canal Street Market", "Blue Spoon Coffee", "Everyman Espresso"};
    final static String[] thai = {"khe-yo", "Empire", "Macao"};
    final static String[] indian = {"Tamarind"};
    final static String[] viatnamese = {"Khe-Yo", "Macao"};

    public static void main(String[] args){
        ArrayList<String[]> cuisine = new ArrayList<>();

        cuisine.add(italian);
        cuisine.add(japanese);
        cuisine.add(french);
        cuisine.add(american);
        cuisine.add(chinese);
        cuisine.add(spanish);
        cuisine.add(cafe);
        cuisine.add(thai);
        cuisine.add(indian);
        cuisine.add(viatnamese);

        System.out.println(cuisine[0,1]);
    }
}

【问题讨论】:

  • 请将语法错误问题与“随机选择项目”问题分开。

标签: java arrays arraylist random printing


【解决方案1】:

您可以通过创建一个新的 Random() 实例并从 nextInt[0,cuisine.size())[0,cuisine.get(rnd).length) 获取随机 int 来生成随机索引

Random rand = new Random();                         //RN Generator
int rnd     = rand.nextInt(cuisine.size());         //random lang index
int rndWord = rand.nextInt(cuisine.get(rnd).length) //random word index

然后您可以使用带有.get(rnd) 的随机索引来访问您想要的String[],并使用[rndWord] 获取该数组中的随机条目。

System.out.print( cuisine.get(rnd)[rndWord] );      //print out random word

【讨论】:

  • 但是美食应该是.size的吧?当我这样做时,它说 size 没有公共访问权限?
  • 确保你在做 .size() 而不是 .size @danaCarlin
  • @danaCarlin 查看我的编辑以从所有集合中获取随机单词
【解决方案2】:

试试System.out.println(cuisine.get(0)[1])

您想使用ArrayList.get(int index) 来检索您的String[] 对象,然后您可以指向该数组中的字符串

【讨论】:

  • 嗨!我如何从说意大利人那里得到一家随机餐厅?除了最后一行,一切都编译好了,我不知道如何获得特定类型的美食,然后是其中的随机餐厅。
  • 我希望你能够思考它而不只是给出答案,否则你不会学习。您想要做的是将其视为多个步骤。你需要一个随机整数。您需要意大利食物的字符串 [],意大利食物的字符串 [] 位于 ArrayList 中。从 ArrayList 中获取那个 String[],并从那个 String[] 中获取一个随机索引。如果不是全部在一条线上,对您来说可能会更容易。分配每个变量并像那样工作。如果您需要更多帮助,请回复消息
【解决方案3】:

要从随机菜系中获取随机餐厅,您可以执行以下操作:

final Random random = new Random();
final String[] randomCuisine = cuisine.get(random.nextInt(cuisine.size()));
final String randomRestaurant = randomCuisine[random.nextInt(randomCuisine.length)];

【讨论】:

    【解决方案4】:

    如果我对您的理解正确,您希望从列表中随机获得一个String[],然后从String[] 中获得一个随机条目。您可以通过使用 java.util.Random 类来获得它:

    public static String getRandom(List<String[]> list) {
        Random random = new Random();
        int listAccess = random.nextInt(list.size());
        String[] s = list.get(listAccess);
        return s[random.nextInt(s.length)];
    }
    

    然后,只需将System.out.println(cuisine[0,1]); 替换为

    System.out.println(getRandom(cuisine));
    

    对于您的代码为什么无法编译的问题,这是因为您必须使用 .get(&lt;index&gt;) 来获取 List,并使用 [&lt;index&gt;] 来访问数组中的项目。

    【讨论】:

      【解决方案5】:

      首先,你的 import 语句不会像写的那样编译。

      import java.util.; //will not compile without class name after '.' import java.util.*; //will compile: You could also specify a specific class name in place of the *

      至于生成随机餐厅,您可以通过将以下代码添加到您的 main 方法来实现。我已经添加了 cmets 进行解释。

      public static void main(String[] args) {
          ArrayList<String[]> cuisine = new ArrayList<>();
      
          cuisine.add(italian);
          cuisine.add(japanese);
          cuisine.add(french);
          cuisine.add(american);
          cuisine.add(chinese);
          cuisine.add(spanish);
          cuisine.add(cafe);
          cuisine.add(thai);
          cuisine.add(indian);
          cuisine.add(viatnamese);
      
          Random randomArrayListIndex = new Random();
      
          int randomCuisine = randomArrayListIndex
                  .nextInt(cuisine.size());
      
          String[] randomArray = cuisine.get(randomCuisine); // get random array
                                                              // from ArrayList
      
          Random randomArrayIndex = new Random();
      
          String randomRestaurant = randomArray[randomArrayIndex // get random element
                                                              // from array
                  .nextInt(randomArray.length)];
          System.out.println(randomRestaurant);
      }
      

      【讨论】:

      • (randomArray.length - 1) - 0) + 1这是什么目的?
      • 好收获。我写得太快了,并没有完全考虑清楚......我最初认为我需要从数组的长度或 ArrayList 的大小中减去 1,因为该数字不是有效的索引。
      • randomArrayIndex.nextInt(size)会自动从[0,size-1] or [0,size)获取下一个int,因为它不包含参数。 :)
      • 是的,我记得在您发表初步评论后。不时查看 API 是值得的 :)
      猜你喜欢
      • 1970-01-01
      • 2022-06-16
      • 2017-08-13
      • 1970-01-01
      • 2022-10-13
      • 2017-02-01
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多