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 );
             }
         } );
     }
}