【问题标题】:Printing the Index of an Array Element: Java2 [duplicate]打印数组元素的索引:Java2 [重复]
【发布时间】:2013-06-21 19:12:09
【问题描述】:

我正在编写一个获取每个月降雨量的 java 程序。它工作得很好,但我只需要知道如何获取一个月的索引 - 例如,有一个输出语句:降雨量最低的月份是 1 和 1.6 英寸。如何获得“1”,即最低月份的索引?我可以得到实际的最低降雨量数字,但不是指数。

我已经尝试了几个月[n-1],但是我仍然收到错误消息“无法从静态上下文中引用非静态变量月份”。

任何帮助都会很棒。谢谢。

// 编辑

这里是代码。我试图玩弄静态,但这只是给了我更多的错误?所以底部的months[n]部分是我卡住的地方。

import java.util.*;

public class Rainfall {

Scanner in=new Scanner(System.in);
 int month=12;
 double total=0;
 double average;
     double months[];

public Rainfall()
{
    months=new double[12];
}

public void setMonths()
{
     for(int n=1; n<=month; n++ )
     {
     System.out.print("Enter the rainfall (in inches) for month #"+n+": ");
     months[n-1] = in.nextDouble();

     //Input Validation - Cannot accept a negative number
        while (months[n-1] < 0)
        {
         System.out.print("Rainfall must be at least 0. Please enter a new value.");
         months[n-1] = in.nextDouble();
        }
     }
}

public double getTotalRainFall()
{
    total = 0;
    for(int i=0; i<12;i++)
    {
        total=total+months[i];
    }
    return total;
}

public double getAverageRainFall()
{
    average = total/12;
    return average;
}

public double getHighestMonth()
{
    double highest=0;
    for ( int i = 0; i < 12; i++)
    {
        if ( months[i] > highest)
        {
            highest = months[i] ;
        }
    }
    return highest;
}

public double getLowestMonth()
{
    double lowest = Double.MAX_VALUE;
    for ( int n = 0; n < month; n++)
        {
            if (months[n] < lowest )
            {
                lowest = months[n];
            }
        }
        return lowest;
}

public static void main(String[]args)
{
    Rainfall r =new Rainfall();
    r.setMonths();
    System.out.println("The total rainfall for this year is " + r.getTotalRainFall());
            System.out.println("The average rainfall for this year is " + r.getAverageRainFall());
    System.out.println("The month with the highest amount of rain is " + months[n] + "with" + r.getHighestMonth() "inches");
            System.out.println("The month with the lowest amount of rain is  " + months[n] "with" + r.getLowestMonth() "inches");

}

/// EDIT #2 - 好的,所以上面的代码在每个月获取用户输入时有效。现在我正在尝试在数组 thisYear 中设置值(即删除用户输入)。计算不再起作用。我做错了什么?

package Rainfall;

public class Rainfall {

int month = 12;
double total = 0;
double average; 
double getRainAt[];

 public Rainfall() {
    getRainAt = new double[12];
}

    double getTotalRain() {
    for (int i = 0; i < 12; i++) {
        total = total + getRainAt[i];
    }
    return total;
}

   double getAverageRain() {
    average = total / 12;
    return average;
}

int getHighestMonth() {
    int high = 0;
    for (int i = 0; i < 12; i++) {
        if (getRainAt[i] > getRainAt[high]) {
            high = i;
        }
    }
    return high;
}

int getLowestMonth() {
    int low = 0;
    for (int i = 0; i < 12; i++) {
        if (getRainAt[i] < getRainAt[low]) {
            low = i;
        }
    }
    return low;
}


public static void main(String[] args) {
   // Create an array of rainfall figures. 

  double thisYear[] = {1.6, 2.1, 1.7, 3.5, 2.6, 3.7,
                       3.9, 2.6, 2.9, 4.3, 2.4, 3.7 };

  int high;      // The high month
  int low;       // The low month

  // Create a RainFall object initialized with the figures
  // stored in the thisYear array.
  Rainfall r = new Rainfall(thisYear);
  // Display the statistics.
  System.out.println("The total rainfall for this year is " +
                     r.getTotalRain());
  System.out.println("The average rainfall for this year is " +
                     r.getAverageRain());
  high = r.getHighestMonth();
  System.out.println("The month with the highest amount of rain " +
                     "is " + (high+1) + " with " + r.getRainAt(high) +
                     " inches.");
  low = r.getLowestMonth();
  System.out.println("The month with the lowest amount of rain " +
                     "is " + (low+1) + " with " + r.getRainAt(low) +
                     " inches.");
    }
  }

【问题讨论】:

  • r.getRainAt[high] ,使用 [] 而不是 ()。
  • 一些要点:不要使用数组使用列表,在一个单独的类中重构你的main(),只使用main 方法(这将帮助你理解哪里出了问题),看看@ 987654328@/Collections.max.

标签: java


【解决方案1】:

你可以这样使用。

double getIndex(double value) {
    Arrays.asList(getRainAt).indexOf(value);
}

【讨论】:

    【解决方案2】:

    一种解决方案,使用 Map 和几个月的枚举:

    package com.stackoverflow.so17289710;
    
    import java.util.*;
    
    public class Rainfall {
    
        public static enum Month {
            JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER;
        }
    
        private final Map<Month, Double> months;
    
        public Rainfall()
        {
            this.months = new TreeMap<Month, Double>(); // treeMap for order
            for (final Month month : Month.values()) {
                this.months.put(month, 0.0);
            }
        }
    
        public void setUpMonths()
        {
            final Scanner in = new Scanner(System.in);
            try {
                for (final Map.Entry<Month, Double> entry : this.months.entrySet()) {
                    do {
                        System.out.print("Enter the rainfall (in inches) for " + entry.getKey().name() + " (>=0): ");
                        entry.setValue(in.nextDouble()); // TODO validation (handle text input, ...)
    
                        // Input Validation - Cannot accept a negative number
                    } while (Math.signum(entry.getValue()) == -1);
                }
            } finally {
                in.close();
            }
        }
    
        public double computeTotalRainFall()
        {
            double total = 0.0;
            for (final Map.Entry<Month, Double> entry : this.months.entrySet()) {
                total += entry.getValue();
            }
            return total;
        }
    
        public double computeAverageRainFall()
        {
            return this.computeTotalRainFall() / (1.0 * this.months.size());
        }
    
        public Map.Entry<Month, Double> computeHighestMonth()
        {
            Map.Entry<Month, Double> highest = null;
            for (final Map.Entry<Month, Double> entry : this.months.entrySet()) {
                if (highest == null || highest.getValue() < entry.getValue()) {
                    highest = entry;
                }
            }
            return highest;
        }
    
        public Map.Entry<Month, Double> computeLowestMonth()
        {
            Map.Entry<Month, Double> lowest = null; 
            for (final Map.Entry<Month, Double> entry : this.months.entrySet()) {
                if (lowest == null || lowest.getValue() > entry.getValue()) {
                    lowest = entry;
                }
            }
            return lowest;
        }
    }
    

    .

    package com.stackoverflow.so17289710;
    
    import com.stackoverflow.so17289710.Rainfall.Month;
    
    import java.util.Map.Entry;
    
    public class App {
        public static void main(final String[] args)
        {
            // TODO: formatting of doubles
            final Rainfall r =new Rainfall();
            r.setUpMonths();
            System.out.println("The total rainfall for this year is " + r.computeTotalRainFall());
            System.out.println("The average rainfall for this year is " + r.computeAverageRainFall());
            final Entry<Month, Double> lowestMonth = r.computeLowestMonth();
            System.out.println("The month with the highest amount of rain is " + lowestMonth.getKey() + " with " + lowestMonth.getValue() + " inches");
            final Entry<Month, Double> highestMonth = r.computeHighestMonth();
            System.out.println("The month with the lowest amount of rain is " + highestMonth.getKey() + " with " + highestMonth.getValue() + " inches");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-05-13
      • 1970-01-01
      • 2021-05-03
      • 2012-06-09
      • 2013-09-12
      • 1970-01-01
      • 2017-04-08
      • 2019-10-26
      • 2012-10-24
      相关资源
      最近更新 更多