Saturday, 6 August 2011

Linear Search in an array in java

Linear Search in Java

In this section, we are going to find an element from an array using Linear Searching. Linear searching is a good way to find an element from the array. The array can be of any order, it checks whether a certain element (number , string , etc. ) is in a specified array or not. Basically it is used for small arrays. In the given code, we have allowed the user to enter the numbers to be stored into the arrays. If the element is found we can return the index where the element is located in the array. If the element is not found we can return -1.
Here is the code:

import java.util.Scanner;

public class LinearSearch
{
public int find(final int[] data, final int key)
{
for (int i = 0; i < data.length; ++i) {
if (data[i] > key)
return -1;
else if (data[i] == key)
return i;
}
return -1;
}

public static void main(String[] args)
{
int arr[] = new int[10];
System.out.println("Enter 10 numbers");
Scanner input = new Scanner(System.in);
for (int i = 0; i < arr.length; i++) {
arr[i] = input.nextInt();
}
LinearSearch search = new LinearSearch();
System.out.print("Enter the element to search: ");
int num=input.nextInt();
int n = search.find(arr, num);
if (n!=-1 )
{
System.out.println("Found at index: " + n);
} else
{
System.out.println("Not Found");
}
}

}

Output:

Enter 10 numbers:
1
2
3
4
5
6
7
8
9
10
Enter the element to search:5
Found at index: 4

Friday, 22 July 2011

How to find the documentation of any java library class or interface

Suppose we want to check this class
java.util.Array
There are two ways
1.If you have an Internet connection then just google
oracle java.util.Array
This gives you the latest documentation
2.If you do not have Internet due to any reason then go to the java folder
open JDK
there will be a compressed folder with name src
open it and then open java folder
then open util
then you can find Array named java source file just open it in a IDE and generate documentation

Monday, 18 July 2011

Providing command line arguments

Here is the code of the file
public class Hello
{
public static void main(String args[])
{
if(args.length==1)
System.out.println("Hello "+args[0]);
}
}
we save it in Hello.java and compile it by javac Hello.java
Then we run it like this
java Hello Codex
and it prints out
Hello Codex
but if we want to provide multiple words as our name then we do like this
java Hello "Codex Java"
and it prints out
Hello Codex Java

Sunday, 17 July 2011

Setting tool tip Text for any JComponent

Tool Tip Text
Creating a tool tip for any JComponent object is easy. Use the setToolTipText method to set up a tool tip for the component. For example, to add tool tips to a button, you add only one line of code:
b1.setToolTipText("Button 1")