Monday, May 11, 2015

Linear search program in java for float type data

The java program given below is able to search a float 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 a float type variable itemNumber.

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

Then another message will appear asking what do you want to search. After providing a float 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 floatSearch{
 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
  float numbers[] = new float[itemNumber];

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

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

  //STORING THE ITEM INTO VARIABLE
  float item = input.nextFloat();

  //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!!! :(");
  }
 }
}

No comments:

Post a Comment