写一个温度。排列

时间:2014-08-29 00:41:36

标签: java arrays

我已经编写了代码,每个月都会采用临时值,然后显示和计算当年的总降雨量,平均降雨量,最多降雨量和最低降雨量。如何用实际的月份名称替换最多和最少的降雨?

到目前为止

代码:

import java.util.Scanner;
import java.text.DecimalFormat;

public class Rainfall
{
  public static void main(String[] args)
  {
    String [] months={"Janurary","Febuary","March","April","May","June","July","August","September","October","November","December"};

    final int MONTHS = 12;
    double[] rain = new double[MONTHS];

    initRain(rain);
    double total = totalRain(rain);
    double average = averageRain(rain, total);
    int most = mostRain(rain);
    int least = leastRain(rain);
    // Decimal Format
    DecimalFormat digit = new DecimalFormat("#.0");
    // Output 
    System.out.println("The total rainfall of the year is " + digit.format(total));
    System.out.println("The average rainfall of the year is " + digit.format(average));
    System.out.println("The month with the highest amount of rain is " + (most + 1));
    System.out.println("The month with the lowest amount of rain is " + (least + 1));
  }

  public static void initRain(double[] array)

  {
    Scanner keyboard = new Scanner(System.in);
    for (int x = 0; x < array.length; x++)
    {
      System.out.print("Enter Rainfall for month " + (x + 1) + ": ");
      array[x] = keyboard.nextDouble();
    }
  }
  public static double totalRain(double[] array)
  {
    double total = 0;
    for (int x = 0; x < 12; x++)
      total += array[x];
    return total;
  }
  public static double averageRain(double[] array, double total)
  {
    return total / array.length;
  }
  public static int mostRain(double[] array)
  {
    double maximum = array[1];
    int value = 0;
    for (int i=0; i < 12; i++) {
      if (array[i] >= maximum) {
        maximum = array[i];
        value = i;
      }
    }
    return months[index];
  }
  public static int leastRain(double[] array)
  {
    double minimum = array[0];
    int value = 0;
    for (int i=0; i < 12; i++)
    {
      if (array[i] <= minimum) {
        minimum = array[i];
        value = i;
      }
    }
    return value;




  }
}

2 个答案:

答案 0 :(得分:0)

嗯,你有一个索引,而且你有几个月的名字,所以...?

String most = months[mostRain(rain)];

答案 1 :(得分:0)

我猜这段代码甚至没有编译

public static int mostRain(double[] array)
  {
    double maximum = array[1];
    int value = 0;
    for (int i=0; i < 12; i++) {
      if (array[i] >= maximum) {
        maximum = array[i];
        value = i;
      }
    }
    return months[index];
  }

因为它期望返回int但你返回String(也不存在索引),所以你想要的是

public static int mostRain(double[] array)
  {
    double maximum = 0.00;  // change this too
    int value = 0;
    for (int i=0; i < 12; i++) {
      if (array[i] >= maximum) {
        maximum = array[i];
        value = i;
      }
    }
    return value; // change this
  }

然后你可以在上面使用它

System.out.println("The month with the highest amount of rain is " + months [mostRain (rain)]);

当然,对leastRain进行类似的更改。