The java program given below is capable to perform linear search for characters. When you will run the program then you will be asked to provide the limit, that means how many characters do you want to provide. After providing the limit, you will be asked to provide the characters one by one.
And then you will be asked to provide a single character that you want to search. After providing the second for-loop of the program will check if there is the expected character. If found then a message will be displayed saying, "The character found at position: n" and if not found, then another message will be displayed saying, "The character x has not found!!!"
And then you will be asked to provide a single character that you want to search. After providing the second for-loop of the program will check if there is the expected character. If found then a message will be displayed saying, "The character found at position: n" and if not found, then another message will be displayed saying, "The character x has not found!!!"
import java.util.*;
public class charSearch{
public static void main(String args[]){
//DECLARING AN INTEGER TYPE VARIABLE
int flag=0;
//CREATING SCANNER OBJECT
Scanner input = new Scanner(System.in);
//MESSAGE TO INPUT THE LIMIT
System.out.print("Enter the limit: ");
//GETTING INPUT
int limit = input.nextInt();
//DECLARING AN STRING TYPE ARRAY
char chars[] = new char[limit];
//MESSAGE TO INPUT CHARACTERS
System.out.print("Input the characters now: ");
//STORING THE CHARACTERS INTO AN ARRAY
for(int i=0; i<limit; i++){
chars[i] = input.next().charAt(0);
}
//MESSAGE TO INPUT A CHARACTER TO SEARCH
System.out.print("Enter the character you want to search: ");
//STORING THE CHARACTER INTO VARIABLE
char searchChar = input.next().charAt(0);
//CHECKING THE EXPECTING CHARACTER INTO THE ARRAY
for(int j=0; j<limit; j++){
if(chars[j]==searchChar){
//SETTING THE POSITION FOR THE CHARACTER
int k = j+1;
//DISPLAYING MESSAGE IF THE EXPECTED CHARACTER FOUND
System.out.println("The character found at position: "+k);
//SETTING FLAG=1 IF THE CHARACTER FOUND
flag = 1;
}
}
//DISPLAYING MESSAGE IF THE EXPECTED CHARACTER DOESN'T EXIST
if(flag==0){
System.out.println("The character "+searchChar+" has not found!!!");
}
}
}
No comments:
Post a Comment