Wednesday, 20 July 2011

Some Important Examples

1.     Program to reverse a given number using while loop
COMMAND LINE ARGUMENT: */
/* num - INPUT NUMBER TO BE REVERSED */
/* ---------------------------------------------------------------- */

public class Reverse
{
public static void main(String [] args)
{
int num = Integer.parseInt(args[0]);
int num1,t;
long rev = 0;
num1 = num;
while(num1 != 0)
{
t = num1 % 10;
rev = rev * 10 + t;
num1 /= 10;
}
System.out.print("The Reverse Of " + num + " Is " + rev);
}
}


******************************************************************************************************************************************************

2.     Program to raise a number to the given power
COMMAND LINE ARGUMENTS : */
/* n1 - BASE NUMBER */
/* n2 - POWER NUMBER */
/* ---------------------------------------------------------------- */

public class Power
{
static double p = 1.0;
public static void main(String [] args)
{
double n1 = Double.parseDouble(args[0]);
double n2 = Double.parseDouble(args[1]);
double lpower = Math.pow(n1,n2);
double upower = power(n1,n2);
System.out.println("\nUsing Math Class\'s pow Method : ");
System.out.println(n1 + " ^ " + n2 + " = " + lpower);
System.out.println("\nUsing User-Defined Method : ");
System.out.println(n1 + " ^ " + n2 + " = " + upower);
}
private static double power(double n1, double n2)
{
if(n2 >= 0)
while(n2-- > 0)
p *= n1;
else
while(n2++ < 0)
p /= n1;
return p;
}
}

******************************************************************************************************************************************************


3.     Public Class OddEven
{
public static void main(String args[]) throws IOException
{
DataInputStream din = new DataInputStream(System.in);
int ar[] = new int[10];
int n,i;
System.out.print("Enter The Array Length : ");
n = Integer.parseInt(din.readLine());
System.out.println("\nEnter " + n + " Elements for the array : ");
for(i = 0;i < n;i++)
ar[i] = Integer.parseInt(din.readLine());
int o = 0,e = 0;
for(i = 0;i <n;i++)
{
if (ar[i] % 2 == 0)
e++;
else
o++;
}
System.out.println("The Number Of Odd Elements Are : " + o);
System.out.println(" The Number Of Even Elements Are : " + e);
}
}

******************************************************************************************************************************************************


4.     Program to find whether the given number is prime or not
COMMAND LINE ARGUMENT : */
/* n - INPUT NUMBER */
/* ---------------------------------------------------------------- */

public class Prime
{
public static void main(String [] args)
{
int n = Integer.parseInt(args[0]);
if(n <= 1)
System.out.println("Enter A +ve Number > 1");
else
{
int d,fin,divided;
if((n == 2) || (n == 3))
System.out.println("\n" + n + " Is Prime");
else
if(n % 2 == 0)
System.out.println("\n" + n + " Is Not Prime");
else
{
fin = (int)(Math.sqrt(n));
d = 3;
divided = 0; // Not Yet Divided
do
{
if(n % d == 0)
divided = 1;
else
d += 2;
}while((divided != 1) && (d <= fin));
if(divided == 1)
System.out.println("\n" + n + " Is Not Prime");
else
System.out.println("\n" + n + " Is Prime");
}
}
}
}


******************************************************************************************************************************************************

5.     Program to reverse a given number using while loop
COMMAND LINE ARGUMENT : */
/* rs - VALUE IN RUPEES */
/* ---------------------------------------------------------------- */

public class Price
{
public static void main(String [] args)
{
float rs = Float.parseFloat(args[0]);
int ps = (int)(rs * 100);
System.out.println("Rs. " + rs + " = " + ps + " paise");
}
}


******************************************************************************************************************************************************

6.     Reader Demo1
Public Class Reader Demo1
{
public static void main(String [] args) throws IOException, Exception
{
InputStreamReader inr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(inr);
int i = 0; float f = 0; boolean bo = false;
System.out.println("Enter An Int : ");
i = Integer.parseInt(br.readLine());
System.out.println("Enter A Float : ");
f = Float.valueOf(br.readLine()).floatValue();
System.out.println("Enter A boolean Value : ");
bo = Boolean.valueOf(br.readLine()).booleanValue();
Clear.screen();
System.out.println("Entered Int = " + i);
System.out.println("Entered Float = " + f);
System.out.println("Entered Boolean = " + bo);
}             
}


******************************************************************************************************************************************************

7.     Power of a Number
COMMAND LINE ARGUMENTS : */
/* n1 - BASE NUMBER */
/* n2 - POWER NUMBER */
/* ---------------------------------------------------------------- */

public class Power
{
static double p = 1.0;
public static void main(String [] args)
{
double n1 = Double.parseDouble(args[0]);
double n2 = Double.parseDouble(args[1]);
double lpower = Math.pow(n1,n2);
double upower = power(n1,n2);
System.out.println("\nUsing Math Class\'s pow Method : ");
System.out.println(n1 + " ^ " + n2 + " = " + lpower);
System.out.println("\nUsing User-Defined Method : ");
System.out.println(n1 + " ^ " + n2 + " = " + upower);
}
private static double power(double n1, double n2)
{
if(n2 >= 0)
while(n2-- > 0)
p *= n1;
else
while(n2++ < 0)
p /= n1;
return p;
}
}

******************************************************************************************************************************************************

8.     Leap Year

Public Class Leap Year
{
public static void main(String args[]) throws IOException
{
int yea;
DataInputStream din = new DataInputStream(System.in);
System.out.println("Enter A Year : ");
yea = Integer.parseInt(din.readLine());
boolean isLeap = leap(yea);
if (isLeap == true)
System.out.println(yea + " Is A Leap Year");
else
System.out.println(yea + " Is Not A Leap Year");
}
private static boolean leap(int y)
{
if((y % 4 == 0) && (y % 100 != 0) || (y % 400 == 0))
return true;
else
return false;
}
}


******************************************************************************************************************************************************


9.     List a File
Public Class List File

{
public static void main(String arg[])
{
File f=new File(arg[0]);
if(f.exists()&&f.isDirectory())
{
String fname[]=f.list();
for(int i=0;i<fname.length;i++)
{
File ff=new File(f.getPath(),fname[i]);
if(ff.isDirectory())
System.out.println(fname[i]+"\t\t\t==<dir>");
else
System.out.println(fname[i]);
}
}
else
System.out.println("file is not a directory or nor exists");
}
}

Program to demonstrate matrix input and output

import java.io.*;
public class Matrix
{
public static void main(String [] args) throws IOException, Exception
{
byte mat[][] = new byte[10][10];
int i,j,m,n;
DataInputStream din = new DataInputStream(System.in);
System.out.println("Enter The Order Of Matrix : ");
m = Integer.parseInt(din.readLine());
n = Integer.parseInt(din.readLine());
System.out.println("Enter The Elements One By One : ");
for (i = 0;i < m;i++)
for(j = 0;j < n;j++)
mat[i][j] = Byte.parseByte(din.readLine());
System.out.println("The Matrix elements Are : \n");
for(i = 0;i < m;i++)
{
for(j = 0;j < n;j++)
System.out.print(" " + mat[i][j]);
System.out.println("");
}

}
}


******************************************************************************************************************************************************

10.   Program to search files similar to dir/s in dos


import java.io.*;
import clrscr.*;
public class FileSearch
{
public static void main(String arg[])
{
Clear.screen();
File f=new File(arg[0]);
if(f.exists())
if(f.isDirectory())
{
File fname = new File(f.getName());
listFiles(fname);
}
else
System.out.println(f.getName());
else
System.out.println("file is not a directory or nor exists");
}

private static void listFiles(File f)
{
String filename[] = f.list();
for(int i=0;i<filename.length-1;i++)
{
File ff=new File(f.getPath(),filename[i]);
if(ff.isDirectory())
{
System.out.println("Listing OF Directory : " + filename[i] + "\n");
String fname1[] = ff.list();
for(int j=0;j<fname1.length-1;j++)
{
File ff1=new File(f.getPath(),fname1[j]);
if(ff1.isDirectory())
{
File fn = new File(ff1.getName());
listFiles(fn);
}
else
System.out.println(fname1[j]);
}
}
}
}
}

******************************************************************************************************************************************************

public class DuplicateNumber {

    public int findDuplicateNumber(List<Integer> numbers){
        int highestNumber = numbers.size() - 1;
        int total = getSum(numbers);
        int duplicate = total - (highestNumber*(highestNumber+1)/2);
        return duplicate;
    }
    
    public int getSum(List<Integer> numbers){
        int sum = 0;
        for(int num:numbers){
            sum += num;
        }
        return sum;
    }
    
    public static void main(String a[]){
        List<Integer> numbers = new ArrayList<Integer>();
        for(int i=1;i<30;i++){
            numbers.add(i);
        }
        //add duplicate number into the list
        numbers.add(22);
        Example dn = new Example();
        System.out.println("Duplicate Number: "+dn.findDuplicateNumber(numbers));
    }
}

public class FindMiddleIndex {
                 
            public static int findMiddleIndex(int[] numbers) throws Exception {
         
                int endIndex = numbers.length - 1;
                int startIndex = 0;
                int sumLeft = 0;
                int sumRight = 0;
                while (true) {
                    if (sumLeft > sumRight) {
                        sumRight += numbers[endIndex--];
                    } else {
                        sumLeft += numbers[startIndex++];
                    }
                    if (startIndex > endIndex) {
                        if (sumLeft == sumRight) {
                            break;
                        } else {
                            throw new Exception(
                                    "Please pass proper array to match the requirement");
                        }
                    }
                }
                return endIndex;
            }
         
            public static void main(String a[]) {
                int[] num = { 2, 4, 4, 5, 4, 1 };
                try {
                    System.out.println("Starting from index 0, adding numbers till index "
                                    + findMiddleIndex(num) + " and");
                    System.out.println("adding rest of the numbers can be equal");
                } catch (Exception ex) {
                    System.out.println(ex.getMessage());
                }
            }
        }

public class MyDeadlock {
     String str1 = "Java";
    String str2 = "UNIX";
      Thread trd1 = new Thread("My Thread 1"){
        public void run(){
            while(true){
                synchronized(str1){
                    synchronized(str2){
                        System.out.println(str1 + str2);
                    }
                }
            }
        }
    };
  Thread trd2 = new Thread("My Thread 2"){
        public void run(){
            while(true){
                synchronized(str2){
                    synchronized(str1){
                        System.out.println(str2 + str1);
                    }
                }
            }
        }
    };
    
 public static void main(String a[]){
        MyDeadlock mdl = new MyDeadlock();
        mdl.trd1.start();
        mdl.trd2.start();
    }
}
public class IsPerfectNumber {
    public boolean isPerfectNumber(int number){
          int temp = 0;
        for(int i=1;i<=number/2;i++){
            if(number%i == 0){
                temp += i;
            }
        }
        if(temp == number){
            System.out.println("It is a perfect number");
            return true;
        } else {
            System.out.println("It is not a perfect number");
            return false;
        }
    }
    
    public static void main(String a[]){
        IsPerfectNumber ipn = new IsPerfectNumber();
        System.out.println("Is perfect number: "+ipn.isPerfectNumber(28));
    }
}

public class DecimalToBinary {

    public void printBinaryFormat(int number){
        int binary[] = new int[25];
        int index = 0;
        while(number > 0){
            binary[index++] = number%2;
            number = number/2;
        }
        for(int i = index-1;i >= 0;i--){
            System.out.print(binary[i]);
        }
    }
    
    public static void main(String a[]){
        DecimalToBinary dtb = new DecimalToBinary();
        dtb.printBinaryFormat(25);
    }
}
public class NumberReverse {
    public int reverseNumber(int number){
         int reverse = 0;
        while(number != 0){
            reverse = (reverse*10)+(number%10);
            number = number/10;
        }
        return reverse;
    }
    
    public static void main(String a[]){
        NumberReverse nr = new NumberReverse();
        System.out.println("Result: "+nr.reverseNumber(17868));
    }
}
public class TwoMaxNumbers {
    public void printTwoMaxNumbers(int[] nums){
        int maxOne = 0;
        int maxTwo = 0;
        for(int n:nums){
            if(maxOne < n){
                maxTwo = maxOne;
                maxOne =n;
            } else if(maxTwo < n){
                maxTwo = n;
            }
        }
        System.out.println("First Max Number: "+maxOne);
        System.out.println("Second Max Number: "+maxTwo);
    }
      public static void main(String a[]){
        int num[] = {5,34,78,2,45,1,99,23};
        TwoMaxNumbers tmn = new TwoMaxNumbers();
        tmn.printTwoMaxNumbers(num);
    }
}
public class DuplicateCharsInString {
  public void findDuplicateChars(String str){
      
        Map<Character, Integer> dupMap = new HashMap<Character, Integer>();
        char[] chrs = str.toCharArray();
        for(Character ch:chrs){
            if(dupMap.containsKey(ch)){
                dupMap.put(ch, dupMap.get(ch)+1);
            } else {
                dupMap.put(ch, 1);
            }
        }
        Set<Character> keys = dupMap.keySet();
        for(Character ch:keys){
            if(dupMap.get(ch) > 1){
                System.out.println(ch+"--->"+dupMap.get(ch));
            }
        }
    }
      public static void main(String a[]){
        DuplicateCharsInString dcs = new DuplicateCharsInString();
        dcs.findDuplicateChars("Java2Novice");
    }
}

import java.util.Arrays;

public class MyArrayList {

    private Object[] myStore;
    private int actSize = 0;
    
    public MyArrayList(){
        myStore = new Object[10];
    }
    
    public Object get(int index){
        if(index < actSize){
            return myStore[index];
        } else {
            throw new ArrayIndexOutOfBoundsException();
        }
    }
    
    public void add(Object obj){
        if(myStore.length-actSize <= 5){
            increaseListSize();
        }
        myStore[actSize++] = obj;
    }
    
    public Object remove(int index){
        if(index < actSize){
            Object obj = myStore[index];
            myStore[index] = null;
            int tmp = index;
            while(tmp < actSize){
                myStore[tmp] = myStore[tmp+1];
                myStore[tmp+1] = null;
                tmp++;
            }
            actSize--;
            return obj;
        } else {
            throw new ArrayIndexOutOfBoundsException();
        }
        
    }
    
    public int size(){
        return actSize;
    }
    
    private void increaseListSize(){
        myStore = Arrays.copyOf(myStore, myStore.length*2);
        System.out.println("\nNew length: "+myStore.length);
    }
    
    public static void main(String a[]){
        MyArrayList mal = new MyArrayList();
        mal.add(new Integer(2));
        mal.add(new Integer(5));
        mal.add(new Integer(1));
        mal.add(new Integer(23));
        mal.add(new Integer(14));
        for(int i=0;i<mal.size();i++){
            System.out.print(mal.get(i)+" ");
        }
        mal.add(new Integer(29));
        System.out.println("Element at Index 5:"+mal.get(5));
        System.out.println("List size: "+mal.size());
        System.out.println("Removing element at index 2: "+mal.remove(2));
        for(int i=0;i<mal.size();i++){
            System.out.print(mal.get(i)+" ");
        }
    }
}
import java.util.Stack;
public class StackSort {
    public static Stack<Integer> sortStack(Stack<Integer> input){        
        Stack<Integer> tmpStack = new Stack<Integer>();
        System.out.println("=============== debug logs ================");
        while(!input.isEmpty()) {
            int tmp = input.pop();
            System.out.println("Element taken out: "+tmp);
            while(!tmpStack.isEmpty() && tmpStack.peek() > tmp) {
                input.push(tmpStack.pop());
            }
            tmpStack.push(tmp);
            System.out.println("input: "+input);
            System.out.println("tmpStack: "+tmpStack);
        }
        System.out.println("=============== debug logs ended ================");
        return tmpStack;
    }
    
    public static void main(String a[]){        
        Stack<Integer> input = new Stack<Integer>();
        input.add(34);
        input.add(3);
        input.add(31);
        input.add(98);
        input.add(92);
        input.add(23);
        System.out.println("input: "+input);
        System.out.println("final sorted list: "+sortStack(input));
    }
}



No comments:

Post a Comment

feedback and suggestion.