Sunday, May 10, 2015

Linear search program in java for integer type data


The java program given below is able to search an integer type number from an array. When you will run the program, then first of all you will be asked to provide a number that will be stored into an integer type variable itemNumber. This number will be considered as number of elements that you want to store into an array.

After providing the number/limit, another message will be displayed asking the numbers/elements you want to store. And the numbers will be stored one by one into an integer type array numbers[].

Then another message will appear asking what do you want to search. After providing an integer type number, it will be compared with each number stored into the array. If match, a message will be displayed saying "Item has found at position: 2", otherwise a message will be displayed saying "Item has not found".

Most importantly, if the item found in three location then the message "Item has found... " will be displayed three times.

import java.util.*;
public class linearSearch{
 public static void main(String args[]){
  //DECLARING VARIABLES
  int j, flag=0;
  
  //CREATING SCANNER OBJECT
  Scanner input = new Scanner(System.in);

  //ASKING TO PROVIDE THE NUMBER OF ITEM
  System.out.print("Enter the number of Item: ");

  //GETTING INPUT FROM KEYWORD
  int itemNumber = input.nextInt();

  //ASKING TO PROVIDE THE ITEMS
  System.out.print("Enter the items one by one: ");

  //DECLARING AN ARRAY
  int numbers[] = new int[itemNumber];

  //STORING THE ITEMS INTO AN ARRAY
  for(int i=0; i<itemNumber; i++){
   numbers[i] = input.nextInt();
  }

  //ASKING TO PROVIDE THE DESIRED ITEM
  System.out.print("Enter the item you want to search: ");

  //STORING THE ITEM INTO VARIABLE
  int item = input.nextInt();

  //SEARCHING AN ITEM
  for(j=0; j<itemNumber; j++){
   if(numbers[j] == item){
    int k=j+1;
    System.out.println("The item has found at position: "+k);
    flag=1;
   }
  }

  if(flag == 0){
   System.out.println("Item has not found!!! :(");
  }
 }
}

Advertisement

No comments:

Post a Comment