-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchingElementOfArray.java
More file actions
57 lines (39 loc) · 1.43 KB
/
SearchingElementOfArray.java
File metadata and controls
57 lines (39 loc) · 1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import java.util.Scanner;
public class SearchingElementOfArray {
public static void main(String [] args){
// Searching the elements of an array
int []numbers={1,3,2,45,5};
int target=4;
boolean isFound=false;
// using linear search
for (int i = 0; i < numbers.length ; i++) {
if (target == numbers[i]) {
System.out.println("Element found at index: " + i);
isFound=true;
break;
}
}
if(!isFound){
System.out.println("Element was not found");
}
// Searching a String element of an array and allowing a user to search the fruit of their choice
Scanner scanner=new Scanner(System.in);
String target1;
boolean fruitFound=false;
String [] Fruits={"Apples", "Orange", "Banana"};
System.out.print("Enter a fruit to search: ");
target1= scanner.nextLine();
for (int i = 0; i < Fruits.length; i++){
if (target1.equalsIgnoreCase(Fruits[i])){
System.out.println("The element "+ target1 +" was found at index: "+i);
fruitFound=true;
break;
}
if (!fruitFound){
System.out.println("Fruit not found");
break;
}
}
scanner.close();
}
}