簡體   English   中英

選擇最大元素后打印數組元素的索引

[英]Printing the index of an array element after choosing the largest element

首先,如果這個問題的標題有誤,我感到抱歉。 我只是不知道如何提出問題。 以下代碼擲骰子一千次,並顯示擲骰子上數字的次數。 我想打印最大數字而不是元素的索引。

import java.util.Random;

public class apples {
public static void main(String args[]){
    Random rand = new Random();
    int a[] = new int[7];

    for(int i = 1; i<1001; i++){
        ++a[rand.nextInt(6) + 1];
    }
    System.out.println("Roll\tTimes");

    for(int j=1; j<a.length; j++){
        System.out.println(j + "\t\t" + a[j]);
    }
    int max = a[0];
    for (int i : a) {
        if (max < i) {
            max = i;

        }
    }
    System.out.println("The winning number is " + max);

}

}

編輯:

我想出了如何獲取索引,但是有更簡單的方法嗎?

import java.util.Random;

public class apples {
public static void main(String args[]){
    Random rand = new Random();
    int a[] = new int[7];
    int winner = 0;

    for(int i = 1; i<1001; i++){
        ++a[rand.nextInt(6) + 1];
    }
    System.out.println("Roll\tTimes");

    for(int j=1; j<a.length; j++){
        System.out.println(j + "\t\t" + a[j]);
    }
    int max = a[0];
    for (int i : a) {
        if (max < i) {
            max = i;

        }
    }
    for(int j=0; j<a.length; j++){
        if(max==a[j]){
            winner = j;
        }
    }
    System.out.println("The winning number is " + winner);

}

}

您必須將foreach更改為索引for循環,並跟蹤最大數量的索引。

將此部分更改為

int max = a[0];
   for (int i : a) {
      if (max < i) {
        max = i;

    }
}

更改它

    int max = a[0];
    int index = 0;
    for (int j = 0, aLength = a.length; j < aLength; j++) {
        int i = a[j];
        if (max < i) {
            max = i;
            index = j;
        }
    }
    System.out.println("The winning number is " + max);
    System.out.println("The winning index is " + index);

這將打印達到該數量的最新數量。

如果使用for-each循環 (如您所做的那樣), 則將無法(直接)獲取數組的索引 ,而是需要使用普通的for循環,如下面代碼中的注釋所示:

int max = a[0];
int maxIndex = 0;//take a variable & Initialize to 0th index
for (int i=0; i<a.length;i++) {//normal for loop, not for each
    if (max < a[i]) {
        max = a[i];
        maxIndex = i;//capture the maxIndex
    }
}
System.out.println(": maxIndex :"+maxIndex);//print the maxIndex

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM