Java将数组元素索引与索引进行比较

时间:2015-02-12 07:51:22

标签: java arrays indexing compare

这是我的代码:

public static void main(String[] args) {

    int lotteryNumbers[] = new int[5];
    int playersNumbers[] = new int[5];
    int winNum = 0;


    Scanner in = new Scanner(System.in);
    Random r = new Random();
    // array med 5 heltal

    //skapa en for loop som fyller upp arrrayen
    //med slumpade tal från klassen Random
    for (int i = 0; i < lotteryNumbers.length; i++) {
        lotteryNumbers[i] = 0 + r.nextInt(9);
        System.out.print(lotteryNumbers[i] + "\t");

    }
    System.out.println();

    for (int i = 0; i < playersNumbers.length; i++) {
        //System.out.println("Var god ange ett nummer mellan 0-9: ");
        //playersNumbers[i]=in.nextInt();
        playersNumbers[i] = 0 + r.nextInt(9);

    }
    for (int i = 0; i < playersNumbers.length; i++) {

        System.out.print(playersNumbers[i] + "\t");

    }
    System.out.println();

    if (lotteryNumbers[0]==playersNumbers[0])
         winNum++;
         if (lotteryNumbers[1]==playersNumbers[1])
              winNum++;
              if (lotteryNumbers[2]==playersNumbers[2])
                   winNum++;
                   if (lotteryNumbers[3]==playersNumbers[3])
                        winNum++;
                        if (lotteryNumbers[4]==playersNumbers[4])
                            winNum++;

     System.out.println("You have " + winNum + " winning numbers");

}

}

我需要将数字索引与索引进行比较。如你所见,我有5个if语句。我想知道我是否可以用循环代替它?

我已经尝试过这样做了:

for (int i = 0; i < lotteryNumbers.length; i++) {

        for (int j = 0; j < playersNumbers.length; j++) {

       if (lotteryNumbers[i] == playersNumbers[j]) {
                winNum++;

            }
        }
    }

但是这会将每个索引与每个索引进行比较,而不仅仅是索引的索引。我想知道如何编写比较索引到索引的循环?

2 个答案:

答案 0 :(得分:2)

仅使用一个循环。这样,可以在两个数组中使用相同的索引。

for (int i = 0; i < lotteryNumbers.length; i++) {
    if (lotteryNumbers[i] == playersNumbers[i]) {
            winNum++;
    }
}

答案 1 :(得分:1)

你工作太辛苦了。 :-)只需一个循环,而不是两个,并对两个数组使用相同的索引变量:

for (int i = 0; i < lotteryNumbers.length; i++) {
    if (lotteryNumbers[i] == playersNumbers[i]) {
        winNum++;
    }
}