Answer to Question #174282 in Java | JSP | JSF for Jean Claude

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.

1
Expert's answer
2021-03-28T18:48:50-0400

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));
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog