import java.util.Random;
public class ArraysExercises02{
Displays all of the elements of an array (of doubles) on one line
@param array
public static void displayArrayValues( double[] array ){
for(int i = 0; i < array.length; ++i){
System.out.println( array[ i ] );
}
System.out.println("With an enhanced for loop:");
for( double num : array ){
System.out.println( num );
}
}
Makes a copy of the elements in array from startIndex to endIndex (but not including endIndex) (up to the end of the array)
@param ...
@param ...
@param ...
@return
public static double[] subset( double[] arr, int startIndex, int endIndex){
double[] sub = new double[ endIndex - startIndex ];
int j = 0;
for( int i = startIndex; i < endIndex && i < arr.length; ++i ){
sub[j] = arr[i];
++j;
}
return sub;
}
Returns the average value
@param array
@return
public static double average( double[] array ){
double sum = 0.0;
for( int i = 0; i < array.length; ++i){
sum = sum + array[ i ];
}
return sum / array.length;
}
public static void doubleValues( int[] arr ){
for( int i = 0; i < arr.length; ++i){
arr[i] = arr[i] * 2;
}
}
public static String[] arrayExtender( String[] originalArray, String newItem ){
String[] newArray = new String[ originalArray.length + 1 ];
int i = 0;
for( i = 0; i < originalArray.length; ++i){
newArray[ i ] = originalArray[i];
}
newArray[ i ] = newItem;
return newArray;
}
public static void main( String[] args ){
System.out.println( "args:" );
for( String arg : args ){
System.out.println( arg );
}
double[] milesRan = new double[365];
milesRan[ 0 ] = 3.1;
Random rand = new Random();
for( int i = 1; i < milesRan.length; ++i){
milesRan[i] = rand.nextDouble() * 10.0;
}
double sum = 0.0;
for( int i = 0; i < 100; ++i){
sum = sum + milesRan[ i ];
}
System.out.println("The average for the first 100 days is: " + sum / 100);
System.out.println("The average for the entire year (" + milesRan.length + " days) is: " + average( milesRan ));
int[] nameOfArray = {5,4,3,2,1};
System.out.println( "Before the method call");
for( int i = 0; i < nameOfArray.length; ++i){
System.out.println( nameOfArray[i] );
}
doubleValues( nameOfArray );
System.out.println( "After the method call");
for( int i = 0; i < nameOfArray.length; ++i){
System.out.println( nameOfArray[i] );
}
double[] springBreakMiles = subset( milesRan, 73, 73 + 7);
System.out.println( "Spring Break running was: ");
displayArrayValues( springBreakMiles );
String[] children = new String[ 3 ];
children[0] = "Emma";
children[1] = "Noah";
children[2] = "Olivia";
children = arrayExtender( children, "Liam" );
for( String child : children ){
System.out.println( child );
}
}
}