You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于Arrays.toString()使用:如何仅打印对应月份的温度元素

Fix: Only Return the Target Month's Temperature Instead of Full Array

Hey there! Let's break down why you're seeing the entire array instead of just the single month's temperature, and how to fix it.

The Root Issue

Right now, your AvgTemp.getTemp() method is returning the full array of all monthly temperatures instead of extracting just the element that corresponds to the month you're targeting (like January). That's why Arrays.toString() is printing every value in the array, including the zeros for unused months.

Solution Options

Here are two straightforward ways to fix this:

Option 1: Modify getTemp() to Accept a Month Index

Update the method to take an index parameter (matching your month's position in the array—e.g., 0 for January, 1 for February, etc.) and return a single-element array containing just that month's temp:

public class AvgTemp {
    // Assume this is your existing temperature array
    private static double[] tempArray = {45.0, 40.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};

    public static double[] getTemp(int monthIndex) {
        // Return a new single-element array with the target temp
        return new double[]{tempArray[monthIndex]};
    }
}

Then call it with the correct index for your month:

// January maps to index 0
System.out.println("The average temp for January is " + Arrays.toString(AvgTemp.getTemp(0)));

Option 2: Extract the Target Element When Calling

If you don't want to change the getTemp() method's signature, pull the specific element from the full array and wrap it in a single-element array before printing:

double[] allTemperatures = AvgTemp.getTemp();
// Grab the January temp (index 0) and wrap it in a new array
double[] januaryTemp = new double[]{allTemperatures[0]};
System.out.println("The average temp for January is " + Arrays.toString(januaryTemp));

Quick Check

Double-check that your month-to-index mapping is correct (e.g., January = 0, February = 1, etc.) to avoid ArrayIndexOutOfBoundsException or grabbing the wrong month's data.

内容的提问来源于stack exchange,提问作者Courtney Creeden

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 02:28:41