【发布时间】:2019-04-17 13:04:11
【问题描述】:
我刚刚创建了一个包含食物列表的 ArrayList,我想从 ArrayList 中随机打印出两种食物。我该怎么做呢?
我在网上看过,我试过了。它有效,但是当我复制它时,它会打印出两次相同的食物(总是)。
public class Main {
public static void main(String[] args) {
int pizza = 1;
int burger = 2;
int fries = 3;
int FishnCHips = 4;
List<String> foodList = new ArrayList<String>();
System.out.print("Which food do you want?");
foodList.add("pizza");
foodList.add("burger");
foodList.add("fries");
foodList.add("Fish and chips'");
int randomIndex = (int) (Math.random()) * foodList.size();
System.out.println("Two random foods : " + foodList.get(randomIndex));
int secondrandomIndex = (int) (Math.random()) * foodList.size();
System.out.println("Two random foods : " + foodList.get(secondrandomIndex));
我真正想要的只是从上面的 ArrayList 中打印出两个项目。没有别的了。
【问题讨论】:
-
使用 Random 类并且只使用一个实例,然后调用 nextInt 两次
标签: java