import java.util.Random;
public class ArraysExercises{
Displays all of the elements of an array (of doubles) on one line
@param arr
public static void displayAll(double[] arr){
for(int i = 0; i < arr.length; ++i ){
System.out.print( arr[i] + " " );
}
System.out.println();
}
Makes a copy of the elements in array from startIndex to endIndex (but not including endIndex) (up to the end of the array)
@param a
@param ...
@param ...
@return
public static int[] sub(int[] a, int startIndex, int endIndex){
int[] s = new int[endIndex - startIndex];
for(int i = startIndex; i < a.length && i < endIndex; ++i ){
s[i - startIndex] = a[i];
}
return s;
}
Returns the average value
@param arr
@return
public static double average(double[] arr){
double total = 0.0;
for(int i = 0; i < arr.length; ++i ){
total += arr[i];
}
return total / arr.length;
}
public static void twiceValues( int[] arr ){
for(int i = 0; i < arr.length; ++i ){
arr[i] = arr[i] * 2;
}
}
Append an item to the end of an array
public static String[] append(String[] strArray, String item){
String[] res = new String[strArray.length + 1];
for( int i = 0; i < strArray.length; ++i){
res[i] = strArray[i];
}
res[strArray.length] = item;
return res;
}
public static void main( String[] args ){
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() * 3.1;
}
double total = 0;
for(int i = 0; i < 100; ++i){
total += milesRan[i];
}
System.out.println("total: " + total);
System.out.println("average: " + total / 100);
displayAll( milesRan );
System.out.println( "Average of all: " + average( milesRan ) );
int[] nums = {7, 5, 3, 1, 55, 42, 99, 97, 45};
System.out.println("Before:");
for( int i = 0; i < nums.length; ++i){
System.out.println(nums[i]);
}
twiceValues( nums );
System.out.println("After:");
for( int i = 0; i < nums.length; ++i){
System.out.println(nums[i]);
}
int[] numsSub = sub( nums, 3, 7+1 );
System.out.println("numsSub:");
for( int i = 0; i < numsSub.length; ++i){
System.out.println(numsSub[i]);
}
String[] children = new String[ 3 ];
children[0] = "Emma";
children[1] = "Noah";
children[2] = "Olivia";
children = append( children, "Liam");
for( String child : children ){
System.out.println( child );
}
}
}