特定的数组索引和调用方法java

时间:2017-08-22 06:09:47

标签: java arrays methods

您好我对方法有一些疑问。所以我写下了用户键入1到12月温度的代码,它会打印出哪个月有最高温度和温度值。

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    final int size = 12;
    String[] month = { "January", "February", "March", "April", "May", "June", "July", "August", "September",
            "October", "November", "December" };
    double[] temp = new double[size];

    for (int i = 0; i < month.length; i++) {
        System.out.println("Enter temperature on first day of " + month[i]);
        temp[i] = sc.nextDouble();

    }
    int maxIndex = maxV(temp);
    System.out.print("Highest temperature in " + month[maxIndex] + " with a temperature of " + temp[maxIndex]);
}

public static int maxV(double temp[]) {
    double maxVL = temp[0];
    int indexM = 0;
    for (int i = 0; i < temp.length; i++) {
        if (temp[i] > maxVL) {
            maxVL = temp[i];
            indexM = i;
        }
    }
    return indexM;
}

所以这是我的代码,我不明白月份[maxIndex]是如何工作的,因为我返回了当月的最高指数?它不应该是maV(临时)吗?至于温度值,temp [maxIndex]怎么办?

2 个答案:

答案 0 :(得分:0)

而不是, System.out.print(“最高温度”+月[maxIndex] +“,温度为”+ temp [maxIndex]);

你可以用, System.out.print(“最高温度”+月[maxV(temp)] +“,温度为”+ temp [maxV(temp)]);

即使在这里你也会失去温度的十进制值,但我认为这将清除你的怀疑。

答案 1 :(得分:0)

maxV(temp)方法中,您实际传递每个月的温度数组(由temp []数组的索引确定的月份),然后返回temp[]数组的最大温度值索引{{1} 1}}。

maxIndex - &gt;将返回具有最高温度值的月份。

month[maxIndex] - &gt;将返回该月的最高温度值。

示例:

temp[maxIndex]

如果最大索引为month = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" } temp = {22, 20, 35, 15, 20, 22, 26, 30, 18, 27, 20, 19} ,则该月份将是第三个i = 2

month[2] = "March"的温度:"March"