//This code is written by Siwat Sirichai
package partB;
public class Replace {
	public static int[] replace(int[] a, int v, int v2) {
		if (a==null)return a; //If a is a null pointer, return immediately to prevent a NullPointerException
		for(int i = 0; i < a.length;i++) //loop from 0 to the length of array a, number of completed iteration is stored in i (type int)
			if(a[i]==v)a[i]=v2; //if the value of a at index i is equal to v, replace it with v2
		return a; //Return the replaced array a

	}
	
	public static void printArray(int[] a) {
		if(a==null) {
			System.out.println("null"); //Print the string null
			return; //If a is a null pointer, return immediately to prevent a NullPointerException
		}
		//NOTE: return; (a return statement without a return value) in a method with no return type will break out of the method.
		for(int i = 0;i<a.length;i++)System.out.format("%d%s",a[i],i==a.length-1?"\n":",");  //Loop from i to a.length use a ternary operator to determine if value printed is the last one, if it is, create a new line , if not, insert a comma (')
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] a = { 1, 2, 3, 1, 5, 4, 1, 2, 3, 1 };
		int[] b = { 1, 5, 5, 1, 4, 5, 4, 2, 1, 5, 5, 2};
		int[] b2 = { 1, 5, 5, 1, 4, 5, 4, 2, 1, 5, 5, 2};
		int[] c = null;
		int[] d = { 1, 2, 3, 4}; 

		System.out.print("Printing array a: ");  printArray(a);
		System.out.print("Printing array b: ");  printArray(b);
		System.out.print("Printing array b2: ");  printArray(b2);
		System.out.print("Printing array c: ");  printArray(c);
		System.out.print("Printing array d: ");  printArray(d);

		System.out.println("Now calling replace in each!");
		replace(a,1,55);
		replace(b,5,66);
		replace(b2,4,77);
		replace(c,1,5);
		replace(d,5,7);

		System.out.println("Printing result of each replace!");
		System.out.print("Printing array a, replacing 1 with 55: ");  printArray(a);
		System.out.print("Printing array b, replacing 5 with 66: ");  printArray(b);
		System.out.print("Printing array b2, replacing 4 with 77: ");  printArray(b2);
		System.out.print("Printing array c, replacing 1 with 5: ");  printArray(c);
		System.out.print("Printing array d, replacing 5 with 7: ");  printArray(d);

	}

}
