Let’s learn linear search string array java.
Linear search string array java
Here let’s learn linear search of string array.
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class LinearSearchString { public void stringLinearSearch(String[] str, String strSearch) { int a; int flag = 0; for(a = 0; a < 5; a++) { if(strSearch.equals(str[a])) { flag = 1; break; } } if(flag == 1) { System.out.println("Word found at position: " + (a + 1)); } else { System.out.println("Word not found"); } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); LinearSearchString obj = new LinearSearchString(); System.out.println("Please enter any 5 words: "); String[] strInput = new String[5]; for(int a = 0; a < 5; a++) { strInput[a] = br.readLine(); } System.out.println("Please enter word to be searched - "); String search = br.readLine(); obj.stringLinearSearch(strInput, search); } }
Output:
Please enter any 5 words:
ajinkya
virat
dhoni
zaheer
bhuvi
Please enter word to be searched – dhoni
Word found at position: 3
Please enter any 5 words:
ajinkya
virat
dhoni
zaheer
bhuvi
Please enter word to be searched – rahul
Word not found
Also read – do while loop in java