关于Arrays.toString()使用:如何仅打印对应月份的温度元素
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

