Write code to search a float array named values for the value in the variable na
ID: 3883494 • Letter: W
Question
Write code to search a float array named values for the value in the variable named findMe. The array has num number of elements in the list. Inside the loop, print out the element at each index separated with a semicolon, and stop searching the array once you find the value in the variable findMe. Note: if the value in findMe is not in the list, then you will print out each element in the array.
For example, if the array has {1, 2, 3} and findMe is 2, you would print:
1;2
values = {3}, findMe = 3 (1 in list, findMe found) 3
values = {9, 2, 8, 1, 4}, findMe = 1 (many in list, findMe in list) 9;2;8;1
values = {7, 3, 1, 8, 2}, findMe = 7 (many in list, findMe is first in list) 7
Explanation / Answer
ArrraySearch.java
public class ArrraySearch {
public static void main(String[] args) {
float values1 [] = {3};
float values2 [] = {9, 2, 8, 1, 4};
float values3 [] = {7, 3, 1, 8, 2};
float findMe1 = 3;
float findMe2 = 1;
float findMe3 = 7;
searchAndDisplay(values1, findMe1);
searchAndDisplay(values2, findMe2);
searchAndDisplay(values3, findMe3);
}
public static void searchAndDisplay(float f[], float findMe) {
String s = "";
for(int i=0;i<f.length; i++) {
s = s + f[i]+";";
if(f[i] == findMe) {
break;
}
}
System.out.println(s.substring(0,s.length()-1));
}
}
Output:
3.0
9.0;2.0;8.0;1.0
7.0
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.