简体   繁体   English

Java-解决简单数组地震程序

[英]Java - solve simple array earthquake program

I have a home work problem like this: 我有这样的家庭作业问题:

The following data represent Richter Scale data for earthquakes. 以下数据代表地震的里氏震级数据。 Write a program to calculate and print the average of any valid earthquake data. 编写程序以计算和打印任何有效地震数据的平均值。

Store the Richter values in an array of doubles named quakeLevels. 将Richter值存储在名为quakeLevels的双精度数组中。

Unfortunately, your seismograph is known to sometimes produce unreliable readings (like the value of 10.1 in this example). 不幸的是,您的地震仪有时会产生不可靠的读数(例如本例中的10.1)。 So you decide to throw out the maximum and minimum readings. 因此,您决定放弃最大和最小读数。

Your program should do the following: 您的程序应执行以下操作:

Declare and initialize the quakeLevels array using the following data. 使用以下数据声明并初始化quakeLevels数组。 { 5.6, 6.2, 4.0, 5.5, 5.7, 6.1,7.4, 8.5, 5.5, 6.3, 6.4, 2.1, 6.9, 4.3, 3.1, 7.0, 10.1 } {5.6、6.2、4.0、5.5、5.7、6.1、7.4、8.5、5.5、6.3、6.4、2.1、6.9、4.3、3.1、7.0、10.1}

Determine the maximum and minimum values in the array. 确定数组中的最大值和最小值。 Compute the average of the array contents, excluding the maximum and minimum values. 计算数组内容的平均值,不包括最大值和最小值。 Print the values in the array excluding the maximum and minimum values. 打印数组中不包括最大值和最小值的值。 Print the average. 打印平均值。

I cannot use the Math class, so that is why everything is written out to print max and min. 不能使用Math类,所以这就是为什么所有内容都被写出以打印max和min的原因。

Here is my code so far: 到目前为止,这是我的代码:

 public class ARRAYminAndmax0RichterScale
    {
        public static void main(String [] args)
        {
            double [] quakeLevels = { 5.6, 6.2, 4.0, 5.5, 5.7, 6.1 ,7.4, 8.5, 5.5, 6.3, 6.4, 2.1, 6.9, 4.3, 3.1, 7.0, 10.1};    
            double [] quakeLevelsNormalized = new double [(quakeLevels.length - 2)];
            int i;

            int minIndex = 0;  // start with 0th element as min
            for ( i = 1; i < quakeLevels.length; i++) {                 
                if (quakeLevels[i] < quakeLevels[minIndex]) {
                    minIndex = i;                        
                }                    
            }
            System.out.print("Min: " + quakeLevels[minIndex] + "    ");

            int maxIndex = 0;  // start with 0th element as max
            for ( i = 1; i < quakeLevels.length; i++) {                 
                if (quakeLevels[i] > quakeLevels[maxIndex]) {
                    maxIndex = i;                        
                }                    
            }

            System.out.println("Max: " + quakeLevels[maxIndex]);                
           System.out.println("The Richter values, excluding the extrema, are as follows: ");   

            //make a new array excluding the max and min
            for ( i = 1; i < quakeLevels.length - 2; i++ ) {

                if(quakeLevels[i]!= minIndex && quakeLevels[i]!= maxIndex){
                    quakeLevelsNormalized[i] = quakeLevels[i];
                    System.out.printf("%6s\n", quakeLevelsNormalized[i] );
                }                    
            }

          //***THIS LOOP IS HERE TO HELP ME FIGURE OUT THE PROBLEM***
            for( i =0; i < quakeLevelsNormalized.length; i++){
                System.out.println("quakeLevelsNormalized["+i+"] = " + quakeLevelsNormalized[i]);
            }

            //find average of quakeLevelsNormalized
            double arrayTotal = 0;
            double average = 0;
            for (i = 0; i < quakeLevelsNormalized.length; i++) {

                arrayTotal = arrayTotal + quakeLevelsNormalized[ i ];

            }
            average = arrayTotal / quakeLevelsNormalized.length;

            //output

            System.out.println( quakeLevelsNormalized[i-1]);
            System.out.printf("%s%.1f\n","Average Quake Level = ", average);
        }

    }

And I get the following output: 我得到以下输出:

Min: 2.1    Max: 10.1

The Richter values, excluding the extrema, are as follows: 
   6.2
   4.0
   5.5
   5.7
   6.1
   7.4
   8.5
   5.5
   6.3
   6.4
   2.1
   6.9
   4.3
   3.1
quakeLevelsNormalized[0] = 0.0
quakeLevelsNormalized[1] = 6.2
quakeLevelsNormalized[2] = 4.0
quakeLevelsNormalized[3] = 5.5
quakeLevelsNormalized[4] = 5.7
quakeLevelsNormalized[5] = 6.1
quakeLevelsNormalized[6] = 7.4
quakeLevelsNormalized[7] = 8.5
quakeLevelsNormalized[8] = 5.5
quakeLevelsNormalized[9] = 6.3
quakeLevelsNormalized[10] = 6.4
quakeLevelsNormalized[11] = 2.1
quakeLevelsNormalized[12] = 6.9
quakeLevelsNormalized[13] = 4.3
quakeLevelsNormalized[14] = 3.1
3.1
Average Quake Level = 5.2

Problem 问题

So this is obviously not what it is supposed to look like. 因此,这显然不是应该的样子。 Why does it give me the extra 3.1 on the end? 到底为什么给我额外的3.1? And it only has 14 elements, when it is supposed to have [18 minus the two extremes]? 而且它只有14个元素,应该具有[18减去两个极值]吗? I'm a beginner programmer- and I greatly appreciate any and all help!! 我是一个初学者程序员, 非常感谢您提供的所有帮助!!

I think you may have a mistake in comparisons. 我认为您在比较中可能有一个错误。

if(quakeLevels[i]!= minIndex && quakeLevels[i]!= maxIndex) if(quakeLevels [i]!= minIndex && quakeLevels [i]!= maxIndex)

In this line, you ask if the VALUE at index i is the same as the min/max index. 在此行中,您询问索引i处的VALUE是否与最小/最大索引相同。 This is not accurate to what you desire, youll want to compare i with maxIndex and minIndex directly. 这与您所需要的不准确,您需要将i与maxIndex和minIndex直接比较。

Some possible methods to help you: 一些可能的方法可以为您提供帮助:

    /**
     * Get the largest number in the array
     */
    public double getMax(double[] array) {
            double max = Double.MIN_VALUE;
            for (double n : array) {
                    if (n > max) max = n;
            }
            return max;
    }

    /**
     * Get the smallest number in the array
     */
    public double getMin(double[] array) {
            double min = Double.MAX_VALUE;
            for (double n : array) {
                    if (n < min) min = n;
            }
            return min;
    }

    /**
     * Remove the specified number from the array, return a new array with the number removed
     */
    public double[] removeFromArray(double[] array, double number) {
            int count = 0;
            for (double n : array) {
                    if (n==number) count++;
            }
            double[] result = new double[array.length - count];
            int index = 0;
            for (double n : array) {
                    if (n!=number) result[index++] = n;
            }
            return result;
    }

    /**
     * Work out the mean of all the numbers in an array
     */
    public double averageOfArray(double[] array) {
            double total = 0;
            for (double n : array) {
                    total += n;
            }
            return total / array.length;
    }

I think you don't even need the quakeLevelsNormalized array. 我认为您甚至不需要quakeLevelsNormalized数组。 Here my solution, anyway this logic could be improved: 在这里,我的解决方案无论如何都可以改进此逻辑:

public class ARRAYminAndmax0RichterScale {
    public static void main(String[] args) {
        double[] quakeLevels = { 5.6, 6.2, 4.0, 5.5, 5.7, 6.1, 7.4, 8.5, 5.5,
                6.3, 6.4, 2.1, 6.9, 4.3, 3.1, 7.0, 10.1 };
        int i;
        int minIndex = 0; // start with 0th element as min
        for (i = 1; i < quakeLevels.length; i++) {
            if (quakeLevels[i] < quakeLevels[minIndex]) {
                minIndex = i;
            }
        }
        System.out.print("Min: " + quakeLevels[minIndex] + "    ");
        int maxIndex = 0; // start with 0th element as max
        for (i = 1; i < quakeLevels.length; i++) {
            if (quakeLevels[i] > quakeLevels[maxIndex]) {
                maxIndex = i;
            }
        }
        System.out.println("Max: " + quakeLevels[maxIndex]);
        System.out.println();
        System.out.println("The Richter values, excluding the extrema, are as follows: ");
        double arrayTotal = 0;
        // make a new array excluding the max and min
        for (i = 0; i < quakeLevels.length; i++) {
            if (i != minIndex && i != maxIndex) {
                System.out.printf("%6s\n", quakeLevels[i]);
                arrayTotal += quakeLevels[i];
            }
        }
        double average = arrayTotal / (quakeLevels.length - 2);
        // output
        System.out.printf("%s%.1f\n", "Average Quake Level = ", average);
    }

}

Hope this was helpful. 希望这会有所帮助。

There are few areas you can improve your code. 您可以在几个方面改进代码。 For finding minimum and maximum you can use the collections method: 要查找最小值和最大值,可以使用collections方法:

int minIndex = quakeLevels.indexOf(Collections.min(quakeLevels));
int maxIndex = quakeLevels.indexOf(Collections.max(quakeLevels));

and your main problem is in the following line. 而您的主要问题在于以下几行。

**//make a new array excluding the max and min
            for ( i = 1; i < quakeLevels.length - 2; i++ )**

why it is quakeLevels.length - 2 , it should be quakeLevels.length . 为什么是quakeLevels.length - 2 ,它应该是quakeLevels.length and also verify i = 1; 并验证i = 1; or i = 0; i = 0; need to be used in for loops. 需要在for循环中使用。

and remove the following line 并删除以下行

System.out.println( quakeLevelsNormalized[i-1]);

I'm guessing you're not allowed to use Collection types, right? 我猜你不允许使用集合类型,对吗?

Try splitting the problem down into it's component parts and doing them one by one. 尝试将问题分解为各个组成部分,并一一进行。

1) Only use the valid data: you could do this by looping through the array and checking each element in turn to see if it's <=0 or >=10. 1)仅使用有效数据:您可以通过遍历数组并依次检查每个元素以查看其是否为<= 0或> = 10,来执行此操作。 If it's valid, stick it in another array, if it's not, ignore it. 如果有效,则将其粘贴在另一个数组中,否则将其忽略。

2) Calculate the max and min values: you've done this one! 2)计算最大值和最小值:您已经完成了这一步! Store the indexes for the next bit 存储下一位的索引

3) Calculate the average: loop through the values adding them up and printing them out as you go along, skipping the min and max you stored from above 3)计算平均值:遍历所有值并将它们相加并在打印时将其打印出来,跳过上面存储的最小值和最大值

Check each part is working before doing the next, it'll be easier for you to debug. 在进行下一个步骤之前,请检查每个部分是否正常工作,以便于调试。

if(quakeLevels[i]!= minIndex && quakeLevels[i]!= maxIndex) {
           quakeLevelsNormalized[i] = quakeLevels[i];
           System.out.printf("%6s\n", quakeLevelsNormalized[i] );
}

You should compare the index, not the values associated to the minIndex and maxIndex. 您应该比较索引,而不是与minIndex和maxIndex相关联的值。

Also, why do you do iterate on 0...length-2 , you should just iterate on 0.. length-1 and check that the index is different than minIndex and maxIndex 另外,为什么要在0...length-2进行迭代,应该只在maxIndex 0...length-2进行迭代maxIndex 0.. length-1并检查索引是否不同于minIndexmaxIndex

This : arrayTotal = arrayTotal + quakeLevelsNormalized[ i ] can be simplified as 这: arrayTotal = arrayTotal + quakeLevelsNormalized[ i ]可以简化为

arrayTotal += quakeLevelsNormalized[i] 

If you can use an ArrayList for the normalized levels datastructure, you should, you don't have to care about the index this way. 如果可以将ArrayList用于规范化级别的数据结构,则应该不必关心索引。

You will just do: 您将要做:

if ((i != minIndex) && (i != maxIndex)) {
    normalized.add(quakeLevels[i])
 }

Your problem is in the calculation of the quakeLevelsNormalized array. 您的问题在于quakeLevelsNormalized数组的计算。 Check this 检查一下

//you need another index variable for 'quakeLevelsNormalized'
int j = 0;
for (i = 0; i < quakeLevels.length; i++) {

    //check the index, not the value, you have this wrong in your code
    //if(quakeLevels[i]!= minIndex && quakeLevels[i]!= maxIndex){
    if (i != minIndex && i != maxIndex) {
        quakeLevelsNormalized[j] = quakeLevels[i];
        System.out.printf("%6s\n", quakeLevelsNormalized[j]);

        //increment the index of 'quakeLevelsNormalized' array
        j++;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM