简体   繁体   English

java数组分配-使用数字文字

[英]java array assignment - use of numeric literal

Create an application containing an array that stores 20 double values, 
such as 2.34, 7.89, 1.34, and so on. The application should:
     *      Display the sum of all the array elements
     *      Display the average of all the array elements
     *      Display the largest value of all the array elements

This is a java class assignment. 这是一个Java类分配。 I got a bad grade on this one because my professor said I used a numeric literal. 我对这门课程的评分很差,因为我的教授说我使用了数字文字。 I lost 28 points out of 40. Did I design the solution so bad? 我在40分中失去了28分。我设计的解决方案太差了吗? His exact comments: 他的确切评论:

 "The program you submitted uses numeric literals in place of the array’s length. 
 This cause several runtime errors when I change the size of your array and tested the code."

AND my solution: 和我的解决方案:

import java.util.Random; 
import java.util.Arrays;

public class MyArray{ 
  public static double[] doubles;

    public static void main(String args[]) {
       MyArray.createDoublesArray();
       MyArray.displayDoublesArray();
       MyArray.displaySum();
       MyArray.displayAverage();
       MyArray.displayTheLargestValue();
    } 

    /*Fill up the double Array class member*/
    public static void createDoublesArray(){
        doubles = new double[20];
        //Create Random object 
        Random r=new Random(); 
        double rangeMin = 1, rangeMax = 9; 
        //Generate random double number - 20 times within the range of 2 to 9
        for(int i=0;i<20;i++) { 
            //Generate random double numbers and round them to the two decimal places
            double randomdouble = Math.round((rangeMin + (rangeMax - rangeMin) * r.nextDouble())*100.0)/100.0; 
            doubles[i] = randomdouble;            
        }         
    }    

    /*Display the double Array*/
    public static void displayDoublesArray(){
        String delimiter;
        Arrays.sort(doubles);
        System.out.println("The double array: ");
        // iterate through all the array elements
        System.out.print("{");
        for(int i=0;i<20;i++) { 
           if(i < 19){
               delimiter = ", ";
           }
           else{
               delimiter = "}";
           }
           System.out.print(doubles[i]+ delimiter);      
        } 
        System.out.println("\n");
    }

    /*Displays the sum of the double array.*/
    public static void displaySum() {
        //initialize the sum with 0
        double sum = 0.0;

        // iterate through all the array elements
        for (int i = 0; i < doubles.length; i++) {
            // add up each element to the sum variable
            sum += doubles[i];
        }

        // display the sum
        System.out.println("The sum is: " + Math.round(sum*100.0)/100.0 + "\n");
    }

    /*Displays the average of the double array.*/
    public static void displayAverage() {
        // initialize the sum with 0
        double sum = 0.0;

        // iterate through all the array elements
        for (int i = 0; i < doubles.length; i++) {
            sum += doubles[i];
        }
        // display the average by dividing the sum to the length of the array
        System.out.println("The average is: " + Math.round((sum / doubles.length)*100.0)/100.0 + "\n");
    }

    /*Displays the largest value from the double array */
    public static void displayTheLargestValue() {
        //initialize the largest value with the first element
        double largestValue = doubles[0];

        //iterate through the remaining elements (ignore the first)
        for (int i = 1; i < doubles.length; i++) {
            // check if "i" element is greater then the current largest value
            if (doubles[i] > largestValue) {
                largestValue = doubles[i];
            }
        }
        // display the largest value
        System.out.println("The largest value is: " + largestValue);
    }
}  

I'm guessing that instead of things like the following 我猜想不是这样的事情

  for(int i=0;i<20;i++)

he wanted you to use the length property 他希望您使用length属性

  for(int i=0;i<doubles.length;i++)

additionally, here 另外,这里

    //initialize the largest value with the first element
    double largestValue = doubles[0];

you're assuming that doubles is not empty, and when it is empty, that will thrown an exception 您假设doubles不为空,当doubles为空时,将引发异常

To allow us to maintain this code easily I would 1st of all create: 为了让我们轻松维护此代码,我将首先创建:

private final static int SIZE = 20;

createDoublesArray : createDoublesArray

 public static void createDoublesArray(){
    doubles = new double[SIZE];
    //Create Random object 
    Random r=new Random(); 
    double rangeMin = 1, rangeMax = 9; 
    //Generate random double number - 20 times within the range of 2 to 9

    double randomdouble = 0.0;  // <- we don't want to initiate double in 'for' loop

    for(int i=0;i<SIZE;i++) { 
        //Generate random double numbers and round them to the two decimal places
        randomdouble = Math.round((rangeMin + (rangeMax - rangeMin) * r.nextDouble())*100.0)/100.0; 
        doubles[i] = randomdouble;            
    }         
}      

displayDoublesArray: displayDoublesArray:

    /*Display the double Array*/
       public static void displayDoublesArray(){
        String delimiter;
        Arrays.sort(doubles);
        System.out.println("The double array: ");
        // iterate through all the array elements

        StringBuilder buff = new StringBuilder(); // use buffer 

        buff.append("{");
        for(int i=0;i<SIZE;i++) { 
           if(i < SIZE-1){
               delimiter = ", ";
           }
           else{
               delimiter = "}";
           }
           buff.append(doubles[i]+ delimiter);                  
        } 

        buff.append("\n");

        System.out.println(buff.toString());
    }

Our code seems a bit more generic and i can change SIZE (if needed) without actually change my code. 我们的代码似乎更通用,我可以更改SIZE (如果需要),而无需实际更改我的代码。

I agree with Maxim Shoustin... 我同意Maxim Shoustin ...

Just one comment to add 只需添加一条评论

1) It is not required to always use double. 1)不必总是使用double。 for eg. 例如

double rangeMin = 1, rangeMax = 9; //can be replaced by int. 

ref: Primitive Data Types ref:基本数据类型

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

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