ISE-ComProg-After-Midterm/Week8/JavaFiles/Replace.java

56 lines
2.4 KiB
Java
Raw Normal View History

2020-10-20 15:21:15 +00:00
//This code is written by Siwat Sirichai
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(); //Create a newline to make the format looks uniform
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++) { //loop from 0 to the length of array a, number of completed iteration is stored in i (type int)
System.out.print(a[i]); //print out the value of array a at index i
if(i<a.length-1)System.out.print(","); //print out a comma if the printed digit before it is not the last digit (last digit does not need a comma)
}
System.out.println(); //Create a newline to make the format looks uniform
}
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);
}
}