java程序 - 输出不是预期的

时间:2013-05-10 09:21:05

标签: java algorithm

我的程序输出有问题。它应该能够找到总降雨量,平均降雨量以及降雨量最少/最多的月份。该程序工作正常,但是当我运行它时,它总是显示1月为最低(当不是)而12月是最高(当不是时)。我希望找出我做错了什么。

public class RainFall {
double[] rainArray = new double [SIZE]; 
public static final int SIZE = 12;



RainFall() {     
}
public RainFall(double[] r){
    rainArray = new double[SIZE];

}

public void setArrayValueAtIndex( double Val, int Index) {
    if (Index < SIZE - 1)
        return;

    rainArray[Index] = Val;
}

public double getTotal() {
    double total = 0;
    for (int i = 0; i < SIZE; i++){
        total += rainArray[i];
    }

    return total;
}

public String getMonth ( int monthIndex) {
    switch( monthIndex )
    {
        case 0 : return "January";
        case 1 : return "February";
        case 2 : return "March";
        case 3 : return "April";
        case 4 : return "May";
        case 5 : return "June";
        case 6 : return "July";
        case 7 : return "August";
        case 8 : return "Septemeber";
        case 9 : return "October";
        case 10 : return "November";
        case 11 : return "December";
        default : return "Error";
    }

}


public double getAverage(){
    return (getTotal() / SIZE);
}

public String getMost(){
    int mostRain = 0;
    for (int i = 1; i < SIZE; i++)
    {
       if (rainArray[i] > rainArray[mostRain])
           mostRain = i;
    }
    return getMonth( mostRain );

}

public double getMostValue(){
    int mostRain = 0;
    for ( int i = 1; i  < SIZE; i++) {
        if (rainArray[i] < rainArray[mostRain])
        mostRain = i; 
    }
    return rainArray[mostRain];

}

public String getLeast(){
    int leastRain = 0;
    for ( int i = 1; i < SIZE; i++ ) {
        if ( rainArray[i] < rainArray[leastRain])
            leastRain = i;
    }

    return getMonth( leastRain );

}

public double getLeastValue(){
    int leastRain = 0;
    for ( int i = 1; i < SIZE; i++) {
        if (rainArray[i] < rainArray[leastRain])
         leastRain =  i;
    }

    return rainArray[leastRain];
}
        }

这个程序有两个部分,但我确信这部分是问题所在。

2 个答案:

答案 0 :(得分:3)

public double getMostValue(){
    int mostRain = 0;
    for ( int i = 1; i  < SIZE; i++) {
        if (rainArray[i] < rainArray[mostRain])
        mostRain = i; 
    }
    return rainArray[mostRain];
}

这将找到最小值。您需要将<替换为>

答案 1 :(得分:0)

我不明白,这个方法找到了最小但最有名的..

public double getMostValue(){
    int mostRain = 0;
    for ( int i = 1; i  < SIZE; i++) {
        if (rainArray[i] < rainArray[mostRain])
        mostRain = i; 
    }
    return rainArray[mostRain];

}