Question #174282

Use the code below to answer the questions that follow:


public class CS204{

public static int linearSearch(int[] data, int target) {

for (int i = 0; i < data; i++) {

if (target == data[i]){

return I;


}

}

return -1;



public void main(String[] args) {

int[] data = {3, 14, 7, 22, 45, 12, 19, 42, 6};

System.out.println("Search for 7: " + linearSearch(7));

}


QUESTIONS


i. Why is method linearSearch declared static?


ii. Identify and resolve the errors in the code.

Expert's answer

C.

  1. The developer decided to make the method a class method, for this he used the static modifier.
  2. the loop condition does not have access to the length of the array(data.length), there is no static modifier in the main method(public static void main(String[] args) ), missing 1 parameter when calling the search method(linearSearch(data, 7))
public class CS204 {
    public static int linearSearch(int[] data, int target) {
        for (int i = 0; i < data.length; i++) {
            if (target == data[i]) {
                return i;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] data = {3, 14, 7, 22, 45, 12, 19, 42, 6};
        System.out.println("Search for 7: " + linearSearch(data, 7));
    }
}
LATEST TUTORIALS
APPROVED BY CLIENTS