Friday, 15 July 2011
Wednesday, 13 July 2011
Saturday, 2 July 2011
Notepad
Notepad
import java.awt.*;
import java.awt.event.*;
import java.awt.datatransfer.*;
import java.io.*;
public class Editor extends Frame
{
String filename;
TextArea tx;
Clipboard clip = getToolkit().getSystemClipboard();
Editor()
{
setLayout(new GridLayout(1,1));
tx = new TextArea();
add(tx);
MenuBar mb = new MenuBar();
Menu F = new Menu("file");
MenuItem n = new MenuItem("New");
MenuItem o = new MenuItem("Open");
MenuItem s = new MenuItem("Save");
MenuItem e = new MenuItem("Exit");
n.addActionListener(new New());
F.add(n);
o.addActionListener(new Open());
F.add(o);
s.addActionListener(new Save());
F.add(s);
e.addActionListener(new Exit());
F.add(e);
mb.add(F);
Menu E = new Menu("Edit");
MenuItem cut = new MenuItem("Cut");
MenuItem copy = new MenuItem("Copy");
MenuItem paste = new MenuItem("Paste");
cut.addActionListener(new Cut());
E.add(cut);
copy.addActionListener(new Copy());
E.add(copy);
paste.addActionListener(new Paste());
E.add(paste);
mb.add(E);
setMenuBar(mb);
mylistener mylist = new mylistener();
addWindowListener(mylist);
}
class mylistener extends WindowAdapter
{
public void windowClosing (WindowEvent e)
{
System.exit(0);
}
}
class New implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
tx.setText(" ");
setTitle(filename);
}
}
class Open implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
FileDialog fd = new FileDialog(Editor.this, "select File",FileDialog.LOAD);
fd.show();
if (fd.getFile()!=null)
{
filename = fd.getDirectory() + fd.getFile();
setTitle(filename);
ReadFile();
}
tx.requestFocus();
}
}
class Save implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
FileDialog fd = new FileDialog(Editor.this,"Save File",FileDialog.SAVE);
fd.show();
if (fd.getFile()!=null)
{
filename = fd.getDirectory() + fd.getFile();
setTitle(filename);
try
{
DataOutputStream d = new DataOutputStream(new FileOutputStream(filename));
String line = tx.getText();
BufferedReader br = new BufferedReader(new StringReader(line));
while((line = br.readLine())!=null)
{
d.writeBytes(line + "\r\n");
d.close();
}
}
catch(Exception ex)
{
System.out.println("File not found");
}
tx.requestFocus();
}
}
}
class Exit implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
void ReadFile()
{
BufferedReader d;
StringBuffer sb = new StringBuffer();
try
{
d = new BufferedReader(new FileReader(filename));
String line;
while((line=d.readLine())!=null)
sb.append(line + "\n");
tx.setText(sb.toString());
d.close();
}
catch(FileNotFoundException fe)
{
System.out.println("File not Found");
}
catch(IOException ioe){}
}
class Cut implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String sel = tx.getSelectedText();
StringSelection ss = new StringSelection(sel);
clip.setContents(ss,ss);
tx.replaceRange(" ",tx.getSelectionStart(),tx.getSelectionEnd());
}
}
class Copy implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String sel = tx.getSelectedText();
StringSelection clipString = new StringSelection(sel);
clip.setContents(clipString,clipString);
}
}
class Paste implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
Transferable cliptran = clip.getContents(Editor.this);
try
{
String sel = (String) cliptran.getTransferData(DataFlavor.stringFlavor);
tx.replaceRange(sel,tx.getSelectionStart(),tx.getSelectionEnd());
}
catch(Exception exc)
{
System.out.println("not string flavour");
}
}
}
public static void main(String args[])
{
Frame f = new Editor();
f.setSize(500,400);
f.setVisible(true);
f.show();
}
}
NegativeLength Exception
NegativeLength Exception
import java.io.*;
public class NegativeLengthException extends Exception {
/** Test NegativeLengthException */
public static void main(String[] args) {
try {
int lineLength = readLength();
for(int i=0; i System.out.print("*");
}
System.out.println();
} catch (NegativeLengthException nle) {
System.out.println("NegativeLengthException: " +
nle.getMessage());
}
}
public NegativeLengthException() {
super("Negative dimensions not permitted.");
}
public NegativeLengthException(String message) {
super(message);
}
// readLength catches IOExceptions locally but lets the
// calling method handle NegativeLengthExceptions.
private static int readLength() throws NegativeLengthException {
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
System.out.print("Enter length: ");
System.out.flush();
int len = 0;
try {
String line = in.readLine();
len = Integer.parseInt(line);
if (len < 0) {
throw new NegativeLengthException();
}
} catch (IOException ioe) {
System.out.println("Problem reading from keyboard");
}
return(len);
}
}
Moving a File or Directory to Another Directory
Moving a File or Directory to Another Directory
public static void main(String args[]){
try{
// File (or directory) to be moved
File file = new File("file.txt");
// Destination directory
File dir = new File("gg");
// Move file to new directory
boolean success = file.renameTo(new File(dir, file.getName()));
if (!success) {
System.out.println("File moved");
}
}
catch (Exception ioe){
ioe.printStackTrace();
}
}
Method Overriding
Method Overriding
class A {
String name() { return "A"; }
}
class B extends A {
String name() { return "B"; }
}
class C extends A {
String name() { return "C"; }
}
public class Overriding {
public static void main(String[] args) {
A[] tests = new A[] { new A(), new B(), new C() };
for (int i = 0; i < tests.length; i++)
System.out.print(tests[i].name());
}
}
Method Overloading
Method Overloading
import java.awt.Container;
import javax.swing.*;
public class MethodOverload extends JApplet
{
JTextArea outputArea;
public void init()
{
outputArea = new JTextArea( 2, 20 );
Container c = getContentPane();
c.add( outputArea );
outputArea.setText(
"The square of integer 7 is " + square( 7 ) +
"\nThe square of double 7.5 is " + square( 7.5 ) );
}
public int square( int x )
{
return x * x;
}
public double square( double y )
{
return y * y;
}
}
Making the application wait for some given time
Making the application wait for some given time
import java.util.*;
public class WaitForSomeTime
{
public static void main(String args[])
{
WaitForSomeTime waitForSomeTime = new WaitForSomeTime();
waitForSomeTime.myMethod();
}
public void myMethod()
{
System.out.println("Starting......");
// pause for a while
Thread thisThread = Thread.currentThread();
try
{
thisThread.sleep(10000);
}
catch (Throwable t)
{
throw new OutOfMemoryError("An Error has occured");
}
System.out.println("Ending......");
}
}
Friday, 1 July 2011
Listing the Files or Subdirectories in a Directory
Listing the Files or Subdirectories in a Directory
public static void main(String args[]){
try{
File dir = new File("d:\\temp");
String[] children = dir.list();
if (children == null) {
System.out.println("Directory does not exist or is not a Directory");
} else {
for (int i=0; i // Get filename of file or directory
String filename = children[i];
System.out.println(filename);
}
}
// It is also possible to filter the list of returned files.
// This example does not return any files that start with `.'.
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return !name.startsWith(".");
}
};
children = dir.list(filter);
// The list of files can also be retrieved as File objects
File[] files = dir.listFiles();
// This filter only returns directories
FileFilter fileFilter = new FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
}
};
files = dir.listFiles(fileFilter);
}
catch (Exception ioe){
ioe.printStackTrace();
}
}
Listing the File System Roots
Listing the File System Roots
public static void main(String args[]){
try{
File[] roots = File.listRoots();
for (int i=0; i System.out.println((roots[i]));
}
}
catch (Exception ioe){
ioe.printStackTrace();
}
}
Listing All Available Unicode to Character Set Converters
Listing All Available Unicode to Character Set Converters
public static void main(String args[])
{
Map map = Charset.availableCharsets();
Iterator it = map.keySet().iterator();
while (it.hasNext()) {
// Get charset name
String charsetName = (String)it.next();
System.out.println("Charset Name "+charsetName);
// Get charset
Charset charset = Charset.forName(charsetName);
System.out.println("Charset "+charset);
}
}
List of users in the network
List of users in the network
import java.io.*;
public class NetworkUsers
{
public static void main(java.lang.String[] args)
{
StringBuffer strBuffer= new StringBuffer();
String line= null;
try
{
Process process= Runtime.getRuntime().exec("cmd");
BufferedReader b=
new BufferedReader(new InputStreamReader(process.getInputStream()));
PrintWriter to= new PrintWriter(process.getOutputStream());
to.println("net view");
to.println("exit");
to.close();
try
{
// we need the process to end, else we'll get an
// illegal Thread State Exception
line= b.readLine();
while (line != null)
{
strBuffer.append(line+"
");
line= b.readLine();
}
process.waitFor();
}
catch (InterruptedException inte)
{
System.out.println("InterruptedException Caught");
}
if (process.exitValue() == 0)
{
System.out.println(strBuffer.toString());
}
process.destroy();
}
catch (IOException ioe)
{
System.out.println(
"IO Exception Occured While Messing aruond with Processes! -> " + ioe);
}
}
}
List all '.java' files present in a directory.
List all '.java' files present in a directory.
import java.io.*;
public class FileExt
{
public static void main(String args[])
{
try
{
String[] filesList;
File dir = new File(".");
filesList= dir.list(new FileFilter());
for (int i=0;i {
System.out.println(filesList[i]);
}
}
catch(Exception e){}
}
}
class FileFilter implements FilenameFilter
{
public boolean accept(File dir, String name)
{
return (name.endsWith(".java"));
}
}
Linear Search of an Array
Linear Search of an Array
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class LinearSearch extends JApplet implements ActionListener
{
JLabel enterLabel, resultLabel;
JTextField enter, result;
int a[];
public void init()
{
Container c = getContentPane();
c.setLayout( new FlowLayout() );
enterLabel = new JLabel( "Enter integer search key" );
c.add( enterLabel );
enter = new JTextField( 10 );
enter.addActionListener( this );
c.add( enter );
resultLabel = new JLabel( "Result" );
c.add( resultLabel );
result = new JTextField( 20 );
result.setEditable( false );
c.add( result );
// create array and populate with even integers 0 to 198
a = new int[ 100 ];
for ( int i = 0; i < a.length; i++ )
a[ i ] = 2 * i;
}
// Search "array" for the specified "key" value
public int linearSearch( int array[], int key )
{
for ( int n = 0; n < a.length; n++ )
if ( array[ n ] == key )
return n;
return -1;
}
public void actionPerformed( ActionEvent e )
{
String searchKey = e.getActionCommand();
// Array a is passed to linearSearch even though it
// is an instance variable. Normally an array will
// be passed to a method for searching.
int element = linearSearch( a, Integer.parseInt( searchKey ) );
if ( element != -1 )
result.setText( "Found value in element " + element );
else
result.setText( "Value not found" );
}
}
Java Script Trim() function
Java Script Trim() function
function fnTrim() {
for(var L=0; L if(this.charAt(L)!=" ")break;
for(R=this.length-1; R>=0;R--)
if(this.charAt(R)!=" ")break;
if(L==this.length)return "";
return this.substring(L,R+1);
}
String.prototype.trim=fnTrim;
//**** For trim the crtl
if ((document.frm.crtlName.value).trim()=="") {
//*** Here ur code
}
Information Servlet
Information Servlet
// Import standard networking I/O packages
import java.net.*;
import java.io.*;
// Enumeration from util
import java.util.Enumeration;
// Import servlet packages
import javax.servlet.*;
import javax.servlet.http.*;
//
//
// InfoServlet
//
//
public class InfoServlet extends HttpServlet
{
// Get method of servlet
public void doGet (HttpServletRequest request, HttpServletResponse response) throws IOException
{
// Define content type
response.setContentType("text/html");
// Get information about client and server
String clientBrowser = request.getHeader("User-Agent");
String clientReferer = request.getHeader("Referer");
String clientIP = request.getRemoteAddr();
String serverOS = System.getProperty("os.name");
String serverOSVersion = System.getProperty("os.version");
String serverOSArch = System.getProperty("os.arch");
// Get a servlet output stream for the response
ServletOutputStream sout = response.getOutputStream();
// Print header information
sout.println ("<HTML><HEAD><TITLE>InfoServlet Response</TITLE></HEAD>");
// Print body information
sout.println ("<BODY BGCOLOR='white' COLOR='black'>");
sout.println ("<H2>InfoServlet</H2><HR>");
// Print information about client
sout.println ("<H3>Client :-</H3>");
// Check for presence of user-agent header field
if (clientBrowser != null)
sout.println ("User-Agent : " + clientBrowser + "<BR>");
// Print IP address
sout.println ("IP Address : " + clientIP + "<BR>");
// Check for presence of referer header field
if (clientReferer != null)
sout.println ("Last page : " + clientReferer + "<BR>");
// Print information about server
sout.println ("<H3>Server</H3>");
// Check to see if each property is valid, and if so, output it
if ( (serverOS != null) & (serverOSVersion != null) )
sout.println ("Server O/S : " + serverOS + " v" + serverOSVersion + "<BR>");
if ( serverOSArch != null)
sout.println ("Server CPU : " + serverOSArch + "<BR>");
// Obtain a reference to the server context
ServletContext context = getServletContext();
if (context != null)
{
// Display information about servlets
sout.println ("<h3> Servlet information </h3>");
// Table for servlet info
sout.println ("<table border='1' width=70%>");
sout.println ("<tr><td><b>Servlet Name</b></td></tr>");
for (Enumeration e = context.getServletNames(); e.hasMoreElements();)
{
// Get name of servlet
String name = (String) e.nextElement();
sout.println ("<tr> <td>");
sout.println (name);
sout.println ("</td> </tr>");
}
sout.println ("</table>");
}
else
sout.println ("Could not determine servlet context");
// Write footer information
sout.println ("</BODY></HTML>");
// Flush
sout.flush();
}
// Post method of servlet
public void doPost (HttpServletRequest request, HttpServletResponse response) throws IOException
{
// Perform same action as get method
doGet(request, response);
}
public String getServletInfo()
{
return new String (
"InfoServlet - reports information on client connection and server state"
);
}
}
Histogram printing program
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 );
}
}
Getting and Setting the Modification Time of a File or Directory
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
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
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
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
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
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
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)
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
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 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
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
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
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
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
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();
}
}
Subscribe to:
Posts (Atom)