/*
 * @topic T02305 Using Arrays.copyOf( ) Arrays.fill( ) Double.isNaN( )
 * @brief Arrays can be zero length -- be careful when using array's length in formulas!
*/
package arraydemo;

import java.util.Arrays;

public class Main {
    /////////////////////////////////////////////
    // Please remove, rename, or comment out
    // specific functions to compile and test
    /////////////////////////////////////////////

    // This main() yields ArithmeticException:
    public static void main(String[] args)
    {
        int[] prices = { };
        System.out.println("prices.length==" + prices.length);
        int sum = 0;
        for (int i = 0; i < prices.length; i++)
        {
            sum += prices[i];
        }
        int average = sum / prices.length;
    }//main


    // This main() yields NaN:
    public static void main(String[] args)
    {
        double[] prices = {};
        System.out.println("prices.length==" + prices.length);
        double sum = 0.0;
        for (int i = 0; i < prices.length; i++)
        {
            sum += prices[i];
        }
        double average = sum / prices.length;
        if (Double.isNaN(average))
        {
            System.out.println("average is Not a Number!");
        }
        else
        {
            System.out.println("average==" + average);
        }
    }//main


    // This main() yields a normal result.
    // Uses Arrays.copyOf() and Arrays.fill()
    public static void main(String[] args)
    {
        // Create and initialize array of doubles:
        double[] prices = { 0.0, 1.0, 3.0, 4.0, 5.0, 6.0, 7.0 };
        prices[2] = 77.95;

        double[] xyz = Arrays.copyOf(prices, prices.length);
        Arrays.fill(xyz, 55.95);
        double sum = 0.0;
        for ( int idx = 0; idx < prices.length; ++idx )
        {
            sum += prices[ idx ];
        }

        // Division of integers by zero results in ArithmeticException.
        // When floating point arithmetic is involved,
        // you may need to check for NaN result:
        double average = sum / prices.length;
        if (Double.isNaN(average))
        {
            System.out.println("average is NaN");
        }
        else
        {
            System.out.println("average==" + average);
        }
    }//main
}// class Main