整数的ArrayList到较小的整数数组

时间:2016-09-20 09:21:07

标签: java arrays

我正在构建我的第一个程序。我们的想法是从文件中读取问题列表,然后允许用户选择一些随机问题。例如,该计划将有30个问题。但是,用户可能只想一次练习5个问题。我已经达到了第一次真正的挂断。

我正在编写一种方法,允许用户输入他们想要问的问题数量。该方法将输出一个x个随机数的数组,其数量不超过问题量。然后,我计划使用该数组从我已经成功构建的另一种方法中调用实际问题。

以下是方法的代码

public int [] ranQuest(int numQs, int totalQs) {

    int [] numberQs = new int [numQs];
    int maxNum = totalQs;

    ArrayList<Integer> allQs = new ArrayList(); 

    for (int x = 0; x < maxNum; x++) {
        allQs.add(x);
    }

    Collections.shuffle(allQs);

    for(int x = 0; x < numberQs.length; x++) {    
       numberQs[x] = allQs.get(x);
    }

    return numberQs;
}

我已经注释了我的故障排除打印行。 这是我的测试代码:

public static void main(String[] args) {

    GameLoad gl = new GameLoad();
    Scanner scan = new Scanner(System.in);
    String userAns = null;
    Random randInt = new Random();
    QuestGen questGen = new QuestGen();

    int [] quests = questGen.ranQuest(4, 10);

    for (int quest : quests) {
        System.out.println(quests[quest]);
    }
}

当我运行3,3或4的输入代码时,它的sudo工作。我没有得到一个outofbounds异常错误,但数字不符合我的预期。当我运行代码为3,10或5时,30 ...我得到一个异常的异常错误,这让我感到沮丧,因为我认为我的for循环是好的。

我做了很多搜索,似乎我可能在尝试将整数转换为整数时遇到问题,或者我的for循环填充int数组是不对的。有没有办法或更好的方法然后路径我采取一个X坑的数组填充顺序混合那些,然后填充一个新的较小的数组?

提前致谢 乔乔

1 个答案:

答案 0 :(得分:2)

for (int quest : quests) {
    System.out.println(quests[quest]);
}

将其更改为

for (int quest : quests) {
    System.out.println(quest);
}

现在,如果您的数组包含例如元素10,11和12 您要求quests[10]quests[11]quests[12]的值显然未定义,因为数组只有三个元素。