Saturday, January 5, 2013

Implement a Java method that finds two neighbouring numbers in an array with the smallest distance to each other.



Implement a Java function that finds two neighbouring numbers in an array with the smallest distance to each other. The function should return the index of the first number.

In the sequence 4 8 6 1 2 9 4 the minimum distance is 1 (between 1 and 2). The function should return the index 3 (of number 1).

class LangFund3{
    static void smallestDistance(int [] array){
   
        int smallest = Math.abs(array[0]-array[1]);
        int index = 0;
        for(int i=1; i<array.length-1; i++){
            int value = Math.abs(array[i]-array[i+1]);
            if(value< smallest){
            smallest= value;
            index = i;
            }
               
        }
        System.out.println(smallest);
        System.out.println(index);   
           
    }
    public static void main(String [] args){
        int []arr= new int[]{4,8,6,1,2,9,4};
        smallestDistance(arr);
    }
}

How to find the largest and smallest number from a given Array using Java?

Find the largest and smallest number from a given array.

This java example shows how to find the largest and smallest number in an array.

        public class FindLargestSmallestNumber {
    
            public static void main(String[] args) {
                  
                    //array of 10 numbers
                    int numbers[] = new int[]{32,43,53,54,32,65,63,98,43,23};
                  
                    //assign first element of an array to largest and smallest
                    int smallest = numbers[0];
                    int largetst = numbers[0];
                  
                    for(int i=1; i< numbers.length; i++)
                    {
                            if(numbers[i] > largetst)
                                    largetst = numbers[i];
                            else if (numbers[i] < smallest)
                                    smallest = numbers[i];
                          
                    }
                  
                    System.out.println("Largest Number is : " + largetst);
                    System.out.println("Smallest Number is : " + smallest);
            }
    }

NumberFormatException and Exception hierarchy.

NumberFormatException and Exception hierarchy.
When we catch an exception with catch clause, we should catch exception from narrow to wide. Otherwise compiler will give a compilation error.
Here is a simple example to illustrate the NumberFormatException and usage of Exception hierarchy.

class NumberFormat{
    void throwExcep(){
        String s=null;
        int [] val={1,2,3,4,5};
        String ss="ABCD";
       
        try{
        int i=Integer.parseInt(ss);
        }
        catch(NumberFormatException np){
            System.out.println("NumberFormat");
       
        }
        catch(ArrayIndexOutOfBoundsException ae){
            System.out.println("ArrayIndexOutOfBounds");
        }
        catch(Exception e){
            System.out.println("Exception");
        }               
   
    }
    public static void main(String args[]){
        NumberFormat nf= new NumberFormat();
        nf.throwExcep();
    }
}

How to through and catch a NullPointerException in Java?

Simple example to show how to through and catch a NullPointerException in Java.

class NullPointer{
    public static void main(String args[]){
        String s=null;

            try{
                System.out.println(s.length());
            }
            catch(NullPointerException e){
                System.out.println("Null Pointer Exception caught by code");
            }
    }
}

How to validate a Social Security Number(SSN) using Java.

How to validate a SSN Number using Java?

SSNValidator class.

import java.util.regex.*;
class SSNValidator{
     public static void isValidSSN(String ssn) throws Exception{
 
        //Initialize reg expression for SSN.
        String expression = "^\\d{3}[- ]\\d{2}[- ]\\d{4}$";
        CharSequence inputStr = ssn;
        Pattern pattern = Pattern.compile(expression);
        Matcher matcher = pattern.matcher(inputStr);   
       
            if(matcher.matches()){
            System.out.println("Correct SNN Number");
            }
            else{
                throw new MyException(ssn);
            }           
    }
    public static void main(String args[])throws Exception{   
                String cmd="";
                try{
                     cmd=args[0];
                    }
                    catch(ArrayIndexOutOfBoundsException ae){
                    System.out.println("You shoud input your SSN number");
                    }
                isValidSSN(cmd);               
    }
}

Creating my own Exception class by extending Exception class.
class MyException extends Exception{
    private String s="";
    MyException(String val){
        this.s=val;
   
    }
      public String toString(){
        return "SSN number you were enter" + " " +s+" is not valid. "+ "please try again with correct format as given here. Ex:123-44-5678";
    }
}
  
How to run?
  1. Copy both java sources into one folder.
  2. Open cmd and navigate to that folder.
  3. Compile  main class(SSNValidator). 
  4. Then run with the SSN number. Ex(java SSNValidator 123-67-7890).
Meaning of Regex expression:
        "^\\d{3}[- ]\\d{2}[- ]\\d{4}$";
        ^\\d{3}:  Starts with three numeric digits.
        [- ]:  Followed by an "-"
        \\d{2}: Two numeric digits after the "-"
        [- ]:  contain an second "-" character.
       \\d{4}: ends with four numeric digits.
Above Regex format accepts only following format "xxx-xx-xxxx".
If you would like to change the Regex expression to accept 9 digits regardless of above format.
String expression = "^\\d{3}[- ]?\\d{2}[- ]?\\d{4}$"; 
This expression can accept the format given below.
SSN format xxx-xx-xxxx, xxxxxxxxx, xxx-xxxxxx; xxxxx-xxxx:
     
     ^\\d{3}: Starts with three numeric digits.
    [- ]?: Followed by an optional "-"
    \\d{2}: Two numeric digits after the optional "-"
    [- ]?: May contain an optional second "-" character.
    \\d{4}: ends with four numeric digits.


Sunday, October 7, 2012

In java, How to print reversely in a given String?

In java, How to print reversely in a given String?

class ReveseString{
public static void main(String args[]){
String s="String is immutable";
for(int i=s.length()-1; i>=0; i--){
System.out.print(s.charAt(i));
}
}
}

How to write a program in java to display given certain pattern?

How to write a program in java to display given certain pattern?

1
12
123
1234
12345
 
class Example5{
public static void main(String args[]){
 for(int i=1;i<6;i++){
System.out.println();
 for(int j=1; j<=i; j++){
System.out.print(j);
 }
}
}
}


Friday, October 5, 2012

How to Extend the Volume/Size of the C drive in Windows 7?

How to Extend the Volume/Size of the C drive in Windows 7?

1.Right click on my computer and select manage



2.Next Click Storage< Disk Management
You will be see something similar to this image.



3.You sould have free space near to C drive. for example if you have D drive adjacent to C drive. You should backup the data of D drive to another Drive and need to be delete the D drive.

4.Then Right click on C drive. you can see "extend voulme" option in the panel. If your "extend volume" option disable in that panel that means you don't have adjacent drive with free sapce. So you should do the step 3.

5.  After that You will be asked  for how much amount you need to allocate for the C drive. Select the Directions as what you want. Finally you have done.


Tuesday, January 3, 2012

How to Disable Back button in android


/**
* To disable back button(when click back button nothing happen)
*/
@Override
public void onBackPressed() {
  return;
}

How to Launch Activities from different application in android



For Example We have two application with same package and Different Namespace.
First Application: Com.Example.Application1
Second Application: Com.Example.Application2
In this case you can define common Manifest file for both Application1 and Application2 as given below
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="Com.Example">
And add given line to your manifest file
<activity android:name=".Application2/Activity2">
  <intent-filter>
    <action android:name="Application2.intent.action.Launch" />
    <category android:name="android.intent.category.DEFAULT" />
  </intent-filter>
</activity>
Now you can create an Intent to launch Activity2 from the Activity1 with this line of code:
Intent intent = new Intent("Application2.intent.action.Launch");
startActivity(intent);


Friday, December 9, 2011

how to use android emulator to find the gps location.

Usually from your emulator you can't get current location when you run your GPS location finder application. 
First you have to make sure  this line of code is available in your source code.
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
You can also request location updates from both the GPS and the Network Location Provider by calling requestLocationUpdates() twice—once for NETWORK_PROVIDER and once for GPS_PROVIDER. But when you run the applicatin in emulator, you should use GPS provider to obtain your location.
And now you have to move to below location by yourself. And run the ddms.bat file
C:/android sdk/tools/ddms.bat
When you run this bat file you will find an emulator controller tab there. from this tab you can pass locations to emulator by longitude and latitude of your current location.

Here you can find your location's longitude and latitude.

Difference between GPS and Android's Network Location Provider to acquire the user location

Obtaining User Location in android application using GPS or Network Location Provider

GPS
Android's Network Location Provider
Although GPS is most accurate
Android's Network Location Provider determines user location using cell tower and Wi-Fi signals
It only works outdoors
Providing location information in a way that works indoors and outdoors
It quickly consumes battery power

Uses less battery power
It doesn’t return the location as quickly as users want.
Responds faster


Note: To obtain the user location in your application, you can use both GPS and the Network Location Provider, or just one.

Thursday, December 8, 2011

How to redirect to another window in android when button click

This Sample Code explain how to show another window of given url when button click in android.

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainWindowActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Button button = (Button)findViewById(R.id.button1);    

    button.setOnClickListener(new OnClickListener() {
      public void onClick(View arg) {
        Intent viewIntent =
          new Intent("android.intent.action.VIEW",
            Uri.parse("https://google.com"));
          startActivity(viewIntent);
      }
    });
}
}