Write a public member function which replace that replaces one occurrence of a given item in the ArrayBag with another passed as an argument. The method should return a boolean to indicate whether the replacement was successful.

Respuesta :

Answer:

The method is written in Java

public static boolean abc(int [] ArrayBag,int num, int replace){

    Boolean done = false;

    for(int i =0; i<ArrayBag.length;i++){

        if(ArrayBag[i] == num){

            ArrayBag[i] = replace;

            done = true;

        }

    }

    for(int i = 0;i<ArrayBag.length;i++){

        System.out.println(ArrayBag[i]+" ");

    }

    return done;

}

Explanation:

The method is written in java

The arguments of the method are:

1. ArrayBag -> The array declares as integer

2. num -> The array element to check the presence

3. replace - > The replacement variable

This line defines the method as boolean.

public static boolean abc(int [] ArrayBag,int num, int replace){

This line declares a boolean variable as false

    Boolean done = false;

The following iterates through the elements of the array

    for(int i =0; i<ArrayBag.length;i++){

This checks if the array element exist

        if(ArrayBag[i] == num){

If yes, the array element is replaced

            ArrayBag[i] = replace;

The boolean variable is updated from false to true

            done = true;

        }

    }

The following iteration prints the elements of the array

    for(int i = 0;i<ArrayBag.length;i++){

        System.out.println(ArrayBag[i]+" ");

    }

This prints returns the boolean thats indicates if replacement was done or not.

    return done;

}

Attached to this solution is the program source file that includes the main method of the program

Ver imagen MrRoyal