【问题标题】:Printing the index of an array element after choosing the largest element选择最大元素后打印数组元素的索引
【发布时间】:2017-04-08 23:09:09
【问题描述】:

首先,如果这个问题的标题有任何错误,我很抱歉。我只是不知道如何把它放在一个问题中。以下代码掷骰子一千次,并显示掷骰子上的数字的次数。我想打印最大数字的索引而不是元素。

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 循环。与其将给定 pos 处的数组值存储到最大值中,不如将索引存储在那里,并与当前最大值 val 所在的索引处的值进行比较,而不是与数字进行比较。
  • 我用 if 语句打开了另一个循环来检查 max 的值是否等于数组元素,然后将索引分配给另一个变量然后打印它....但是还有其他方法吗可以吗?

标签: java arrays


【解决方案1】:

如果您使用 for-each 循环(就像您所做的那样),您将无法(直接)获取数组的索引,而是需要使用普通的 for 循环作为如下代码中的 cmets 所示:

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

【讨论】:

  • 谢谢。我很困惑,如果我按照你说的做,我的索引总是为 6。
  • 不,有if条件,所以maxIndex只有在有更大的值时才会被赋值
【解决方案2】:

您必须将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);

这将打印获得的最大滚动数。

【讨论】:

    猜你喜欢
    • 2019-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-13
    • 2013-06-21
    • 1970-01-01
    • 1970-01-01
    • 2018-10-17
    相关资源
    最近更新 更多