【问题标题】:Printing the Index of an Array Element: Java [duplicate]打印数组元素的索引:Java [重复]
【发布时间】:2012-05-13 15:58:07
【问题描述】:

我正在编写一个获取每个月降雨量的 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.");
    }
  }

【问题讨论】:

  • “非静态”错误可能是由于您将月份数组声明为应用程序类的字段并从main 方法中引用它。将static 放在您的数组前面以消除该错误。
  • 如果能提供源代码就好了。看来您走在正确的道路上,但正如@Ray 所提到的,您必须使用静态。
  • @RayToal - 我尝试过使用静态,但似乎仍然无法正常工作。你能从我发布的代码中看到我做错了什么吗?谢谢。
  • 当然可以。 months 有一个问题必须取自 r,所以我继续发布了一个带有工作代码的答案,并提出了一些其他建议。我意识到它已经晚了,所以如果他们是正确的,请随时接受早期的答案。

标签: java arrays


【解决方案1】:

不能从静态上下文中引用非静态变量月份

当您从静态成员或块访问非静态成员时,会出现此编译时错误 喜欢-

类测试{ 私人int i = 0; 公共静态无效主要(字符串[]参数){ 我=1; //这将填充该错误。 } } 我认为我们可以从不同的角度看待这个问题

class RainFall{
     private double minFall;
     private double maxFall;
    public void setMinFall(double minFall) {
        this.minFall = minFall;
    }
    public double getMinFall() {
        return minFall;
    }
    public void setMaxFall(double maxFall) {
        this.maxFall = maxFall;
    }
    public double getMaxFall() {
        return maxFall;
    }

}
public class RainFallMeasure{
        public static void main(String[] args) {
     Map<Integer,RainFall> rainFalls=new HashMap<Integer,RainFall>();
     RainFall janRainFall = new RainFall();
     janRainFall.setMinFall(1);
     janRainFall.setMaxFall(1.6);
     rainFalls.put(Calendar.JANUARY, janRainFall);
     RainFall febRainFall = new RainFall();
     ...
     rainFalls.put(Calendar.FEBRUARY, febRainFall);
    }
}

【讨论】:

    【解决方案2】:

    你可以用这个方法找到索引

    public class TEST {
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            double temp[] = {1, 5, 3};
            System.out.print(getIndex(temp,3));
        }
          //takes 2 parameters one is array and other is the value for which you want find index
        public static int getIndex(double[] temp, int value)
        {
            int i ;
            for( i= 0; i< temp.length; i++)
            {
                if(temp[i] == value)
                {
                    return i;           
                }
            }
            return -1;
        }
    }
    

    您可以在传递参数时使用月份来代替 temp。

    【讨论】:

      【解决方案3】:

      另一种方法是重新设计您的应用程序,以便这些方法计算降雨量最高和最低的月份的索引,而不是自己计算降雨量。这个想法是,一旦有了索引,您就可以随时根据需要查找实际值。

      我已经为您修补了代码,以便它可以做到这一点,并冒昧地更正了几个“静态”错误。

      您可以使用此工作应用程序并根据需要对其进行调整:

      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 enterMonthData() {
              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;
          }
      
          /**
           * Returns the index of the month with the highest rainfall.
           */
          public int getHighestMonth() {
              int highest = 0;
              for (int i = 0; i < 12; i++) {
                  if (months[i] > months[highest]) {
                      highest = i;
                  }
              }
              return highest;
          }
      
          /**
           * Returns the index of the month with the lowest rainfall.
           */
          public int getLowestMonth() {
              int lowest = 0;
              for (int i = 0; i < 12; i++) {
                  if (months[i] < months[lowest]) {
                      lowest = i;
                  }
              }
              return lowest;
          }
      
          public static void main(String[]args) {
              Rainfall r = new Rainfall();
              r.enterMonthData();
              System.out.println("The total rainfall for this year is " + r.getTotalRainFall());
              System.out.println("The average rainfall for this year is " + r.getAverageRainFall());
              int lowest = r.getLowestMonth();
              int highest = r.getHighestMonth();
              System.out.println("The month with the highest amount of rain is " + (highest+1) + " with " + r.months[highest] + " inches");
              System.out.println("The month with the lowest amount of rain is  " + (lowest+1) + " with " + r.months[lowest] + " inches");
          }
      }
      

      附录

      要回答您的后续问题,您需要为您的 Rainfall 对象提供一个构造函数,该构造函数接收降雨数据并将此数据存储在对象的字段中。这就是你想要的:

      public class Rainfall {
      
          private double[] amounts;
      
          public Rainfall(double[] amounts) {
              this.amounts = amounts;
          }
      
          double getTotalRain() {
              double total = 0.0;
              for (int i = 0; i < amounts.length; i++) {
                  total += amounts[i];
              }
              return total;
          }
      
          double getAverageRain() {
              return getTotalRain() / amounts.length;
          }
      
          int getHighestMonth() {
              int high = 0;
              for (int i = 0; i < amounts.length; i++) {
                  if (amounts[i] > amounts[high]) {
                      high = i;
                  }
              }
              return high;
          }
      
          int getLowestMonth() {
              int low = 0;
              for (int i = 0; i < 12; i++) {
                  if (amounts[i] < amounts[low]) {
                      low = i;
                  }
              }
              return low;
          }
      
          /**
           * Returns the total rain the given month number.  Month numbers
           * start at 0, not 1.
           */
          double getRainForMonth(int monthNumber) {
              return amounts[monthNumber];
          }
      
          public static void main(String[] args) {
      
              // Sample data for testing
              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, starting at 0
              int low;     // The low month, stating at 0
      
              // Create a RainFall object initialized with amounts from above 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.getRainForMonth(high) + " inches.");
              low = r.getLowestMonth();
              System.out.println("The month with the lowest amount of rain is " + (low + 1)
                      + " with " + r.getRainForMonth(low) + " inches.");
          }
      }
      

      【讨论】:

      • 上帝,这更有意义。非常感谢!!
      • 我现在正在尝试删除所有用户输入并指定数组中的值。你能看出我做错了什么吗?
      猜你喜欢
      • 2013-06-21
      • 1970-01-01
      • 2021-05-03
      • 2012-06-09
      • 2013-09-12
      • 1970-01-01
      • 1970-01-01
      • 2017-04-08
      • 2013-10-27
      相关资源
      最近更新 更多