Tuesday 28 February 2012

Fibonacci numbers (Right side)


import java.text.*;


    public class TestRight {
        public static void main(String args[]) {
        long f1 = 1;
        long f2 = 1;
        RightFormat rf = new RightFormat(20);
        
        System.out.println("Test of RightFormat(20) on Fibonacci numbers:");
            for(int ix = 0; ix < 32; ix++) {
            System.out.println(rf.format(Long.toString(f1)));
            System.out.println(rf.format(Long.toString(f2)));
            f1 = f1 + f2;
            f2 = f2 + f1;
        }
    }
}

Empty Directory


import java.io.*;
//DANGEROUS Program to empty a directory


    public class Empty {
         public static void main(String[] argv) {
             if (argv.length != 1) { // no progname in argv[0]
             System.err.println("usage: Empty dirname");
             System.exit(1);
         }
        
         File dir = new File(argv[0]);
             if (!dir.exists()) {
             System.out.println(argv[0] + " does not exist");
             return;
         }
        
         String[] info = dir.list();
             for (int i=0; i             File n = new File(argv[0] + dir.separator + info[i]);
             if (!n.isFile()) // skip ., .., other directories too
             continue;
             System.out.println("removing " + n.getPath());
             if (!n.delete())
             System.err.println("Couldn't remove " + n.getPath());
         }
     }
}

Double Array


// Double-subscripted array example
import java.awt.*;
import javax.swing.*;


public class DoubleArray extends JApplet 
     {
     int grades[][] = { { 77, 68, 86, 73 }, { 96, 87, 89, 81 }, { 70, 90, 86, 81 } };
    
     int students, exams;
     String output;
     JTextArea outputArea;
    
     // initialize instance variables
     public void init()
         {
         students = grades.length;
         exams = grades[ 0 ].length;
        
         outputArea = new JTextArea();
         Container c = getContentPane();
         c.add( outputArea );
        
         // build the output string
         output = "The array is:\n";
         buildString();
        
         output += "\n\nLowest grade: " + minimum() +
         "\nHighest grade: " + maximum() + "\n";
        
         for ( int i = 0; i < students; i++ )
         output += "\nAverage for student " + i + " is " + average( grades[ i ] );
        
         outputArea.setFont( new Font( "Courier", Font.PLAIN, 12 ) );
         outputArea.setText( output );
     }
    
     // find the minimum grade
     public int minimum()
         {
         int lowGrade = 100;
        
         for ( int i = 0; i < students; i++ )
         for ( int j = 0; j < exams; j++ )
         if ( grades[ i ][ j ] < lowGrade )
         lowGrade = grades[ i ][ j ];
        
         return lowGrade;
     }
    
    
     // find the maximum grade
     public int maximum()
         {
         int highGrade = 0;
        
         for ( int i = 0; i < students; i++ )
         for ( int j = 0; j < exams; j++ )
         if ( grades[ i ][ j ] > highGrade )
         highGrade = grades[ i ][ j ];
        
         return highGrade;
     }
    
     // determine the average grade for a particular
     // student (or set of grades)
     public double average( int setOfGrades[] )
         {
         int total = 0;
        
         for ( int i = 0; i < setOfGrades.length; i++ )
         total += setOfGrades[ i ];
        
         return ( double ) total / setOfGrades.length;
     }
    
     // build output string
     public void buildString()
         {
         output += " "; // used to align column heads
        
         for ( int i = 0; i < exams; i++ )
         output += "[" + i + "] ";
        
         for ( int i = 0; i < students; i++ ) 
             {
             output += "\ngrades[" + i + "] ";
            
             for ( int j = 0; j < exams; j++ )
             output += grades[ i ][ j ] + " ";
         }
     }
}

DOS Calculator


public class Calculator {
         public static abstract class Operation {
         private final String name;
        
         Operation(String name) { this.name = name; }
        
         public String toString() { return this.name; }
        
         // Perform arithmetic op represented by this constant
         abstract double eval(double x, double y);
        
         // Doubly nested anonymous classes
             public static final Operation PLUS = new Operation("+") {
             double eval(double x, double y) { return x + y; }
         };
             public static final Operation MINUS = new Operation("-") {
             double eval(double x, double y) { return x - y; }
         };
             public static final Operation TIMES = new Operation("*") {
             double eval(double x, double y) { return x * y; }
         };
             public static final Operation DIVIDE = new Operation("/") {
             double eval(double x, double y) { return x / y; }
         };
     }
    
     // Return the results of the specified calculation
         public double calculate(double x, Operation op, double y) {
         return op.eval(x, y);
     }
}


    public class CalcTest {
         public static void main(String args[]) {
         double x = Double.parseDouble(args[0]);
         double y = Double.parseDouble(args[1]);
        
         operate(x, Calculator.Operation.PLUS, y);
         operate(x, Calculator.Operation.MINUS, y);
         operate(x, Calculator.Operation.TIMES, y);
         operate(x, Calculator.Operation.DIVIDE, y);
     }
    
         static void operate(double x, Calculator.Operation op, double y) {
         Calculator c = new Calculator();
         System.out.println(x + " " + op + " " + y + " = " +
         c.calculate(x, op, y));
     }
}

Demonstrating the logical operators


import javax.swing.*;


public class LogicalOperators
     {
     public static void main( String args[] )
         {
         JTextArea outputArea = new JTextArea( 17, 20 );
         JScrollPane scroller = new JScrollPane( outputArea );
         String output = "";
        
         output += "Logical AND (&&)" +
         "\nfalse && false: " + ( false && false ) +
         "\nfalse && true: " + ( false && true ) +
         "\ntrue && false: " + ( true && false ) +
         "\ntrue && true: " + ( true && true );
        
         output += "\n\nLogical OR (||)" +
         "\nfalse || false: " + ( false || false ) +
         "\nfalse || true: " + ( false || true ) +
         "\ntrue || false: " + ( true || false ) +
         "\ntrue || true: " + ( true || true );
        
         output += "\n\nBoolean logical AND (&)" +
         "\nfalse & false: " + ( false & false ) +
         "\nfalse & true: " + ( false & true ) +
         "\ntrue & false: " + ( true & false ) +
         "\ntrue & true: " + ( true & true );
        
         output += "\n\nBoolean logical inclusive OR (|)" +
         "\nfalse | false: " + ( false | false ) +
         "\nfalse | true: " + ( false | true ) +
         "\ntrue | false: " + ( true | false ) +
         "\ntrue | true: " + ( true | true );
        
         output += "\n\nBoolean logical exclusive OR (^)" +
         "\nfalse ^ false: " + ( false ^ false ) +
         "\nfalse ^ true: " + ( false ^ true ) +
         "\ntrue ^ false: " + ( true ^ false ) +
         "\ntrue ^ true: " + ( true ^ true );
        
         output += "\n\nLogical NOT (!)" +
         "\n!false: " + ( !false ) +
         "\n!true: " + ( !true );
        
         outputArea.setText( output );
         JOptionPane.showMessageDialog( null, scroller, "Truth Tables", JOptionPane.INFORMATION_MESSAGE );
         System.exit( 0 );
     }
}

Demonstrating the logical operators


import javax.swing.*;


public class LogicalOperators
     {
     public static void main( String args[] )
         {
         JTextArea outputArea = new JTextArea( 17, 20 );
         JScrollPane scroller = new JScrollPane( outputArea );
         String output = "";
        
         output += "Logical AND (&&)" +
         "\nfalse && false: " + ( false && false ) +
         "\nfalse && true: " + ( false && true ) +
         "\ntrue && false: " + ( true && false ) +
         "\ntrue && true: " + ( true && true );
        
         output += "\n\nLogical OR (||)" +
         "\nfalse || false: " + ( false || false ) +
         "\nfalse || true: " + ( false || true ) +
         "\ntrue || false: " + ( true || false ) +
         "\ntrue || true: " + ( true || true );
        
         output += "\n\nBoolean logical AND (&)" +
         "\nfalse & false: " + ( false & false ) +
         "\nfalse & true: " + ( false & true ) +
         "\ntrue & false: " + ( true & false ) +
         "\ntrue & true: " + ( true & true );
        
         output += "\n\nBoolean logical inclusive OR (|)" +
         "\nfalse | false: " + ( false | false ) +
         "\nfalse | true: " + ( false | true ) +
         "\ntrue | false: " + ( true | false ) +
         "\ntrue | true: " + ( true | true );
        
         output += "\n\nBoolean logical exclusive OR (^)" +
         "\nfalse ^ false: " + ( false ^ false ) +
         "\nfalse ^ true: " + ( false ^ true ) +
         "\ntrue ^ false: " + ( true ^ false ) +
         "\ntrue ^ true: " + ( true ^ true );
        
         output += "\n\nLogical NOT (!)" +
         "\n!false: " + ( !false ) +
         "\n!true: " + ( !true );
        
         outputArea.setText( output );
         JOptionPane.showMessageDialog( null, scroller, "Truth Tables", JOptionPane.INFORMATION_MESSAGE );
         System.exit( 0 );
     }
}

Demonstrating the File class


import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;


public class FileTest extends JFrame implements ActionListener
     {
     private JTextField enter;
     private JTextArea output;
     public FileTest()
         {
         super( "Testing class File" );
        
         enter = new JTextField( "Enter file or directory name here" );
         enter.addActionListener( this );
         output = new JTextArea();
         Container c = getContentPane();
         ScrollPane p = new ScrollPane();
         p.add( output );
         c.add( enter, BorderLayout.NORTH );
         c.add( p, BorderLayout.CENTER );
        
         setSize( 400, 400 );
         show();
     }
    
     public void actionPerformed( ActionEvent e )
         {
         File name = new File( e.getActionCommand() );
        
         if ( name.exists() )
             {
             output.setText( name.getName() + " exists\n" + ( name.isFile() ? "is a file\n" :
             "is not a file\n" ) +
             ( name.isDirectory() ? "is a directory\n" :
             "is not a directory\n" ) +
             ( name.isAbsolute() ? "is absolute path\n" :
             "is not absolute path\n" ) +
             "Last modified: " + name.lastModified() +
             "\nLength: " + name.length() +
             "\nPath: " + name.getPath() +
             "\nAbsolute path: " + name.getAbsolutePath() +
             "\nParent: " + name.getParent() );
            
             if ( name.isFile() )
                 {
                 try
                     {
                     RandomAccessFile r = new RandomAccessFile( name, "r" );
                     StringBuffer buf = new StringBuffer();
                     String text;
                     output.append( "\n\n" );
                    
                     while( ( text = r.readLine() ) != null )
                     buf.append( text + "\n" );
                    
                     output.append( buf.toString() );
                 }
                 catch( IOException e2 )
                     {
                     JOptionPane.showMessageDialog( this, "FILE ERROR",
                     "FILE ERROR", JOptionPane.ERROR_MESSAGE );
                 }
             }
             else if ( name.isDirectory() )
                 {
                 String directory[] = name.list();
                
                 output.append( "\n\nDirectory contents:\n");
                
                 for ( int i = 0; i < directory.length; i++ )
                 output.append( directory[ i ] + "\n" );
             }
         }
         else
             {
             JOptionPane.showMessageDialog( this, e.getActionCommand() + " Does Not Exist",
             "FILE ERROR", JOptionPane.ERROR_MESSAGE );
         }
     }
    
     public static void main( String args[] )
         {
         FileTest app = new FileTest();
        
         app.addWindowListener( new WindowAdapter()
             {
             public void windowClosing( WindowEvent e )
                 {
                 System.exit( 0 );
             }
         } );
     }
}

Currency Formatter


import java.text.*;
import java.io.*;


    class CurrencyFormatter{
    public static void main(String[] args)
    throws java.io.IOException, java.text.ParseException
        {
        
        BufferedReader inStream=
         new BufferedReader(new InputStreamReader(System.in));
        
        double currency;
        
        NumberFormat currencyFormatter=
         NumberFormat.getCurrencyInstance();
        
        NumberFormat numberFormatter=
         NumberFormat.getInstance();
        
        String currencyOut;
        
        System.out.println("Please enter a number to be formatted as currency:\n");
        
        currency=numberFormatter.parse(inStream.readLine()).doubleValue();
        
        currencyOut=currencyFormatter.format(currency);
        
        System.out.println("\n\nThe number formatted as currency is:\n");
        System.out.println(currencyOut);
        
    }//close main
    
}//close class

Creating a Shared File Lock on a File


public static void main(String[] args)
    {
         try {
         // Obtain a file channel
         File file = new File("filename");
         FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
        
         // Create a shared lock on the file.
         // This method blocks until it can retrieve the lock.
         FileLock lock = channel.lock(0, Long.MAX_VALUE, true);
        
         // Try acquiring a shared lock without blocking. This method returns
         // null or throws an exception if the file is already exclusively locked.
             try {
             lock = channel.tryLock(0, Long.MAX_VALUE, true);
             } catch (OverlappingFileLockException e) {
             // File is already locked in this thread or virtual machine
         }
        
         // Determine the type of the lock
         boolean isShared = lock.isShared();
        
         // Release the lock
         lock.release();
        
         // Close the file
         channel.close();
         } catch (Exception e) {
     }
}

Creating a Log file


import java.io.*;
 import java.text.*;
 import java.util.*;


     public class MsgLog {
     protected static String defaultLogFile = "c:\\msglog.txt";
    
         public static void write(String s) throws IOException {
         write(defaultLogFile, s);
     }
    
         public static void write(String f, String s) throws IOException {
         TimeZone tz = TimeZone.getTimeZone("EST"); // or PST, MID, etc ...
         Date now = new Date();
         DateFormat df = new SimpleDateFormat ("yyyy.mm.dd hh:mm:ss ");
         df.setTimeZone(tz);
         String currentTime = df.format(now);
        
         FileWriter aWriter = new FileWriter(f, true);
         aWriter.write(currentTime + " " + s + "\n");
         aWriter.flush();
         aWriter.close();
     }
 }

Creating a File Lock on a File


public static void main(String[] args)
     {
         try {
         // Get a file channel for the file
         File file = new File("Test.java");
         FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
        
         // Use the file channel to create a lock on the file.
         // This method blocks until it can retrieve the lock.
         FileLock lock = channel.lock();
        
         // Try acquiring the lock without blocking. This method returns
         // null or throws an exception if the file is already locked.
             try {
             lock = channel.tryLock();
             } catch (OverlappingFileLockException e) {
             // File is already locked in this thread or virtual machine
         }
        
         // Release the lock
         lock.release();
        
         // Close the file
         channel.close();
         } catch (Exception e) {
     }
}

Count total number of occurences of a String in a text file


import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.StringTokenizer;


public class WordCounter {
public static void main(String args[]) throws Exception {
if(args.length != 1) {
System.out.println("Invalid number of arguments!");
return;
}
String sourcefile = args[0];
String searchFor = "good bye";
int searchLength=searchFor.length();
String thisLine;
try {
BufferedReader bout = new BufferedReader (new FileReader (sourcefile));
String ffline = null;
int lcnt = 0;
int searchCount = 0;
while ((ffline = bout.readLine()) != null) {
lcnt++;
for(int searchIndex=0;searchIndex<ffline.length();) {
int index=ffline.indexOf(searchFor,searchIndex);
if(index!=-1) {
System.out.println("Line number " + lcnt);
searchCount++;
searchIndex+=index+searchLength;
} else {
break;
}
}
}
System.out.println("SearchCount = "+searchCount);
} catch(Exception e) {
System.out.println(e);
}
}
}

Core java programmer


import java.io.*;
import java.sql.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
import java.lang.*;
class History
    {
     
     public static void main(String args[])
         {
         
         
         String dd="asbdjs";
         while(dd.length()>0)
             {
             
                 try{
                 System.out.println("welcome to personal account information");
                 System.out.println("\n"+"enter q to quit");
                 System.out.println("\n");
                 System.out.println("enter account number :");
                 BufferedReader read=new BufferedReader(new InputStreamReader(System.in));
                 String sx=read.readLine();
                 if(sx.equals("q"))
                     {
                     System.exit(0);
                 }
                 else
                     {
                     try
                         {
                         Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                     }
                     catch(ClassNotFoundException k)
                         {
                         System.out.println(k);
                     }
                     try
                         {
                         String url="jdbc:odbc:test";
                         int account=Integer.parseInt(sx);
                         String command="select * from Account where account like "+account;
                         Connection con=DriverManager.getConnection(url);
                         Statement s=con.createStatement();
                         ResultSet rs=s.executeQuery(command);
                         
                         
                         
                         while(rs.next())
                             { 
                        
                             String s1=rs.getString(1);
                             String s2=rs.getString(2);
                             int d1=rs.getInt(3);
                             int d2=rs.getInt(4);
                             int s3=rs.getInt(5);
                             
                             String data="account "+s1+"\n"+"date "+s2+" withdrawl "+d1+" deposit "+d2+"\n"+"balance "+s3+"\n";
                            
                             System.out.println(data);
                             System.out.println("\n");
                             
                         }
                         
                     } 
                     catch(SQLException k)
                         {
                         System.out.println(k);
                     }
                 }
                 
             }
                          
             catch(Exception w)
                 {
                 System.out.println(w);
             }
         }
    }
}

Copy a File


import java.io.*;


     public class jCOPY {
         public static void main(String args[]){
             try {
             jCOPY j = new jCOPY();
             j.CopyFile(new File(args[0]),new File(args[1]));
         }
             catch (Exception e) {
             e.printStackTrace();
         }
     }
    
         public void CopyFile(File in, File out) throws Exception {
         FileInputStream fis = new FileInputStream(in);
         FileOutputStream fos = new FileOutputStream(out);
         byte[] buf = new byte[1024];
         int i = 0;
             while((i=fis.read(buf))!=-1) {
             fos.write(buf, 0, i);
         }
         fis.close();
         fos.close();
     }
}

Converting String to Hex


public static String stringToHex(String base)
    {
     StringBuffer buffer = new StringBuffer();
     int intValue;
     for(int x = 0; x < base.length(); x++)
         {
         int cursor = 0;
         intValue = base.charAt(x);
         String binaryChar = new String(Integer.toBinaryString(base.charAt(x)));
         for(int i = 0; i < binaryChar.length(); i++)
             {
             if(binaryChar.charAt(i) == '1')
                 {
                 cursor += 1;
             }
         }
         if((cursor % 2) > 0)
             {
             intValue += 128;
         }
         buffer.append(Integer.toHexString(intValue) + " ");
     }
     return buffer.toString();
}


public static void main(String[] args)
    {
     String s = "The cat in the hat";
     System.out.println(s);
     System.out.println(test1.stringToHex(s));
}

Converting Non ASCII String to Hex


public static String toHexString(char c)
    {
     String rep;
     String temp;
     int low = c & 0x00FF;
     int high = c & 0xFF00;
     temp = Integer.toHexString(low);
     if( temp.length() == 1 )
     temp = "0" + temp;
    
     rep = temp;
    
     temp = Integer.toHexString(high);
     if( temp.length() == 1 )
     temp = "0" + temp;
    
     rep += temp;
     // If you want a space between bytes
     // rep += " " + temp;
    
     return rep;
}


public static void main(String a[])
    {
     String str = toHexString('b');
     System.out.println(str);
}

Converting Between Strings (Unicode) and Other Character Set Encodings


public static void main(String args[])
    {
     // Create the encoder and decoder for ISO-8859-1
     Charset charset = Charset.forName("ISO-8859-1");
     CharsetDecoder decoder = charset.newDecoder();
     CharsetEncoder encoder = charset.newEncoder();
    
         try {
         // Convert a string to ISO-LATIN-1 bytes in a ByteBuffer
         // The new ByteBuffer is ready to be read.
         ByteBuffer bbuf = encoder.encode(CharBuffer.wrap("a string"));
        
         // Convert ISO-LATIN-1 bytes in a ByteBuffer to a character ByteBuffer and then to a string.
         // The new ByteBuffer is ready to be read.
         CharBuffer cbuf = decoder.decode(bbuf);
         String s = cbuf.toString();
         System.out.println(s);
         } catch (CharacterCodingException e) {
     }
}

Computing Fibonacci numbers


import java.io.*;
import java.math.BigInteger;


/**
* BigFib is a simple class for computing Fibonacci
* numbers, using the Java multi-precision integer
* class java.math.BigInteger.
*/
    public class BigFib {
    BigInteger last;
    BigInteger next;
    int n;
    
    /**
    * Create a new BigFib object, initialized to 0 on
    * the Fibonnacci sequence.
    */
        public BigFib () {
        n = 0;
        last = new BigInteger("0");
        next = new BigInteger("1");
    }
    
    /**
    * Compute c more Fibonnacci numbers, returning the
    * last one. Ideally, c should be even and >0.
    * If you want to print the numbers too, pass printTo
    * as non-null.
    */
        public BigInteger getFib(int c, PrintStream printTo) {
        BigInteger tmp;
            for( ; c > 0; c -= 2) {
            last = last.add(next); n++;
            if (printTo != null) printTo.println(" " + n + "\t" + last);
            next = next.add(last); n++;
            if (printTo != null) printTo.println(" " + n + "\t" + next);
        }
        if (c == 0) return next;
        else return last;
    }
    
    /**
    * Default limit for self-test.
    */
    public static final int defaultLimit = 100;
    
    /**
    * Self-test code, accepts an integer from the
    * command line, or uses the default limit.
    */
        public static void main(String args[]) {
        BigInteger answer;
        
        BigFib fib = new BigFib();
        
        System.out.println("\t\t Fibonacci sequence!");
        System.out.println("");
        
        System.out.println();
        int limit = 100;
            if (args.length > 0) {
            try { limit = Integer.parseInt(args[0]); }
                catch (NumberFormatException nfe) {
                System.err.println("Bad number, using default " + limit);
            }
                if (limit < 1) {
                limit = defaultLimit;
                System.err.println("Limit too low, using default " + limit);
            }
        }
        
        answer = fib.getFib(limit, System.out);
    }
}

Collection classifier


import java.util.*;


    public class CollectionClassifier2 {
         public static String classify(Collection c) {
         return (c instanceof Set ? "Set" :
         (c instanceof List ? "List" : "Unknown Collection"));
     }
    
         public static void main(String[] args) {
             Collection[] tests = new Collection[] {
             new HashSet(), // A Set
             new ArrayList(), // A List
             new HashMap().values() // Neither Set nor List
         };
        
         for (int i = 0; i < tests.length; i++)
         System.out.println(classify(tests[i]));
     }
}

Cloning an Object


    class MyClass implements Cloneable {
         public MyClass() {
     }
         public Object clone() {
         Cloneable theClone = new MyClass();
         // Initialize theClone.
         return theClone;
     }
}


//Here's some code to create a clone. 


MyClass myObject = new MyClass();
MyClass myObjectClone = (MyClass)myObject.clone();


//Arrays are automatically cloneable: 
int[] ints = new int[]{123, 234};
int[] intsClone = (int[])ints.clone();

Check for Files


import java.io.*;
import java.util.*;


/**
* Create filelist.txt file by your self.
*/
    public class CheckFiles {
         public static void main(String[] argv) {
         CheckFiles cf = new CheckFiles();
         System.out.println("CheckFiles starting.");
         cf.getListFromFile();
         cf.getListFromDirectory();
         cf.reportMissingFiles();
         System.out.println("CheckFiles done.");
     }
     public String FILENAME = "filelist.txt";
    
     protected ArrayList listFromFile;
     protected ArrayList listFromDir = new ArrayList();
    
         protected void getListFromFile() {
         listFromFile = new ArrayList();
         BufferedReader is;
             try {
             is = new BufferedReader(new FileReader(FILENAME));
             String line;
             while ((line = is.readLine()) != null)
             listFromFile.add(line);
             } catch (FileNotFoundException e) {
             System.err.println("Can't open file list file.");
             return;
             } catch (IOException e) {
             System.err.println("Error reading file list");
             return;
         }
     }
    
     /** Get list of names from the directory */
         protected void getListFromDirectory() {
         listFromDir = new ArrayList();
         String[] l = new java.io.File(".").list();
         for (int i=0; i         listFromDir.add(l[i]);
     }
    
         protected void reportMissingFiles() {
         for (int i=0; i         if (!listFromDir.contains(listFromFile.get(i)))
         System.err.println("File " + listFromFile.get(i) + " missing.");
     }
}