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.