Hey!
I got this class with some static methods in it from an assignment that i am doing atm.
One method should act as the following : Method void replaceAll(int[] arr, int old, int nw), replacing all occurrences of old with nw in arr.
However i feel lost.. does anyone know what they mean? And if so then how should i approach this?
Here is the code:
import java.util.Scanner; //Forbidden to use array classes. public class engV { static final int[] arr = { 3, 4, 5, 6, 7 }; // Made this a static and a final so that it won't change and so that everything // can access it! public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println(sum(arr)); // For sum method. It takes all the values of arr and adds them together. System.out.println(); System.out.println(); System.out.println(tostring(arr)); // Prints out the numbers from the array. System.out.println(); System.out.println(); // Adds numbers to each element. System.out.println("Write a number that you would like to add to each element in the array :"); int input = in.nextInt(); System.out.print("The new numbers are : "); addN(arr, input); // Takes return from addN method. System.out.println(); System.out.println(); System.out.println(); System.out.print("Reverse order of array : "); reverse(arr); // Writes the reverse order of the array. System.out.println("\n"); hasN(arr, 4); // Tests to see if the number within the parentheses, in this case it checks if // 4 is within the array. in.close(); } public static int sum(int[] arr) { int n = 0; for (int i : arr) { n += i; } return n; } public static String tostring(int[] arr) { String strk = " "; int i = 0; String st = null; for (i = 0; i < arr.length; i++) { st = Integer.toString(arr[i]); System.out.print(st + strk); if (i >= arr.length) { break; } } return strk; } public static int[] addN(int[] arr, int n) { String strK = " "; int results[] = null; int k = 0; for (k = 0; k < arr.length; k++) { System.out.print(arr[k] + n + strK); } return results; } public static int[] reverse(int[] arr) { int counter = 0; String str = " "; for (counter = arr.length - 1; counter >= 0; counter--) { System.out.print(arr[counter] + str); } return arr; } public static boolean hasN(int[] arr, int n) { boolean found = false; for (int i = 0; !found && (i < arr.length); i++) { found = (arr[i] == n); } if (found == true) { System.out.println("Yes, " + n + " does exist in the array!"); } else { System.out.println("No, " + n + " does not exist in the array!"); } return found; } public static void replaceAll(int[] arr, int old, int nw) { //Here i get lost... } }