Free CoreJava Programs Source codes | Examples | Video Tutorials Download

Wednesday, January 21, 2009

Print All Occurrences And Total Number Of Occurrences

import java.io.BufferedReader;

import java.io.InputStreamReader;

/**

* A variation of the above,

* with multiple occurrences of the item in the array,

* Print all occurrences and total number of occurrences.

*/

public class SearcharrayMultipleOccur

{

/**

* gets the integer input from from user

* and search and count position of that integer in source array

* and display it.

* @throws Exception

*/

public static void getIntgerNsearchpos() throws Exception

{

// source array

final int[] intSourceArray={0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,0,1,2,3,4};

// get the search integer from user..

BufferedReader brConsole=new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter any integer to search : ");

int intSearchNo=Integer.parseInt(brConsole.readLine());

// counter for search no

int intSrCounter=0;

/// find position of no in array

for(int i=0;i<intSourceArray.length;i++)

{

if(intSourceArray[i]==intSearchNo)

{

System.out.println("Position of " + intSearchNo + " in source array is " + i);

intSrCounter++;

}

}

if(intSrCounter==0)

{

System.out.println(intSearchNo + " not exists in source array");

}

else

System.out.println("Total No of Occurence of " + intSearchNo +" in source array is " + intSrCounter);

}

/**

* excecution begin from here

* @param args

*/

public static void main(String[] args)

{

try

{

getIntgerNsearchpos();

}

catch(Exception e)

{

System.out.println("Error occured!!");

}

}

}

No comments:

Post a Comment

Followers