Doing some array experimenting, I attempted to to copy each element matching the value a user is looking for from the "arr" array to the "valuesFound" array Here's my code:
SamsArrays.java
package samsExperiments; import java.util.Arrays; import java.util.Scanner; public class SamsArrays { public int[] findAndStoreValues(int[]arr, int[]valuesFound) { System.out.println("What integer value are you looking for:"); Scanner input = new Scanner(System.in); int value = input.nextInt(); int j = 0; for(int i = 0; i < arr.length; i++) { if(i == value) { System.out.println("Found a " + value + ". Copying it to the valuesFound array."); arr[i] = valuesFound[j]; j++; } } if(valuesFound == null) { System.out.println("No " + value + " values were found to copy. valuesFound array is empty."); } return valuesFound; } }
SamsExperimentsMain.java
package samsExperiments; import java.util.Scanner; import java.util.Arrays; import SortingAlgorithms.*; import customExceptions.BuiltInExceptions; public class SamsExperimentsMain { public static void main(String[] args){ SamsArrays x = new SamsArrays(); int[] arr = {17,41,3,5,22,54,6,29,3,13}; System.out.println("We start out with: " + Arrays.toString(arr)); int[] valuesFound = new int[10]; valuesFound = x.findAndStoreValues(arr, valuesFound); System.out.println("Our valuesFound array now has: " + Arrays.toString(valuesFound)); }//end of main method }//end of class
The output looks like this:
We start out with: [17, 41, 3, 5, 22, 54, 6, 29, 3, 13]
What integer value are you looking for:
3
Found a 3. Copying it to the valuesFound array.
Our valuesFound array now has: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
As you can see, the arr array we started out with has two 3's in it, but it doesn't even seem to go through the whole arr array, because we should be seeing, "Found a 3. Copying it to the valuesFound array" printed out twice, not once. What's more, the valuesFound array should have become "[3, 3, 0, 0, 0, 0, 0, 0, 0, 0]". What happened?