- Create a new class named ArrayTraversal.
- Add the following method named power, create a main method, and have main call the power method. Also, be certain to import the Arrays class.
import java.util.Arrays; public class ArrayTraversal { public static void power(double[] a){ for(int i = 0; i < a.length; i++){ a[i] = Math.pow(a[i], 2.0); } System.out.println(Arrays.toString(a)); } public static void main(String[] args){ double[] a = {1.0,2.2,3.4,4.44,5.22}; ArrayTraversal.power(a); } }
- Compile and run the program.
$ javac ArrayTraversal.java $ java ArrayTraversal [1.0, 4.840000000000001, 11.559999999999999, 19.713600000000003, 27.248399999999997]
- Now add a search method that takes an array of doubles and a number that the method should try to find in the array.
- Add two calls in main to search. Also, comment the call to power so it is no longer called in main.
public static void main(String[] args){ double[] a = {1.0,2.2,3.4,4.44,5.22}; //ArrayTraversal.power(a); System.out.println(ArrayTraversal.search(a,3.4)); System.out.println(ArrayTraversal.search(a,33.33)); } public static int search(double[] a, double target){ for(int i = 0; i < a.length; i++){ if(a[i]==target){ return i; } } }
- Compile and run the program.
$ javac ArrayTraversal.java $ java ArrayTraversal 2 -1
- Add a method named sum and add a call to it in main.
public static double sum(double[] a){ double total = 0.0; for(int i = 0; i < a.length;i++){ total += a[i]; } return total; }
- Add a call to sum in main.
System.out.println(ArrayTraversal.sum(a));
- Compile and run the program.
$ javac ArrayTraversal.java $ java ArrayTraversal 2 -1 16.259999999999998
The complete class should appear as follows.
import java.util.Arrays; public class ArrayTraversal { public static void power(double[] a){ for(int i = 0; i < a.length; i++){ a[i] = Math.pow(a[i], 2.0); } System.out.println(Arrays.toString(a)); } public static void main(String[] args){ double[] a = {1.0,2.2,3.4,4.44,5.22}; //ArrayTraversal.power(a); System.out.println(ArrayTraversal.search(a,3.4)); System.out.println(ArrayTraversal.search(a,33.33)); System.out.println(ArrayTraversal.sum(a)); } public static int search(double[] a, double target){ for(int i = 0; i < a.length; i++){ if(a[i]==target){ return i; } } return -1; } public static double sum(double[] a){ double total = 0.0; for(int i = 0; i < a.length;i++){ total += a[i]; } return total; } }