In: Computer Science
Download the AddValueNewArray.java file, and open it in jGrasp (or a text editor of your choice). This program behaves similarly to the AddValueToArray program from before. However, instead of modifying the array in-place, it will return a new array holding the modification. The original array does not change. For simplicity, the array used is “hard-coded” in main, though the method you write should work with any array. Example output with the command-line argument 3 is shown below:
Original array: 3 8 6 4 New array: 6 11 9 7
Note that the output shows the original, unchanged array, along with the new array.
public class AddValueNewArray { // You must define the addValueNew method, which behaves // similarly to the addValueTo method in AddValueToArray.java. // However, instead of adding the given value to the given // array, it will return a _new_ array, where the new array // is the result of adding the value to each element of the // given array. To be clear, the given array NEVER CHANGES. // // TODO - define your code below this comment // // DO NOT MODIFY printArray! public static void printArray(int[] array) { for (int index = 0; index < array.length; index++) { System.out.println(array[index]); } } public static void main(String[] args) { int[] array = new int[]{3, 8, 6, 4}; int valueToAdd = Integer.parseInt(args[0]); int[] newArray = addValueNew(valueToAdd, array); System.out.println("Original array:"); printArray(array); System.out.println("New array:"); printArray(newArray); } }
public class AddValueNewArray { // You must define the addValueNew method, which behaves // similarly to the addValueTo method in AddValueToArray.java. // However, instead of adding the given value to the given // array, it will return a _new_ array, where the new array // is the result of adding the value to each element of the // given array. To be clear, the given array NEVER CHANGES. // private static int[] addValueNew(int valueToAdd, int[] array) { int result[] = new int[array.length]; for(int i = 0;i<array.length;i++){ result[i] = array[i] + valueToAdd; } return result; } // DO NOT MODIFY printArray! public static void printArray(int[] array) { for (int index = 0; index < array.length; index++) { System.out.println(array[index]); } } public static void main(String[] args) { int[] array = new int[]{3, 8, 6, 4}; int valueToAdd = Integer.parseInt(args[0]); int[] newArray = addValueNew(valueToAdd, array); System.out.println("Original array:"); printArray(array); System.out.println("New array:"); printArray(newArray); } }