在Java中,我正在为循环嵌套,但它给了我一个错误消息

时间:2017-06-15 07:32:35

标签: java loops for-loop

我尝试使用EXACT相同格式进行循环练习,并且不会像这样做出错误消息。在我引入外部循环(使用int j)之前,内部循环(使用int i)完美地工作:

private static void mBTI(){
    Scanner console = new Scanner(System.in);
    Random rand = new Random();

    //Practice loop
    int wtf = console.nextInt();
    for (int k = 1; k <= wtf; k++){
        for (int m = 1; m <= 2; m++){
            System.out.println("derp");
        }
    }        

    //Error loop
    System.out.println("How many results do you want? (Type a numerical value.)");
    int amount = console.nextInt();
    String[] types = {"E","I","N","S","F","T","J","P"};
    int loop = 0;
    for(int j = 1; j <= amount; j++){
        for(int i = 1; i <= 4; i++){
            int randType = rand.nextInt(2);
            randType = loop+randType;
            System.out.print(types[randType]);
            loop = loop+2;
        }
        System.out.println("");
    }
}

1 个答案:

答案 0 :(得分:-1)

你可能会获得一个超出范围的索引例外。确保使用randType = randType%types.length(或其他东西来保持randType在边界内)。