Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

USING JAVA Write a program that performs search of the element in the array. The

ID: 3735399 • Letter: U

Question

USING JAVA

Write a program that performs search of the element in the array. The method accepts two

parameters: an array of integers and an integer. It returns the indexes of all occurrences of of the integer in the array if it is found. Otherwise, it returns -1. Print out the index in the main method.

Create another method, similar to the previous one, that works with arrays of strings (and looks for a string).

Create 2 lists of integers and strings in your main method, fill them with arbitrary values and test your methods.

Explanation / Answer

SearchArrayValue.java

public class SearchArrayValue {

public static void main(String[] args) {

int a[] = {1,2,3,4,5,6,7,8,7,6,5,1};

String s[] = {"aaaaa", "bbbbb", "ccccc", "aaaaa", "ggggg", "yyyy", "bbbbb", "ffff", "ddddd", "aaaaa", "ccccc"};

System.out.println(searchArray(a, 7));

System.out.println(searchArray(s, "aaaaa"));

}

public static String searchArray(int a[], int key) {

String s = "";

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

if(a[i]==key) {

s=s+i+", ";

}

}

if(s.equals("")) {

return "-1";

}

return s.substring(0,s.length()-2);

}

public static String searchArray(String a[], String key) {

String s = "";

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

if(a[i].equalsIgnoreCase(key)) {

s=s+i+", ";

}

}

if(s.equals("")) {

return "-1";

}

return s.substring(0,s.length()-2);

}

}

Output:

6, 8
0, 3, 9