In late 1995, the Java programming language burst onto the Internet scene and gained instant celebrity status.
Saturday, February 26, 2011
Histogram printing program
import javax.swing.*;
public class Histogram
{
public static void main( String args[] )
{
int n[] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 };
String output = "";
output += "Element\tValue\tHistogram";
for ( int i = 0; i < n.length; i++ )
{
output += "\n" + i + "\t" + n[ i ] + "\t";
for ( int j = 1; j <= n[ i ]; j++ ) // print a bar
output += "*";
}
JTextArea outputArea = new JTextArea( 11, 30 );
outputArea.setText( output );
JOptionPane.showMessageDialog( null, outputArea,"Histogram Printing Program",JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
}
Hash table
import java.util.*;
public class SortHashtabledesc {
public static void main(String[] args) {
// Create and populate hashtable
Hashtable ht = new Hashtable();
ht.put("abc",new Double(3445.23));
ht.put("xyz",new Double(2333.56));
ht.put("pqr",new Double(3900.88));
ht.put("mno",new Double(2449.00));
// Sort hashtable.
Vector v = new Vector(ht.keySet());
Collections.sort(v, Collections.reverseOrder());
// Display (sorted) hashtable.
for (Enumeration e = v.elements(); e.hasMoreElements();) {
String key = (String)e.nextElement();
System.out.println(key+":"+ht.get(key));
System.out.println();
}
}
}
Getting and Setting the Modification Time of a File or Directory
public static void main(String args[]){
try{
File file = new File("file.txt");
// Get the last modified time
long modifiedTime = file.lastModified();
// 0L is returned if the file does not exist
// Set the last modified time
long newModifiedTime = System.currentTimeMillis();
boolean success = file.setLastModified(newModifiedTime);
if (!success) {
System.out.println("Operation failed");
}
}
catch (Exception ioe){
ioe.printStackTrace();
}
}
Get hashtable keys from value
class keyhash
{
ResultSet rs;
Hashtable hash;
Vector v;
static int i;
Enumeration e;
public static void main(String[] args)
{
keyhash gs = new keyhash();
System.out.println("Hello World!");
gs.getresultset();
}
public void getresultset()
{
Hashtable hash = new Hashtable();
Vector v = new Vector();
boolean connected = dbConnect();
// Establish database connection here
if(connected == true)
{
try{
PreparedStatement getArticles = db.con.prepareStatement
("select * from xx where id = ?"
// sample query
)
String artid;
getArticles.setInt(1, 4);
//This passes integer 4 as a parameter in
//the sql query
rs = getArticles.executeQuery();
while (rs.next() == true)
{
key = rs.getString(1);
value = rs.getString(2);
hash.put(key,value);
//Hashtable populated
}
fillvector(hash,v);
getkeys(v);
rs.close();
}
catch(Exception ex){
ex.printStackTrace();
}
}
}
public void fillvector(Hashtable hash,Vector v)
{
int j=0;
boolean success;
Enumeration e = hash.keys();
while(e.hasMoreElements())
{
String key = (String)(e.nextElement());
String value = (String)hash.get(key);
if(value.matches("*****"))
//Put the value here to retrieve the
// corresponding keys
{
v.addElement(key);
//Add the corresponding keys to the vector
}
}
}
public void getkeys(Vector v)
{
Enumeration ev= v.elements();
while (ev.hasMoreElements())
{
System.out.println(ev.nextElement());
// Print the keys related to a single value
}
}
}
Formatting real number with Decimal
import java.text.*;
public class NumFormat {
public static void main (String[] args) {
DecimalFormat science = new DecimalFormat("0.000E0");
DecimalFormat plain = new DecimalFormat("0.0000");
for(double d=100.0; d<140.0; d*=1.10) {
System.out.println("Scientific: " + science.format(d) +
" and Plain: " + plain.format(d));
}
}
}
Float datatype
// Static factory version of complex class
public class Complex1 {
private final float re;
private final float im;
private Complex1(float re, float im) {
this.re = re;
this.im = im;
}
public static Complex1 valueOf(float re, float im) {
return new Complex1(re, im);
}
public static Complex1 valueOfPolar(float r, float theta) {
return new Complex1((float) (r * Math.cos(theta)),
(float) (r * Math.sin(theta)));
}
// Accessors with no corresponding mutators
public float realPart() { return re; }
public float imaginaryPart() { return im; }
public Complex1 add(Complex1 c) {
return new Complex1(re + c.re, im + c.im);
}
public Complex1 subtract(Complex1 c) {
return new Complex1(re - c.re, im - c.im);
}
public Complex1 multiply(Complex1 c) {
return new Complex1(re*c.re - im*c.im,
re*c.im + im*c.re);
}
public Complex1 divide(Complex1 c) {
float tmp = c.re*c.re + c.im*c.im;
return new Complex1((re*c.re + im*c.im)/tmp,
(im*c.re - re*c.im)/tmp);
}
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Complex1))
return false;
Complex1 c = (Complex1)o;
return (Float.floatToIntBits(re) ==
Float.floatToIntBits(c.re)) &&
(Float.floatToIntBits(im) ==
Float.floatToIntBits(im));
}
public int hashCode() {
int result = 17 + Float.floatToIntBits(re);
result = 37*result + Float.floatToIntBits(im);
return result;
}
public String toString() {
return "(" + re + " + " + im + "i)";
}
// Public constants
public static final Complex1 ZERO = new Complex1(0, 0);
public static final Complex1 ONE = new Complex1(1, 0);
public static final Complex1 I = new Complex1(0, 1);
public static void main(String args[]) {
Complex1 x = Complex1.valueOf(2, 3);
Complex1 y = Complex1.valueOf(2,-3);
System.out.println(x + " + " + y + " = " + x.add(y));
System.out.println(x + " - " + y + " = " + x.subtract(y));
System.out.println(x + " * " + y + " = " + x.multiply(y));
System.out.println(x + " / " + y + " = " + x.divide(y));
System.out.println(x.divide(y).multiply(y));
Complex1 z = Complex1.valueOfPolar(1, (float) (Math.PI/4));
Complex1 w = Complex1.valueOf(z.realPart(), -z.imaginaryPart());
System.out.println(z + " * " + w + " = " + z.multiply(w));
}
}
Finding the maximum of three doubles
import java.awt.Container;
import javax.swing.*;
public class DoubleMax extends JApplet
{
public void init()
{
JTextArea outputArea = new JTextArea();
String s1 = JOptionPane.showInputDialog( "Enter first floating-point value" );
String s2 = JOptionPane.showInputDialog( "Enter second floating-point value" );
String s3 = JOptionPane.showInputDialog( "Enter third floating-point value" );
double number1 = Double.parseDouble( s1 );
double number2 = Double.parseDouble( s2 );
double number3 = Double.parseDouble( s3 );
double max = maximum( number1, number2, number3 );
outputArea.setText( "number1: " + number1 + "\nnumber2: " + number2 + "\nnumber3: " + number3 +
"\nmaximum is: " + max );
// get the applet's GUI component display area
Container c = getContentPane();
// attach outputArea to Container c
c.add( outputArea );
}
// maximum method definition
public double maximum( double x, double y, double z )
{
return Math.max( x, Math.max( y, z ) );
}
}
Find Numeric filter
class FindNumFilter {
/** The value of this filter */
int num;
/** Constants for the comparison operators. */
final int LE = -2, LT = -1, EQ = 0, GT = +1, GE = +2;
/** The current comparison operator */
int mode = EQ;
/** Constructor */
FindNumFilter(String input) {
switch(input.charAt(0)) {
case '+': mode = GT; break;
case '-': mode = LT; break;
case '=': mode = EQ; break;
// No syntax for LE or GE yet.
}
num = Math.abs(Integer.parseInt(input));
}
/** Construct a NumFilter when you know its mode and value */
FindNumFilter(int mode, int value) {
this.mode = mode;
num = value;
}
boolean accept(int n) {
switch(mode) {
case GT: return n > num;
case EQ: return n == num;
case LT: return n < num;
default:
System.err.println("UNEX CASE " + mode );
return false;
}
}
}
File Input and Output Stream
import java.io.*;
class FileIO {
public static void main(String[] args) {
System.out.println("Enter some numbers.");
StreamTokenizer st = new StreamTokenizer(
new BufferedReader(new InputStreamReader(System.in)));
File f = new File("temp.out");
int numberCount = 0;
try {
DataOutputStream dos = new DataOutputStream(
new BufferedOutputStream(new FileOutputStream(f)));
while (st.nextToken() != st.TT_EOF) {
if (st.ttype == st.TT_NUMBER) {
dos.writeDouble(st.nval);
numberCount++;
}
}
System.out.println("numberCount=" + numberCount);
dos.flush();
dos.close();
DataInputStream dis = new DataInputStream(
new BufferedInputStream(new FileInputStream(f)));
for (int i = 0; i < numberCount; i++) {
System.out.println("number=" + dis.readDouble());
}
dis.close();
} catch (IOException e) {
System.err.println("FileIO: " + e);
} finally {
f.delete();
}
}
}
/* ............... Example compile and run(s)
% javac file.java
% java FileIO
Enter some numbers.
1 2 3
4.4 5.5
6.67
^D
numberCount=6
number=1.0
number=2.0
number=3.0
number=4.4
number=5.5
number=6.67
... end of example run(s) */
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));
}
}
Determining When an Object Is No Longer Used
// Create the weak reference.
ReferenceQueue rq = new ReferenceQueue();
WeakReference wr = new WeakReference(object, rq);
// Wait for all the references to the object.
try {
while (true) {
Reference r = rq.remove();
if (r == wr) {
// Object is no longer referenced.
}
}
} catch (InterruptedException e) {
}
Determining If Two Filename Paths Refer to the Same File
public static void main(String args[]){
try{
File file1 = new File("gg/file.txt");
File file2 = new File("file.txt");
// Filename paths are not equal
boolean b = file1.equals(file2); // false
// Normalize the paths
try {
file1 = file1.getCanonicalFile(); // c:\almanac1.4\filename
file2 = file2.getCanonicalFile(); // c:\almanac1.4\filename
} catch (IOException e) {
}
// Filename paths are now equal
b = file1.equals(file2); // true
}
catch (Exception ioe){
ioe.printStackTrace();
}
}
Detect ASCII values
BufferedReader inStream=new BufferedReader(new InputStreamReader(System.in));
int a;
for(int i=1;i<=26;i++)
{
System.out.println("please enter a character: ");
a=(int)System.in.read();
System.out.println("The integer code for " +(char)a+ " is " +(int)a);
inStream.readLine();
}
Deserializing an Object
public static void main(String args[]){
try{
// Deserialize from a file
File file = new File("filename.ser");
ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
// Deserialize the object
javax.swing.JButton button = (javax.swing.JButton) in.readObject();
in.close();
// Get some byte array data
byte[] bytes = getBytesFromFile(file);
// see e36 Reading a File into a Byte Array for the implementation of this method
// Deserialize from a byte array
in = new ObjectInputStream(new ByteArrayInputStream(bytes));
button = (javax.swing.JButton) in.readObject();
in.close();
}
catch (Exception ioe){
ioe.printStackTrace();
}
}
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
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);
}
}
}
}
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));
}
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 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.");
}
}
Card shuffling and dealing program
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DeckOfCards extends JFrame
{
private Card deck[];
private int currentCard;
private JButton dealButton, shuffleButton;
private JTextField displayCard;
private JLabel status;
public DeckOfCards()
{
super( "Card Dealing Program" );
String faces[] = { "Ace", "Deuce", "Three", "Four",
"Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King" };
String suits[] = { "Hearts", "Diamonds", "Clubs", "Spades" };
deck = new Card[ 52 ];
currentCard = -1;
for ( int i = 0; i < deck.length; i++ )
deck[ i ] = new Card( faces[ i % 13 ], suits[ i / 13 ] );
Container c = getContentPane();
c.setLayout( new FlowLayout() );
dealButton = new JButton( "Deal card" );
dealButton.addActionListener( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
Card dealt = dealCard();
if ( dealt != null )
{
displayCard.setText( dealt.toString() );
status.setText( "Card #: " + currentCard );
}
else
{
displayCard.setText( "NO MORE CARDS TO DEAL" );
status.setText( "Shuffle cards to continue" );
}
}
} );
c.add( dealButton );
shuffleButton = new JButton( "Shuffle cards" );
shuffleButton.addActionListener( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
displayCard.setText( "SHUFFLING ..." );
shuffle();
displayCard.setText( "DECK IS SHUFFLED" );
}
});
c.add( shuffleButton );
displayCard = new JTextField( 20 );
displayCard.setEditable( false );
c.add( displayCard );
status = new JLabel();
c.add( status );
setSize( 275, 120 ); // set the window size
show(); // show the window
}
public void shuffle()
{
currentCard = -1;
for ( int i = 0; i < deck.length; i++ )
{
int j = ( int ) ( Math.random() * 52 );
Card temp = deck[ i ]; // swap
deck[ i ] = deck[ j ]; // the
deck[ j ] = temp; // cards
}
dealButton.setEnabled( true );
}
public Card dealCard()
{
if ( ++currentCard < deck.length )
return deck[ currentCard ];
else
{
dealButton.setEnabled( false );
return null;
}
}
public static void main( String args[] )
{
DeckOfCards app = new DeckOfCards();
app.addWindowListener( new WindowAdapter()
{
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
} );
}
}
class Card
{
private String face;
private String suit;
public Card( String f, String s )
{
face = f;
suit = s;
}
public String toString()
{
return face + " of " + suit;
}
}
Byte to Binary Conversion
import java.io.*;
/**
* BinCat is a simple class for reading bytes and
* writting them back out in binary representation.
*/
public class BinCat {
BufferedInputStream brIn;
PrintStream psOut;
public static int BYTES_PER_LINE = 4;
public BinCat() {
this(System.in,System.out);
}
public BinCat(InputStream in, OutputStream out) {
brIn = new BufferedInputStream(in);
if (out instanceof PrintStream)
psOut = (PrintStream)out;
else
psOut = new PrintStream(out);
}
public void doit() {
int ch, cv, bit, cnt;
try {
for(cnt = 0, ch = brIn.read(); ch >= 0; ch = brIn.read()) {
cv = ((int)ch & 0x00ff);
for(bit = 7; bit >= 0; bit--) {
if ((cv & (2 << bit)) > 0)
psOut.print("1");
else
psOut.print("0");
}
cnt++;
if ((cnt % BYTES_PER_LINE) == 0)
psOut.println("");
}
} catch (IOException e) { }
return;
}
/**
* Test main for BinCat
*/
public static void main(String args[]) {
BinCat kitty;
kitty = new BinCat();
kitty.doit();
System.exit(0);
}
}
Automatically create and delete a file
import java.util.*;
import java.io.*;
public class ab extends TimerTask
{
static File file;
public static void main(String[] args ) throws IOException
{
file = new File ("test.dat");
if (! file.exists() )
{
file.createNewFile();
}
System.out.println("File Created");
ab test = new ab();
Timer t = new Timer ();
t.schedule(test, 30*1000L);
try
{
while (file.exists())
{
System.out.print('.');
Thread.sleep(1000);
}
}
catch (InterruptedException ie)
{
System.out.println("Error");
}
System.exit(0);
} //end of main
public void run()
{
file.delete();
}
} //end of public class ab
using ByteBuffer
public static void main(String[] args)
{
// Create a ByteBuffer using a byte array
byte[] bytes = new byte[10];
ByteBuffer buf = ByteBuffer.wrap(bytes);
// Create a non-direct ByteBuffer with a 10 byte capacity
// The underlying storage is a byte array.
buf = ByteBuffer.allocate(10);
// Create a direct (memory-mapped) ByteBuffer with a 10 byte capacity.
buf = ByteBuffer.allocateDirect(10);
// Get the ByteBuffer's capacity
int capacity = bbuf.capacity(); // 10
// Use the absolute get(). This method does not affect the position.
byte b = bbuf.get(5); // position=0
// Set the position
bbuf.position(5);
// Use the relative get()
b = bbuf.get();
// Get the new position
int pos = bbuf.position(); // 6
// Get remaining byte count
int rem = bbuf.remaining(); // 4
// Set the limit
bbuf.limit(7); // remaining=1
// This convenience method sets the position to 0
bbuf.rewind(); // remaining=7
// Use the absolute put(). This method does not affect the position.
bbuf.put((byte)0xFF); // position=0
// Use the relative put()
bbuf.put((byte)0xFF);
// This convenience method sets the position to 0
bbuf.rewind(); // remaining=7
/*
Use ByteBuffer to store Strings
*/
// Create a character ByteBuffer
CharBuffer cbuf = buf.asCharBuffer();
// Write a string
cbuf.put("str");
// Convert character ByteBuffer to a string.
// Uses characters between current position and limit so flip it first
cbuf.flip();
String s = cbuf.toString(); // str Does not affect position
// Get a substring
int start = 2; // start is relative to cbuf's current position
int end = 5;
CharSequence sub = cbuf.subSequence(start, end); // str
/*
Set Byte Ordering for a ByteBuffer
*/
// Get default byte ordering
ByteOrder order = buf.order(); // ByteOrder.BIG_ENDIAN
// Put a multibyte value
buf.putShort(0, (short)123);
buf.get(0); // 0
buf.get(1); // 123
// Set to little endian
buf.order(ByteOrder.LITTLE_ENDIAN);
// Put a multibyte value
buf.putShort(0, (short)123);
buf.get(0); // 123
buf.get(1); // 0
}
Use of Runtime Class
import java.io.*;
class test extends Thread
{
public void run()
{
Runtime r=Runtime.getRuntime();
Process p=null;
try
{
for(int i=0;i<=100;i++)
{
p=r.exec("net send vishal how r u!");
//p.waitFor();
Thread.sleep(5000);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void main(String args[])
{
test t=new test();
t.run();
}
}
Set the foreground and background color to the text area
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
class colopat extends Frame
{
Checkbox r,g,b;
Checkbox m,y,gr,p,w,bl,c;
TextArea ta;
Checkbox r1,g1,b1;
Checkbox m1,y1,gr1,p1,w1,bl1,c1;
Label ba,fo;
Panel pa1,p2,p3;
colopat()
{
setSize(800,600);
setLayout(new BorderLayout());
pa1=new Panel(new GridLayout(5,2,10,10));
p2=new Panel(new GridLayout(5,2,10,10));
CheckboxGroup cbg=new CheckboxGroup();
r=new Checkbox("red",cbg,false);
g=new Checkbox("green",cbg,false);
b=new Checkbox("blue",cbg,false);
m=new Checkbox("megenta",cbg,false);
y=new Checkbox("yellow",cbg,false);
gr=new Checkbox("grey",cbg,false);
p=new Checkbox("pink",cbg,false);
w=new Checkbox("white",cbg,false);
bl=new Checkbox("black",cbg,true);
c=new Checkbox("cyan",cbg,false);
ba=new Label("BACKGROUND COLORS",Label.CENTER);
ba.setBackground(Color.pink);
pa1.add(ba);
pa1.add(r);
pa1.add(b);
pa1.add(m);
pa1.add(y);
pa1.add(gr);
pa1.add(p);
pa1.add(w);
pa1.add(bl);
pa1.add(c);
add("West",pa1);
ta=new TextArea(5,25);
p3=new Panel(new GridLayout(3,1));
p3.add(new Label("Text Area",1));
p3.add(ta);
add("Center",p3);
r.addItemListener(new CheckBoxHandler(this));
g.addItemListener(new CheckBoxHandler(this));
b.addItemListener(new CheckBoxHandler(this));
m.addItemListener(new CheckBoxHandler(this));
y.addItemListener(new CheckBoxHandler(this));
gr.addItemListener(new CheckBoxHandler(this));
p.addItemListener(new CheckBoxHandler(this));
w.addItemListener(new CheckBoxHandler(this));
c.addItemListener(new CheckBoxHandler(this));
bl.addItemListener(new CheckBoxHandler(this));
CheckboxGroup cbg1=new CheckboxGroup();
r1=new Checkbox("red",cbg1,false);
g1=new Checkbox("green",cbg1,false);
b1=new Checkbox("blue",cbg1,false);
m1=new Checkbox("megenta",cbg1,false);
y1=new Checkbox("yellow",cbg1,false);
gr1=new Checkbox("grey",cbg1,false);
p1=new Checkbox("pink",cbg1,false);
w1=new Checkbox("white",cbg1,false);
bl1=new Checkbox("black",cbg1,true);
c1=new Checkbox("cyan",cbg1,false);
fo=new Label("FOREGROUND COLORS");
fo.setBackground(Color.pink);
p2.add(fo);
p2.add(c1);
p2.add(g1);
p2.add(b1);
p2.add(m1);
p2.add(y1);
p2.add(gr1);
p2.add(p1);
p2.add(w1);
p2.add(bl1);
p2.add(c1);
add("East",p2);
r1.addItemListener(new CheckBoxHandler(this));
g1.addItemListener(new CheckBoxHandler(this));
b1.addItemListener(new CheckBoxHandler(this));
m1.addItemListener(new CheckBoxHandler(this));
y1.addItemListener(new CheckBoxHandler(this));
gr1.addItemListener(new CheckBoxHandler(this));
p1.addItemListener(new CheckBoxHandler(this));
w1.addItemListener(new CheckBoxHandler(this));
c1.addItemListener(new CheckBoxHandler(this));
bl1.addItemListener(new CheckBoxHandler(this));
c1.addItemListener(new CheckBoxHandler(this));
addWindowListener(new mywindowAdapter(this));
setVisible(true);
}
public static void main(String args[])
{
new colopat();
}
}
class CheckBoxHandler implements ItemListener
{
colopat cp;
CheckBoxHandler(colopat cp)
{
this.cp=cp;
}
public void itemStateChanged(ItemEvent ie)
{
if(cp.r.getState())
cp.ta.setBackground(Color.red);
else if(cp.g.getState())
cp.ta.setBackground(Color.green);
else if(cp.b.getState())
cp.ta.setBackground(Color.blue);
else if(cp.m.getState())
cp.ta.setBackground(Color.magenta);
else if(cp.y.getState())
cp.ta.setBackground(Color.yellow);
else if(cp.gr.getState())
cp.ta.setBackground(Color.lightGray);
else if(cp.bl.getState())
cp.ta.setBackground(Color.black);
else if(cp.w.getState())
cp.ta.setBackground(Color.white);
else if(cp.p.getState())
cp.ta.setBackground(Color.pink);
else
cp.ta.setBackground(Color.cyan);
if(cp.r1.getState())
cp.ta.setForeground(Color.red);
else if(cp.g1.getState())
cp.ta.setForeground(Color.green);
else if(cp.b1.getState())
cp.ta.setForeground(Color.blue);
else if(cp.m1.getState())
cp.ta.setForeground(Color.magenta);
else if(cp.y1.getState())
cp.ta.setForeground(Color.yellow);
else if(cp.gr1.getState())
cp.ta.setForeground(Color.lightGray);
else if(cp.bl1.getState())
cp.ta.setForeground(Color.black);
else if(cp.w1.getState())
cp.ta.setForeground(Color.white);
else if(cp.p1.getState())
cp.ta.setForeground(Color.pink);
else
cp.ta.setForeground(Color.cyan);
}
}
class mywindowAdapter extends WindowAdapter
{
colopat cp;
mywindowAdapter(colopat cp)
{
this.cp=cp;
}
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
School Management System
import java.awt.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.*;
public class ProjectX extends JFrame implements ChangeListener,
ActionListener
{
static int choice = 0;
static String line = "--------------------------------
";
DataInputStream inputData = new DataInputStream(System.in);
private Registration studentDetails = new Registration();
int topScore = studentDetails.getTopScore();
int passMarks = studentDetails.getPassMarks();
int firstClass = studentDetails.getFirstClass();
int secondClass = studentDetails.getSecondClass();
JTabbedPane tabbedPane = new JTabbedPane();
JLabel statusLabel = new JLabel();
JLabel titleLabel = new JLabel("Student Software Beta Edition");
JPanel addStudentPanel = new JPanel();
JTextField studentName = new JTextField();
JTextField physicsMarks = new JTextField();
JTextField biologyMarks = new JTextField();
JTextField mathsMarks = new JTextField();
JButton submitDetails = new JButton("Submit Details");
JPanel studentDetailsPanel = new JPanel();
JTextField studentID1 = new JTextField();
JTextArea studentInfo = new JTextArea();
JButton submitID1 = new JButton("Submit ID");
JPanel studentGradePanel = new JPanel();
JTextField studentID2 = new JTextField();
JTextArea studentGrade = new JTextArea();
JButton submitID2 = new JButton("Submit ID");
JPanel numberPassedPanel = new JPanel();
JTextArea studentPassed = new JTextArea();
JPanel classTopperPanel = new JPanel();
JTextArea studentTopper = new JTextArea();
public ProjectX(String frameTitle)
{
super(frameTitle);
setResizable(true);
setSize(400,400);
submitDetails.addActionListener(this);
submitID1.addActionListener(this);
submitID2.addActionListener(this);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(titleLabel,"North");
tabbedPane.addTab("Add Student",addStudentPanel);
addStudentPanel.setLayout(new GridLayout(8,2,5,5));
addStudentPanel.add(new JLabel("Student Name: "));
addStudentPanel.add(studentName);
addStudentPanel.add(new JLabel("Physics Marks: "));
addStudentPanel.add(physicsMarks);
addStudentPanel.add(new JLabel("Biology Marks: "));
addStudentPanel.add(biologyMarks);
addStudentPanel.add(new JLabel("Maths Marks: "));
addStudentPanel.add(mathsMarks);
addStudentPanel.add(submitDetails);
tabbedPane.addTab("Student Details",studentDetailsPanel);
studentDetailsPanel.add(new JLabel("Enter Student ID: "));
studentDetailsPanel.add(studentID1);
studentDetailsPanel.add(submitID1);
studentDetailsPanel.add(new JLabel("Student Details:"));
studentDetailsPanel.add(studentInfo);
tabbedPane.addTab("Student Grade",studentGradePanel);
studentGradePanel.setLayout(new GridLayout(5,2,5,5));
studentGradePanel.add(new JLabel("Enter Student ID: "));
studentGradePanel.add(studentID2);
studentGradePanel.add(submitID2);
studentGradePanel.add(new JLabel("Student Grade:"));
studentGradePanel.add(studentGrade);
tabbedPane.addTab("Passed Student",numberPassedPanel);
numberPassedPanel.setLayout(new GridLayout(2,2,5,5));
numberPassedPanel.add(new JLabel("Number of Student Passed: "));
numberPassedPanel.add(studentPassed);
tabbedPane.addTab("Class Topper",classTopperPanel);
classTopperPanel.setLayout(new GridLayout(2,2,5,5));
classTopperPanel.add(new JLabel("Here are the class Toppers: "));
classTopperPanel.add(studentTopper);
tabbedPane.addChangeListener(this);
getContentPane().add(tabbedPane,"Center");
statusLabel.setText("Status: Normal");
getContentPane().add(statusLabel,"South");
setVisible(true);
}
public static void main(String args[])
{
ProjectX outputScreen = new ProjectX("Case Study");
}
public String setStudentInfo()
{
int id = studentDetails.addStudent(studentName.getText(),
Integer.parseInt(physicsMarks.getText()),
Integer.parseInt(biologyMarks.getText()),
Integer.parseInt(mathsMarks.getText()));
return ("
" +
line +
"Record Created For " + studentName +
"
" +
"Student ID: " + id +
"
" +
line );
}
public String getStudentInfo()
{
int id = Integer.parseInt(studentID1.getText());
if(studentDetails.getStudentDetails(id))
return ("
" +
line +
"Student Details
" +
line +
"Student ID:" + " " + id + "
" +
"Student Name:" + " " + studentDetails.studentName + "
" +
"Physics Marks:" + " " + studentDetails.physicsMarks + "
" +
"Biology Marks:" + " " + studentDetails.biologyMarks + "
" +
"Maths Marks:" + " " + studentDetails.mathsMarks + "
" +
line );
else
return("
Records Not Found for ID " + id);
}
public String getStudentGrade()
{
int id = Integer.parseInt(studentID2.getText());
studentDetails.getStudentDetails(id);
String grade;
if(studentDetails.studentName == null)
{
System.out.println("
Records Not Found for ID " + id);
return null;
}
if(studentDetails.physicsMarks < passMarks ||
studentDetails.biologyMarks < passMarks || studentDetails.mathsMarks <
passMarks)
{
grade = "Failed";
}
else
{
int avgMarks = (studentDetails.physicsMarks +
studentDetails.biologyMarks + studentDetails.mathsMarks)/3;
if(avgMarks >= passMarks && avgMarks < secondClass) grade = "Pass
Class";
else if(avgMarks >= secondClass && avgMarks < firstClass) grade =
"Second Class";
else if(avgMarks >= firstClass && avgMarks < topScore) grade = "First
Class";
else grade = "Distinction";
}
return(line + "Grade For " + studentDetails.studentName + " is " + grade
+ "
" + line);
}
public String getNumberPasses()
{
int lastID = Registration.getNextID() -1;
boolean passed = true;
int numberPassed = 0;
for(int id = 1; id <= lastID; id++)
{
studentDetails.getStudentDetails(id);
if(studentDetails.physicsMarks >= passMarks &&
studentDetails.biologyMarks >= passMarks && studentDetails.mathsMarks >=
passMarks) numberPassed++;
}
return(line + "Number of Student Passed: " + numberPassed + "
" +
line);
}
public String getClassTopper()
{
int lastID = Registration.getNextID() -1;
String classTopper;
StringBuffer buffer = new StringBuffer(500);
int topMarks = 0;
for(int id = 1; id <= lastID; id++)
{
studentDetails.getStudentDetails(id);
int studentMarks = studentDetails.physicsMarks +
studentDetails.biologyMarks + studentDetails.mathsMarks;
if(studentMarks > topMarks) topMarks = studentMarks;
}
buffer.append(line + "Student Having Top Marks:
");
for(int id = 1; id <= lastID; id++)
{
studentDetails.getStudentDetails(id);
int studentMarks = studentDetails.physicsMarks +
studentDetails.biologyMarks + studentDetails.mathsMarks;
if(studentMarks == topMarks)
{
buffer.append(studentDetails.studentName + " Having Total Marks: " +
topMarks + "
");
}
}
buffer.append(line);
return(buffer.toString());
}
public void stateChanged(ChangeEvent e)
{
switch(tabbedPane.getSelectedIndex())
{
case 3: studentPassed.setText(getNumberPasses());
break;
case 4: studentTopper.setText(getClassTopper());
break;
}
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == submitID1)
{
studentInfo.setText(getStudentInfo());
}
else if(e.getSource() == submitID2)
{
studentGrade.setText(getStudentGrade());
}
if(e.getSource() == submitDetails)
{
setStudentInfo();
}
}
}
//Registration Class
class Registration
{
private int topScore = 90;
private int passMarks = 35;
private int firstClass = 65;
private int secondClass = 45;
private static String idFile = "id.dat";
private static String studentFile = "studentfile.dat";
public int id;
public String studentName;
public int physicsMarks;
public int biologyMarks;
public int mathsMarks;
public int addStudent(String studentName, int physicsMarks, int
biologyMarks, int mathsMarks)
{
int id = 0;
try
{
FileWriter fileOutput = new FileWriter(Registration.studentFile,true);
id = Registration.getNextID();
String buffer = id + "|" + studentName + "|" + physicsMarks + "|" +
biologyMarks + "|" + mathsMarks + "
";
fileOutput.write(buffer);
fileOutput.close();
Registration.setID(id);
}
catch(IOException e)
{
System.err.println(e.toString());
System.exit(1);
}
return id;
}
//Function to get the details of a student given the ID
public boolean getStudentDetails(int id)
{
try
{
FileReader fileInput = new FileReader(Registration.studentFile);
BufferedReader br = new BufferedReader(fileInput);
{
String str;
while((str = br.readLine()) != null)
{
StringTokenizer fields = new StringTokenizer(str,"|");
if(Integer.parseInt(fields.nextToken()) == id)
{
this.id = id;
this.studentName = fields.nextToken();
this.physicsMarks = Integer.parseInt(fields.nextToken());
this.biologyMarks = Integer.parseInt(fields.nextToken());
this.mathsMarks = Integer.parseInt(fields.nextToken());
return true;
}
}
}
}
catch(IOException e)
{
System.err.println(e.toString());
System.exit(1);
}
return false;
}
public int getTopScore()
{
return topScore;
}
public int getPassMarks()
{
return passMarks;
}
public int getFirstClass()
{
return firstClass;
}
public int getSecondClass()
{
return secondClass;
}
//Function to get the next ID available
public static int getNextID()
{
int id = 0;
try
{
RandomAccessFile studentIDFile = new
RandomAccessFile(Registration.idFile,"rw");
if(studentIDFile.length() == 0)
{
id = 0;
}
else id = studentIDFile.readInt();
id++;
studentIDFile.close();
}
catch(IOException e)
{
System.err.println(e.toString());
System.exit(1);
}
return id;
}
//Function to Store current ID in a file
public static void setID(int id)
{
try
{
RandomAccessFile studentIDFile = new
RandomAccessFile(Registration.idFile,"rw");
studentIDFile.seek(0);
studentIDFile.writeInt(id);
studentIDFile.close();
}
catch(IOException e)
{
System.err.println(e.toString());
System.exit(1);
}
}
}
Program to implement Gregorian Calendar
import java.util.*;
class calendar1
{
public static void main(String arg[])
{
GregorianCalendar c1 = new GregorianCalendar();
int month = Integer.parseInt(arg[0]);
int year = Integer.parseInt(arg[1]);
month = month-1;
c1.set(year,month,1);
int day = c1.get(Calendar.DAY_OF_WEEK);
System.out.println(day);
int numdays = 0;
switch(c1.get(Calendar.MONTH))
{
case 0:
case 2:
case 4:
case 6:
case 7:
case 9:
case 11:
numdays = 31;
break;
case 1:
if(c1.isLeapYear(c1.get(Calendar.YEAR)))
numdays = 29;
else
numdays = 28;
break;
case 3:
case 5:
case 8:
case 10:
numdays = 30;
break;
default:
System.out.println("ERROR IN MONTH SPECIFICATION");
break;
}
display(day,numdays);
}
static void display(int sday , int tday)
{
int k = 0;
System.out.println(" SUN MON TUE WED THU FRI SAT
");
for(int j = 1;j <= sday-1; j++)
{
System.out.print(" ");
k++;
}
for(int i = 1;i <= tday;i++)
{
if(i < 10)
System.out.print(" "+"0"+i+" ");
else
System.out.print(" "+i+" ");
k++;
if ( k == 7)
{
System.out.println();
k = 0;
}
}
}
}
Program to create GUI for Bank Account Simulation
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class GuiAccTest extends Frame implements ActionListener
{
Label lab=new Label(" ");
Label lab1=new Label(" ");
TextField t[]=new TextField [4];
Label l[]=new Label [4];
Button but=new Button("Create Account");
Button but1=new Button("Test Account");
BankAccount b;
GuiAccTest()
{
addWindowListener(new NewWindowAdapter());
setLayout(new GridLayout(2,0));
Panel p=new Panel();
Panel p1=new Panel();
but.addActionListener(this);
but1.addActionListener(this);
p.setLayout(new GridLayout(5,2));
p1.add(lab1);
p1.add(lab);
l[0]=new Label("Account Number");
l[1]=new Label("Initial Balance");
l[2]=new Label("Deposit Amount");
l[3]=new Label("Withdraw Amount");
for(int i=0;i<4;i++)
{
t[i]=new TextField(10);
p.add(l[i]);
p.add(t[i]);
}
p.add(but);
p.add(but1);
but1.setVisible(false);
l[2].setVisible(false);
l[3].setVisible(false);
t[2].setVisible(false);
t[3].setVisible(false);
add(p);
add(p1);
}
String testAccount(int d_amt,int w_amt)
{
String msg;
b.deposit(d_amt);
msg="Transaction Succesful";
try
{
b.withdraw(w_amt);
}catch(FundsInsufficientException fe)
{
fe=new FundsInsufficientException(b.amount,w_amt);
msg=String.valueOf(fe);
}
return msg;
}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand();
if(str.equals("Create Account"))
{
b=new BankAccount(Integer.parseInt(t[0].getText()),Integer.parseInt(t[1].getText()));
but1.setVisible(true);
l[2].setVisible(true);
l[3].setVisible(true);
t[2].setVisible(true);
t[3].setVisible(true);
but.setVisible(false);
l[0].setVisible(false);
l[1].setVisible(false);
t[0].setVisible(false);
t[1].setVisible(false);
lab1.setText("Account : "+b.accnum+", Current Balance : "+b.amount);
return;
}
else
{
lab.setText(testAccount(Integer.parseInt(t[2].getText()),Integer.parseInt(t[3].getText())));
lab1.setText("Account : "+b.accnum+", Current Balance : "+b.amount);
}
}
public static void main(String arg[])
{
GuiAccTest at=new GuiAccTest();
at.setTitle("Bank Account Tester");
at.setSize(600,200);
at.setVisible(true);
}
}
class NewWindowAdapter extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
class BankAccount
{
int accnum;
int amount;
BankAccount(int num,int amt)
{
accnum=num;
amount=amt;
}
public void deposit(int amt)
{
amount=amount+amt;
}
public void withdraw(int amt) throws FundsInsufficientException
{
if(amt>amount)
throw new FundsInsufficientException(amount,amt);
else
amount=amount-amt;
}
}
class FundsInsufficientException extends Exception
{
int balance;
int withdraw_amount;
FundsInsufficientException(int bal,int w_amt)
{
balance=bal;
withdraw_amount=w_amt;
}
public String toString()
{
return "Your withdraw amount ("+withdraw_amount+") is less than the balance ("+balance+"). No withdrawal was recorded.";
}
}
Program to check the input characcter for uppercase, lowercase, no. of digits and other characters
import java.io.*;
class InputDiagnosis{
public static void main(String args[]) throws IOException
{
char ch;
int digit=0;
int upper=0;
int lower=0;
int other=0;
BufferedReader inputstream =new BufferedReader(new InputStreamReader(System.in));
System.out.println("
Type some text. When done, press Enter to Quit:");
do{
ch=(char) inputstream.read();
if(Character.isDigit(ch))
digit++;
else if(Character.isUpperCase(ch))
upper++;
else if(Character.isLowerCase(ch))
lower++;
else
other++;
}while(ch !='
');
System.out.println("No Of Digits:" +digit);
System.out.println("No Of Uppercase Characters:" +upper);
System.out.println("No Of Lowercase Characters:" +lower);
System.out.println("No Of Other Characters:" +other);
}
}
Program for counting no. of Chars, Words and Lines in a file
import java.lang.*;
import java.io.*;
import java.util.*;
class WordCount
{
public static void main(String arg[]) throws Exception
{
int char_count=0;
int word_count=0;
int line_count=0;
String s;
StringTokenizer st;
BufferedReader buf=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter filename : ");
s=buf.readLine();
buf=new BufferedReader(new FileReader(s));
while((s=buf.readLine())!=null)
{
line_count++;
st=new StringTokenizer(s," ,;:.");
while(st.hasMoreTokens())
{
word_count++;
s=st.nextToken();
char_count+=s.length();
}
}
System.out.println("Character Count : "+char_count);
System.out.println("Word Count : "+word_count);
System.out.println("Line Count : "+line_count);
buf.close();
}
}
Program for converting numbers in a file to corresponding words
import java.io.*;
import java.lang.*;
class NumToWords
{
public static void main(String a[]) throws IOException
{
String s="";
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter filename : ");
try
{
s=br.readLine();
}catch(Exception e){}
InputStream in=new FileInputStream(s);
MyInputStream mis=new MyInputStream(in);
mis.changeNumbers();
in.close();
mis.close();
}
}
class MyInputStream extends FilterInputStream
{
InputStream is;
MyInputStream(InputStream in)
{
super(in);
is=in;
}
public void changeNumbers() throws IOException
{
PushbackInputStream pis;
String num="";
char ch;
int c;
pis=new PushbackInputStream(is);
while((c=pis.read())!=-1)
{
ch=(char)c;
if('0'<=ch&&ch<='9')
{
num="";
while('0'<=ch&&ch<='9'&&c!=-1)
{
num=num+ch;
c=pis.read();
ch=(char)c;
}
System.out.print(MyInputStream.process(num));
pis.unread(ch);
}
else
System.out.print(ch);
}
}
static String process(String str)
{
String a1[]={"One","Two","Three","Four","Five","Six","Seven","Eight","Nine"};
String a2[]={"Twenty","Thirty","Fourty","Fifty","Sixty","Seventy","Eighty","Ninety"};
String a3[]={"Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};
String a4[]={"Hundered","Thousand","Lakhs","Crores"};
int num=0;
try
{
num=Integer.parseInt(str);
}catch(Exception e){}
if(num==0)
return "Zero";
int n,n1;
String ans="";
String ans1="";
n1=num%10;
num=num/10;
if(n1!=0)
ans=a1[n1-1];
if(num>0)
{
n=num%10;
num=num/10;
if(n==1)
ans=a3[n1];
else if(n!=0)
ans=a2[n-2]+" "+ans;
}
if(num>0)
{
n=num%10;
num=num/10;
if(n!=0)
ans=a1[n-1]+" "+a4[0]+" "+ans;
}
for(int i=1;num>0;i++)
{
n1=num%10;
num=num/10;
if(n1!=0)
ans1=a1[n1-1];
if(num>0)
{
n=num%10;
num=num/10;
if(n==1)
ans1=a3[n1];
else if(n!=0)
ans1=a2[n-2]+" "+ans1;
}
ans=ans1+" "+a4[i]+" "+ans;
ans1="";
}
return(ans);
}
}
Subscribe to:
Comments (Atom)