循环外的java打印

循环外的java打印,java,Java,我是一名学习编程的高中生,现在我无法回避这个问题。我试图在循环外打印平均值,但我不知道如何打印 for (int index = 0; index < temperature.length; index++) { double tempSum = 0; tempSum += temperature[index]; double averageTemp = tempSum / temperature.length; double rainSum = 0;

我是一名学习编程的高中生,现在我无法回避这个问题。我试图在循环外打印平均值,但我不知道如何打印

for (int index = 0; index < temperature.length; index++) {
    double tempSum = 0;
    tempSum += temperature[index];
    double averageTemp = tempSum / temperature.length;
    double rainSum = 0;
    rainSum += precipitation[index];

}

//Output: display table of weather data including average and total
System.out.println();
System.out.println("           Weather Data");
System.out.println("      Location: " + city + ", " + state);
System.out.println("Month     Temperature (" + tempLabel + ")     Precipitation (" + precipLabel + ")");
System.out.println();
System.out.println("***************************************************");

for (int index = 0; index < precipitation.length; index++) {
    System.out.println(month[index] + "     " + temperature[index] + "     " + precipitation[index]);
}

System.out.println("Average Temperature: " + averageTemp + "    Total Rainfall: " + rainSum);
for(int index=0;index
这些评论提供了正确的想法。Java中的变量具有块作用域,这意味着它们在声明它们的块之外不可用。JavaScript有“提升”,这意味着,无论在哪里使用var关键字,都将定义变量


将变量声明移到“for”块之外。然后,当循环完成时,它们将可用。如果需要知道“index”变量的最后一个值,也可以对其执行此操作。通常,这是不必要的。

在代码中,变量
averageTemp
仅在
for
-循环中存在/可访问。 要在循环外部访问它,您需要在循环之前声明外部。有点

double averageTemperature;
for (....) {

for
-循环中,您可以将温度相加到
tempSum
,循环完成后,将
tempSum
除以循环中迭代的项数。如果您想这样做,请记住,在进入循环之前也必须声明
tempSum

您需要在循环之外声明变量。你需要在for循环外声明tempSum,并在for循环外计算averageTemp如果你在for循环内做了更糟糕的事情rainsum将永远不会超过0定义循环外的变量要解决任何问题,你需要了解,需要做什么。然后一步一步地编码。我敢肯定,在发布问题之前,您从未亲自检查过代码。