Vous êtes sur la page 1sur 58

SRIRAM ENGINEERING COLLEGE

Perumalpattu, Tiruvallur Dist-602 024.

DEPARTMENT OF COMPUTER SCIENCE


JAVA LAB

CS2309

NAME

REGNO :

SRIRAM ENGINEERING COLLEGE


Perumalpattu, Tiruvallur Dist-602 024.

DEPARTMENT OF COMPUTER SCIENCE

Register.No:

BONAFIDE CERTIFICATE
NAME OF THE LAB: JAVA LAB

DEPARTMENT: COMPUTER SCIENCE AND ENGINEERING

This is to certify that a bonafide record of work done by _________________________ Of V semester computer science and engineering class in the Java Laboratory during the year 20102011.

Signature of lab in charge

Signature of Head of Dept

Submitted for the practical examination held on __________________

Internal Examiner

External Examiner

S.N O 1 2 3 4. a 4. b 5 6 7 8 9

DATE

NAME OF EXPERIMENT

PAG E

SIGN

10 11 12

PROGRAM: import java.io.*; /** * * @author STUDENT */ public class Rational { private int num; // the numerator private int den; // the denominator // create and initialize a new Rational object /** * * @param numerator * @param denominator */ public Rational(int numerator, int denominator) { String s; if (denominator == 0) { throw new RuntimeException("Denominator is zero"); } int g = gcd(numerator, denominator); num = numerator / g; den = denominator / g; if(den == 1) { System.out.println(""); System.out.print("The rational number is :"+ num + ""); } else { System.out.println(""); System.out.print("The rational number is :"+ num + "/"+den); }

} // return string representation of (this) /** * * @return */ public String toStrings() { if (den == 1) { return num + ""; } else { return num + "/" + den; } } private static int gcd(int n, int d) { if (0 == d) return n; else return gcd(d, n % d); } /** * * @param args * @throws IOException */ public static void main(String[] args) throws IOException { Rational x; int num,den; DataInputStream din = new DataInputStream(new BufferedInputStream(System.in)); System.out.print("Enter the numerator :"); num=Integer.parseInt(din.readLine()); System.out.println(""); System.out.print("Enter the Denominator :"); den=Integer.parseInt(din.readLine()); x = new Rational(num, den); } } OUTPUT: C:\Documents and Settings\Student>d: D:\>cd javas D:\javas>set path=D:\Java\jdk1.6\bin D:\javas>javac Rational.java D:\javas>java Rational

Enter the numerator: 6 Enter the denominator:12 The rational number is : 1/2

JAVA DOCUMENTATION:
Package Class Use Tree Depr ecat ed Index Help

PREV CLASS NEXT CLASS SUMMARY: NESTED | FIELD | CONSTR | METHOD

FRAMES

NO FRAMES

DETAIL: FIELD | CONSTR | METHOD

Class Rational
java.lang.Object Rational public class Rational extends java.lang.Object

Constructor Summary
Rational(int numerator, int denominator)

Method Summary
static void main(java.lang.String[] args)

java.lang.String toStrings()

Methods inherited from class java.lang.Object


clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail
Rational
public Rational(int numerator, int denominator)

Parameters:
numerator

denominator

Method Detail
toStrings
public java.lang.String toStrings()

Returns:

main
public static void main(java.lang.String[] args) throws java.io.IOException

Parameters:
args

Throws:
java.io.IOException

Package Class Use Tree Depr ecat ed Index Help

PREV CLASS NEXT CLASS SUMMARY: NESTED | FIELD | CONSTR | METHOD

FRAMES

NO FRAMES

DETAIL: FIELD | CONSTR | METHOD

Package Class Use Tre Depr e ecate d Index Help

PREV NEXT

FRAMES

NO FRAMES

Class Hierarchy
o

java.lang.Object o Rational

Package Class Use Tre Depr e ecate d Index Help

PREV NEXT

FRAMES

NO FRAMES

RESULT:

PROGRAM: import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; public class DateUtility { /* Add Day/Month/Year to a Date add() is used to add values to a Calendar object. You specify which Calendar field is to be affected by the operation (Calendar.YEAR, Calendar.MONTH, Calendar.DATE). */ public static final String DATE_FORMAT = "dd-MM-yyyy"; public static void addToDate() { System.out.println("1. Add to a Date Operation\n"); SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); Calendar c1 = Calendar.getInstance(); System.out.println("c1.getTime() : " + c1.getTime()); System.out.println("c1.get(Calendar.YEAR): "+ c1.get(Calendar.YEAR)); c1.set(1999, 0, 20); System.out.println("c1.set(1999,0 ,20) : " + c1.getTime()); c1.add(Calendar.DATE, 20); System.out.println("Date + 20 days is : "+ sdf.format(c1.getTime())); System.out.println(); System.out.println("-------------------------------------"); } /*Substract Day/Month/Year to a Date roll() is used to substract values to a Calendar object. You specify which Calendar field is to be affected by the operation (Calendar.YEAR, Calendar.MONTH, Calendar.DATE). Note: To substract, simply use a negative argument.

roll() does the same thing except you specify if you want to roll up (add 1) or roll down (substract 1) to the specified Calendar field. The operation only affects the specified field while add() adjusts other Calendar fields. See the following example, roll() makes january rolls to december in the same year while add() substract the YEAR field for the correct result. Hence add() is preferred even for subtraction by using a negative element. */ public static void subToDate() { System.out.println("2. Subtract to a date Operation\n"); SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); Calendar c1 = Calendar.getInstance(); c1.set(1999, 0, 20); System.out.println("Date is : " + sdf.format(c1.getTime())); c1.roll(Calendar.MONTH, false); System.out.println("Date roll down 1 month : "+ sdf.format(c1.getTime())); c1.set(1999, 0, 20); System.out.println("Date is : " + sdf.format(c1.getTime())); c1.add(Calendar.MONTH, -1); System.out.println("Date minus 1 month : "+ sdf.format(c1.getTime())); System.out.println(); System.out.println("-------------------------------------"); } public static void daysBetween2Dates() { System.out.println("3. No of Days between 2 dates\n"); Calendar c1 = Calendar.getInstance(); //new GregorianCalendar(); Calendar c2 = Calendar.getInstance(); //new GregorianCalendar(); c1.set(1999, 0, 20); c2.set(1999, 0, 22); System.out.println("Days Between " + c1.getTime() + " and " + c2.getTime() + " is"); System.out.println((c2.getTime().getTime() - c1.getTime() .getTime()) / (24 * 3600 * 1000)); System.out.println(); System.out.println("-------------------------------------"); } public static void daysInMonth() {

System.out.println("4. No of Days in a month for a given date\n"); Calendar c1 = Calendar.getInstance(); c1.set(1999, 6, 20); int year = c1.get(Calendar.YEAR); int month = c1.get(Calendar.MONTH); int[] daysInMonths = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30,31 }; daysInMonths[1] += DateUtility.isLeapYear(year) ? 1 : 0; System.out.println("Days in " + month + "th month for year " + year + " is " + daysInMonths[c1.get(Calendar.MONTH)]); System.out.println(); System.out.println("-------------------------------------"); } public static void compare2Dates() { System.out.println("5. Comparision of 2 dates\n"); SimpleDateFormat fm = new SimpleDateFormat("dd-MM-yyyy"); Calendar c1 = Calendar.getInstance(); Calendar c2 = Calendar.getInstance(); c1.set(2000, 02, 15); c2.set(2001, 02, 15); System.out.print(fm.format(c1.getTime()) + " is "); if (c1.before(c2)) { System.out.println("less than " + fm.format(c2.getTime())); } else if (c1.after(c2)) { System.out.println("greater than " + fm.format(c2.getTime())); } else if (c1.equals(c2)) { System.out.println("is equal to " + fm.format(c2.getTime())); } System.out.println(); System.out.println("-------------------------------------"); } //Utility Method to find whether an Year is a Leap year or Not public static boolean isLeapYear(int year) { if ((year % 100 != 0) || (year % 400 == 0)) { return true; } return false;

} public static void main(String args[]) { addToDate(); //Add day, month or year to a date field. subToDate(); //Subtract day, month or year to a date field. daysBetween2Dates(); //The "right" way would be to compute the Julian day number of //both dates and then do the subtraction. daysInMonth();//Find the number of days in a month for a date compare2Dates(); //Compare 2 dates } } OUTPUT: C:\Documents and Settings\Student>d: D:\>cd javas D:\javas>set path=D:\Java\jdk1.6\bin D:\javas>javac DateUtility.java D:\javas>java DateUtility 1. Add to a Date Operation c1.getTime() : Fri Apr 09 21:22:38 IST 2011 c1.get(Calendar.YEAR): 2011 c1.set(1999,0 ,20) : Wed Jan 20 21:22:38 IST 1999 Date + 20 days is : 09-02-1999 ------------------------------------2. Subtract to a date Operation Date is : 20-01-1999 Date roll down 1 month : 20-12-1999 Date is : 20-01-1999 Date minus 1 month : 20-12-1998 ------------------------------------3. No of Days between 2 dates Days Between Wed Jan 20 21:22:38 IST 1999 and Fri Jan 22 21:22:38 IST 1999 is 2 -------------------------------------

4. No of Days in a month for a given date Days in 6th month for year 1999 is 31 ------------------------------------5. Comparision of 2 dates 15-03-2000 is less than 15-03-2001 ------------------------------------JAVA DOCUMENTATION Package Class

Tre Depr Index Help e ecate d PREV CLASS NEXT CLASS FRAMES NO FRAMES SUMMARY: NESTED | FIELD | CONSTR | METHO DETAIL: FIELD | CONSTR | METHO D D Class DateUtility java.lang.Object DateUtility public class DateUtility extends java.lang.Object Field Summary static java.lang.String DATE_FORMAT

Use

Constructor Summary DateUtility()

Method Summary static void addToDate() static void compare2Dates() static void daysBetween2Dates()

static void daysInMonth() static void getDayofTheDate() static boolean isLeapYear(int year) static void main(java.lang.String[] args) static void subToDate() static void validateAGivenDate()

Methods inherited from class java.lang.Object clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait Field Detail DATE_FORMAT public static final java.lang.String DATE_FORMAT See Also: Constant Field Values Constructor Detail DateUtility public DateUtility() Method Detail addToDate public static void addToDate() subToDate public static void subToDate()

daysBetween2Dates public static void daysBetween2Dates() daysInMonth public static void daysInMonth() validateAGivenDate public static void validateAGivenDate() compare2Dates public static void compare2Dates() getDayofTheDate public static void getDayofTheDate() isLeapYear public static boolean isLeapYear(int year) main public static void main(java.lang.String[] args)

RESULT:

PROGRAM package lists; // Declarations for a typical list-node class public class ListNode {

protected Object data; // the information to be stored in the node protected ListNode next; // the pointer to the next list-node // Constructors public ListNode (Object startingData) { data = startingData; next = null; } public ListNode (Object startingData, ListNode nextNode) { data = startingData; next = nextNode; } // extractors public Object getData () { return data; } public ListNode getNext () { return next; } // modifiers public void setData (Object newData) { data = newData; } public void setNext (ListNode newNext) { next = newNext; } } // ListNode // Definition of a Scheme-like list class import lists.ListNode; import java.lang.NullPointerException;

import java.io.PrintWriter; public class ListLikeScheme { protected ListNode first; // Constructor public ListLikeScheme () { first = null; } // observers public boolean isNull() { return first == null; } public int length () { // an iterative method to find the length of a list int i = 0; ListNode ptr = first; while (ptr != null) { i++; ptr = ptr.getNext(); } return i; } public String toString() { String temp; if (first == null) temp = "nil"; else { temp = "(" + first.getData(); for (ListNode ptr=first.getNext(); ptr!=null; ptr=ptr.getNext()) temp = temp + " " + ptr.getData(); temp = temp + ")"; } return temp; } public int size ()

{ // a recursive method to find the length of a list // recursive algorithm uses a husk-and-kernel approach return sizeKernel (first, 0); } private int sizeKernel (ListNode ptr, int count) { // a private, recursive method for finding the length of a list if (ptr == null) return count; else return sizeKernel (ptr.getNext(), (count + 1)); } // extractors public Object car () { if (isNull()) throw new NullPointerException("car applied to null list"); else return first.getData(); } public ListLikeScheme cdr () { if (isNull()) throw new NullPointerException("cdr applied to null list"); else { ListLikeScheme temp = new ListLikeScheme (); temp.first = first.getNext(); return temp; } } // modifiers public void cons (Object newData, ListLikeScheme rest) { // a first approach, reusing previous nodes first = new ListNode (newData, rest.first); } public static void main (String argv[]) { // testing method for list class

PrintWriter out = new PrintWriter(System.out, true); // construct the list (nodeA nodeB nodeC) in four steps ListLikeScheme A = new ListLikeScheme(); ListLikeScheme B = new ListLikeScheme(); ListLikeScheme C = new ListLikeScheme(); ListLikeScheme D = new ListLikeScheme(); C.cons ("nodeC", D); B.cons ("nodeB", C); A.cons ("nodeA", B); // check lists and operations try { out.println ("List A: " + A); out.println (" length/size: " + A.length() + "\t" + A.size()); out.println (" null?: " + A.isNull()); out.println (" car: " + A.car()); out.println (" cdr: " + A.cdr()); out.println ("List B: " + B); out.println (" length/size: " + B.length() + "\t" + B.size()); out.println (" null?: " + B.isNull()); out.println (" car: " + B.car()); out.println (" cdr: " + B.cdr()); out.println ("List C: " + C); out.println (" length/size: " + C.length() + "\t" + C.size()); out.println (" null?: " + C.isNull()); out.println (" car: " + C.car()); out.println (" cdr: " + C.cdr()); out.println ("List D: " + D); out.println (" length/size: " + D.length() + "\t" + D.size()); out.println (" null?: " + D.isNull()); out.println (" car: " + D.car()); out.println (" cdr: " + D.cdr()); } catch (NullPointerException e) { out.println (e);

} try { out.println (" cdr: " + D.cdr()); } catch (NullPointerException e) { out.println (e); } } } OUTPUT: C:\Documents and Settings\Student>d: D:\>cd javas D:\javas>set path=D:\Java\jdk1.6\bin D:\javas>cd lists D:\javas\lists>javac ListNode.java D:\javas\lists>cd.. D:\javas>javac ListLikeScheme.java D:\javas>java ListLikeScheme List A: (nodeA nodeB nodeC) length/size: 3 3 null?: false car: nodeA cdr: (nodeB nodeC) List B: (nodeB nodeC) length/size: 2 2 null?: false car: nodeB cdr: (nodeC) List C: (nodeC) length/size: 1 1 null?: false car: nodeC cdr: nil List D: nil length/size: 0 0 null?: true

RESULT:

PROGRAM import java.io.*; import java.util.LinkedList; class pArrayStackIntTest { public static void main(String[] args) { pArrayStackInt s = new pArrayStackInt(10); int i,j; System.out.println("starting..."); for(i=0;i<10;i++) {

j = (int)(Math.random() * 100); s.push(j); System.out.println("push: " + j); } System.out.println(\n\nTop most element in stack:+s.top()); System.out.println(pop: +s.pop()); System.out.println(pop: +s.pop()); System.out.println(pop: +s.pop()); System.out.println(Top most element after deleting 3 elements:+s.top()); while(!s.isEmpty()) { System.out.println("pop: " + s.pop()); } System.out.println("Done ;-)"); StackL stack = new StackL(); for (i = 0; i < 10; i++) { stack.push(new Integer(i)); } for (i = 0; i < 10; i++) { System.out.println("element from top "+i+":"+stack.list.get(i)); } System.out.println("Push :"+stack.top()); System.out.println("Pop : "+stack.pop()); System.out.println("PoP :"+stack.pop()); System.out.println("Pop :"+stack.pop()); System.out.println("Push :"+stack.top()); } } interface Stackop { public void push(Object x); public Object pop(); public Object top(); } //class for Array Implementation class pArrayStackInt implements Stackop { protected Object head[]; protected int pointer;

public pArrayStackInt(int capacity) { head = new Object[capacity]; pointer = -1; } public boolean isEmpty() { return pointer == -1; } public void push(Object i) { if(pointer+1 < head.length) head[++pointer] = i; } public Object pop() { if(isEmpty()) return 0; return head[pointer--]; } public Object top() { return head[pointer--]; } } //class for linked list implementation public class StackL implements Stackop { LinkedList list = new LinkedList(); public void push(Object v) { list.addFirst(v); } public Object top() { return list.getFirst(); } public Object pop() { return list.removeFirst();

} } OUTPUT: C:\Documents and Settings\Student>d: D:\>cd javas D:\javas>set path=D:\Java\jdk1.6\bin D:\javas>javac pArrayStackIntTest.java D:\javas>java pArrayStackIntTest starting... push: 96 push: 49 push: 10 push: 50 push: 0 push: 98 push: 46 push: 60 push: 24 push: 2

Top most element in Stack: 2 pop: 2 pop: 24 pop: 60 Top most element after deleting 3: 46 pop: 46 pop: 98 pop: 0 pop: 50 pop: 10 pop: 49 pop: 96 Done ;-)

element from top 0:9 element from top 1:8 element from top 2:7

element from top 3:6 element from top 4:5 element from top 5:4 element from top 6:3 element from top 7:2 element from top 8:1 element from top 9:0 push: 9 pop: 9 pop: 8 pop: 7 push: 6

RESULT:

PROGRAM //Vehicle.java //This is the class that will be inherited class Vehicle { public int doors; public int seats; public int wheels; Vehicle() { wheels=4; doors=4; seats=4; } }

//Car.java //This class inherits Vehicle.java class Car extends Vehicle { public String toString() { return "This car has "+seats+" Seats, "+doors+" Doors "+ "and "+wheels+" wheels."; } } //MotorCycle.java //This class inherits Vehicle.java class MotorCycle extends Vehicle { MotorCycle() { wheels=2; doors=0; seats=1; } void setSeats(int num) { seats=num; } public String toString() { return "This motorcycle has "+seats+" Seats, "+doors+" Doors "+ "and "+wheels+" wheels."; } } //Truck.java //This class inherits Vehicle.java class Truck extends Vehicle { boolean isPickup; Truck() { isPickup=true; } Truck(boolean aPickup) { this(); isPickup=aPickup; }

Truck(int doors, int seats, int inWheels, boolean isPickup) { this.doors=doors; this.seats=seats; wheels=inWheels; this.isPickup=isPickup; } public String toString() { return "This "+(isPickup?"pickup":"truck")+ " has "+seats+" Seats, "+doors+" Doors "+"and "+wheels+" wheels."; } } //VehiclesTest.java //This class tests the classes that inherit Vehicle.java public class VehiclesTest { public static void main(String args[]) { MotorCycle mine = new MotorCycle(); System.out.println(mine); Car mine1 = new Car(); System.out.println(mine1); Car mine2 = new Car(); mine2.doors=2; System.out.println(mine2); Truck mine3 = new Truck(); System.out.println(mine3); Truck mine4 = new Truck(false); mine4.doors=2; System.out.println(mine4); } } OUTPUT: C:\Documents and Settings\Student>d: D:\>cd javas D:\javas>set path=D:\Java\jdk1.6\bin D:\javas>javac Vehicle.java D:\javas>javac Car.java D:\javas>javac MotorCycle.java D:\javas>javac Truck.java D:\javas>javac VehiclesTest.java

D:\javas>java VehiclesTest This motorcycle has 1 Seats, 0 Doors and 2 wheels. This car has 4 Seats, 4 Doors and 4 wheels. This car has 4 Seats, 2 Doors and 4 wheels. This pickup has 4 Seats, 4 Doors and 4 wheels. This truck has 4 Seats, 2 Doors and 4 wheels.

RESULT:

PROGRAM import java.io.*; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Random; class Rupee implements java.io.Serializable { float r; public Rupee(float rupee) { r=rupee; } public String toString()

{ return ""+r; } } class Dollar implements java.io.Serializable { float d; public Dollar(float dollar) { d=dollar; } public String toString() { return ""+d; } } class DollarRupeeDemo { public static void main(String a[]) throws Exception { Object obj; int prob; FileOutputStream fileOut=null; ObjectOutputStream out=null; Random rand=new Random(); fileOut = new FileOutputStream("DollarRupee.ser"); out = new ObjectOutputStream(fileOut); DataInputStream din=new DataInputStream(new BufferedInputStream(System.in)); for(int i=0;i<10;i++) { prob=(int)(100*rand.nextDouble()); if(prob<50) { System.out.println(Enter the value of rupee:); obj=new Rupee(Integer.parseInt(din.realLine()); } else { System.out.println(Enter the value of dollar:); obj=new Dollar((Integer.parseInt(din.realLine()); } out.writeObject(prob); out.writeObject(obj); }

out.close(); fileOut.close(); } } import java.io.FileInputStream; import java.io.ObjectInputStream; import java.io.*; class DollarRupeeDemo1 { public static void main(String[] args) throws Exception { Dollar dollar = null; Rupee rupee=null; FileInputStream fileIn = new FileInputStream("DollarRupee.ser"); ObjectInputStream in = new ObjectInputStream(fileIn); System.out.println(Prob\t\tValue); for(int i=0;i<10;i++) { Object Str=in.readObject(); System.out.println(Str); Object obj = in.readObject(); if(obj instanceof Rupee) System.out.println((Rupee)obj); else { dollar=(Dollar)obj; System.out.println(dollar.d*45); } } in.close(); fileIn.close(); } }

OUTPUT: C:\Documents and Settings\Student>d: D:\>cd javas D:\javas>set path=D:\Java\jdk1.6\bin

D:\javas>javac DollarRupeeDemo.java D:\javas>java DollarRupeeDemo Enter the value of rupee: 45 Enter the value of rupee: 52 Enter the value of dollar: 3 Enter the value of rupee: 65 Enter the value of dollar: 2 Enter the value of dollar: 1 Enter the value of rupee: 78 Enter the value of dollar: 2 Enter the value of dollar: 3 Enter the value of rupee: 89 D:\javas>javac DollarRupeeDemo1.java D:\javas>java DollarRupeeDemo1 Prob Value 45 45 31 52 56 135 29 65 67 90 72 45 21 78 77 90 86 135 39 89 RESULT: PROGRAM: import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Calculator { public static void main(String arg[]) { CalculatorFrame frame=new CalculatorFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } } class CalculatorFrame extends JFrame

{ public CalculatorFrame() { setTitle(" CALCULATOR"); CalculatorPanel panel=new CalculatorPanel(); add(panel); } } class CalculatorPanel extends JPanel { public CalculatorPanel() { setLayout(new BorderLayout()); result=0; lastCommand = "="; start = true; display = new JButton( "0"); display.setEnabled(false); add(display,BorderLayout.NORTH); ActionListener insert= new InsertAction(); ActionListener command=new CommandAction(); panel=new JPanel(); panel.setLayout(new GridLayout(4,4)); addButton("7",insert); addButton("8",insert); addButton("9",insert); addButton("/",command); addButton("4",insert); addButton("5",insert); addButton("6",insert); addButton("*",command); addButton("1",insert); addButton("2",insert); addButton("3",insert); addButton("-",command); addButton("0",insert); addButton(".",insert); addButton("=",command); addButton("+",command); addButton("tan",command); addButton("sin",command); addButton("cos",command);

addButton("sqrt",command); addButton("x^3",command); addButton("x^2",command); addButton("clr",command); add(panel,BorderLayout.CENTER); } private void addButton(String label,ActionListener listener) { JButton button=new JButton(label); button.addActionListener(listener); panel.add(button); } private class InsertAction implements ActionListener { public void actionPerformed(ActionEvent event) { String input=event.getActionCommand(); if(start) { display.setText(""); start=false; } display.setText(display.getText()+input); } } private class CommandAction implements ActionListener { public void actionPerformed(ActionEvent event) { String command=event.getActionCommand(); if(start) { if(command.equals("-")) { display.setText (command); start=false; } else if(command.equals("clr")) { display.setText ("0.0"); //start=false; } else lastCommand=command;

} else { if(command.equals("clr")) { display.setText ("0.0"); start=true; } else { Calculate(Double.parseDouble(display.getText())); lastCommand=command; start=true; } } } } public void Calculate(double x) { if(lastCommand.equals("+"))result +=x; else if(lastCommand.equals("-")) result -=x; else if(lastCommand.equals("*")) result *=x; else if(lastCommand.equals("/")) result /=x; else if(lastCommand.equals("=")) result =x; else if(lastCommand.equals("sin")) result =Math.sin(Math.PI*x/180); else if(lastCommand.equals("tan")) result =Math.tan(Math.PI*x/180); else if(lastCommand.equals("cos")) result =Math.cos(Math.PI*x/180); else if(lastCommand.equals("sqrt")) result =Math.sqrt(x); else if(lastCommand.equals("x^3")) result=Math.pow(x,3); else if(lastCommand.equals("x^2")) result=Math.pow(x,2); else if(lastCommand.equals("clr")) result=0.0; display.setText(" " + result); } private JButton display; private JPanel panel; private double result; private String lastCommand; private boolean start; }

OUTPUT: C:\Documents and Settings\Student>d: D:\>cd javas D:\javas>set path=D:\Java\jdk1.6\bin D:\javas>javac Calculator.java D:\javas>java Calculator

RESULT:

PROGRAM: import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream;

import java.io.PipedInputStream; import java.io.PipedOutputStream; public class PipeDemo { public static void writeData1(OutputStream os1) { try { int a,c=0;; DataOutputStream out1 = new DataOutputStream(new BufferedOutputStream(os1)); for(int i=0;i<1000;i++) { c=0; for(int j=1;j<=i;j++) { a=i%j; if(a==0) { c=c+1; } } if (c==2) { out1.writeInt(i); } } out1.flush(); out1.close(); } catch (IOException e) { e.printStackTrace(); } } public static void writeData2(OutputStream os2) { try { int a=0,b=1,c=0;; DataOutputStream out2 = new DataOutputStream(new BufferedOutputStream(os2)); out2.writeInt(a); out2.writeInt(b); for(int i=0;i<24;i++) { c=a+b; out2.writeInt(c); a=b; b=c; } out2.flush(); out2.close();

} catch (IOException e) { e.printStackTrace(); } } public static void readData(InputStream is1,InputStream is2) { try { DataInputStream in1 = new DataInputStream(new BufferedInputStream(is1)); DataInputStream in2 = new DataInputStream(new BufferedInputStream(is2)); int prm=in1.readInt(); int fib=in2.readInt(); System.out.println("The numbers common between Fibonacci and prime series:"); while((fib!=-1) && (prm!=-1)) { while(prm<=fib) { if(prm==fib) System.out.println(prm); prm=in1.readInt(); } fib=in2.readInt(); } } catch (IOException e) { } System.out.println("End of Data"); } public static void main(String[] args) throws Exception { final PipedOutputStream pos1 = new PipedOutputStream(); final PipedOutputStream pos2 = new PipedOutputStream(); final PipedInputStream pis1 = new PipedInputStream(pos1); final PipedInputStream pis2 = new PipedInputStream(pos2); Runnable runOutput1 = new Runnable() { public void run() { writeData1(pos1); } }; Runnable runOutput2 = new Runnable() { public void run() { writeData2(pos2); } }; Thread outThread1 = new Thread(runOutput1, "outThread1"); outThread1.start(); Thread outThread2 = new Thread(runOutput2, "outThread2"); outThread2.start(); Runnable runInput = new Runnable() { public void run() {

readData(pis1,pis2); } }; Thread inThread = new Thread(runInput, "inThread"); inThread.start(); } }

OUTPUT: C:\Documents and Settings\Student>d: D:\>cd javas D:\javas>set path=D:\Java\jdk1.6\bin D:\javas>javac PipeDemo.java D:\javas>java PipeDemo The numbers common between Fibonacci and prime series: 2 3 5 13 89 233 1597 End of Data

RESULT:

PROGRAM: import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement;

import java.util.logging.Level; import java.util.logging.Logger; import java.applet.*; import java.awt.*; import java.awt.event.*; /** * * @author STUDENT */ public class NewApplet extends Applet { public void init() { try { java.awt.EventQueue.invokeAndWait(new Runnable() { public void run() { initComponents(); } }); } catch (Exception ex) { ex.printStackTrace(); } } private void display() { panel2.setVisible(true); TextArea ta=new TextArea(); panel2.add(ta); panel1.setVisible(true); try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection("Jdbc:Odbc:Lib","sa","sa"); Statement st = con.createStatement(); String qry="select * from Book";// where User ='"+name.getText()+"' and Pass ='" +pass.getText()+"'"; ResultSet rs = st.executeQuery(qry); if(rs.next())

{ ta.append("ISBN Number: "); ta.setText(rs.getString(1)); ta.append("\n"); ta.append("Book Name: "); ta.append(rs.getString(2)); ta.append("\n"); ta.append("Author: "); ta.append(rs.getString(3)); ta.append("\n"); ta.append("Publisher: "); ta.append(rs.getString(4)); ta.append("\n"); ta.append("Description: "); ta.append(rs.getString(5)); } else { error(); pass.setText(""); } } catch(Exception e) { System.out.println(e); } repaint(); } private void error() { User2=new Label("Sorry Username or Password incorrect"); panel3.add(User2); panel3.setVisible(true); } private void initComponents() { panel1 = new Panel(); panel2 = new Panel(); panel3 = new Panel(); User=new Label("Username"); Passwd=new Label("Password"); Ok_btn = new Button(); cancel_btn = new Button(); pass = new TextField(); name = new TextField();

Ok_btn.setLabel("Ok"); Ok_btn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { Ok_btnActionPerformed(evt); } }); cancel_btn.setLabel("Cancel"); pass.setEchoChar('*'); add(panel1); add(panel2); add(panel3); User.setSize(200,200); pass.setSize(200,200); panel1.setLayout(new GridLayout(3,2)); panel1.add(User); panel1.add(name); panel1.add(Passwd); panel1.add(pass); panel1.add(Ok_btn); panel1.add(cancel_btn); panel1.setVisible(true); panel2.setVisible(false); panel3.setVisible(false); } private void Ok_btnActionPerformed(ActionEvent evt) { ResultSet rs=null; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection("Jdbc:Odbc:Lib","sa","sa"); Statement st = con.createStatement(); String qry="select User,Pass from Login where User ='"+name.getText()+"' and Pass ='" +pass.getText()+"'"; rs = st.executeQuery(qry); } catch(Exception e) { System.out.println(e); } try { if (rs.next()) { display(); } else {

error(); pass.setText(""); } } catch (SQLException ex) { Logger.getLogger(NewApplet.class.getName()).log(Level.SEVERE, null, ex); } } private Button Ok_btn; private Button cancel_btn; private Label Passwd; private Label User; private Label User1; private Label User2; private TextField name; private Panel panel1; private Panel panel2; private Panel panel3; private TextField pass; } TABLE VIEW: LOGIN TABLE:

BOOK DETAILS TABLE:

OUTPUT: C:\Documents and Settings\Student>d: D:\>cd javas D:\javas>set path=D:\Java\jdk1.6\bin D:\javas>javac NewApplet.java

D:\javas>Appletviewer NewApplet.java

RESULT:

PROGRAM: SERVER PROGRAM import java.io.*; import java.net.*; public class MultiThreadChatServer{ static Socket clientSocket = null; static ServerSocket serverSocket = null; static clientThread t[] = new clientThread[10]; public static void main(String args[]) { int port_number=2222;

if (args.length < 1) { System.out.println("Usage: java MultiThreadChatServer \n"+ "Now using port number="+port_number); } else { port_number=Integer.valueOf(args[0]).intValue(); } try { serverSocket = new ServerSocket(port_number); } catch (IOException e) {System.out.println(e);} while(true){ try { clientSocket = serverSocket.accept(); for(int i=0; i<=9; i++){ if(t[i]==null) { (t[i] = new clientThread(clientSocket,t)).start(); break; } } } catch (IOException e) { System.out.println(e);} } } } class clientThread extends Thread{ DataInputStream is = null; PrintStream os = null; Socket clientSocket = null; clientThread t[]; public clientThread(Socket clientSocket, clientThread[] t){ this.clientSocket=clientSocket; this.t=t; } public void run() { String line; String name; try{ is = new DataInputStream(clientSocket.getInputStream()); os = new PrintStream(clientSocket.getOutputStream()); os.println("Enter your name.");

name = is.readLine(); os.println("Hello "+name+" to our chat room.\nTo leave enter /quit in a new line"); for(int i=0; i<=9; i++) if (t[i]!=null && t[i]!=this) t[i].os.println("*** A new user "+name+" entered the chat room !!! ***" ); while (true) { line = is.readLine(); if(line.startsWith("BYE")) break; for(int i=0; i<=9; i++) if (t[i]!=null) t[i].os.println("<"+name+"> "+line); } for(int i=0; i<=9; i++) if (t[i]!=null && t[i]!=this) t[i].os.println("*** The user "+name+" is leaving the chat room !!! ***" ); os.println("*** Bye ***"); for(int i=0; i<=9; i++) if (t[i]==this) t[i]=null; is.close(); os.close(); clientSocket.close(); } catch(IOException e){}; } } GUI CLIENT PROGRAM: import java.io.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.net.*; public class TCPChat implements Runnable { public final static int NULL = 0; public final static int DISCONNECTED = 1; public final static int BEGIN_CONNECT = 2; public final static int CONNECTED = 3; public final static String statusMessages[] = { " Error! Could not connect!", " Disconnected", " Connecting...", " Connected" }; public final static TCPChat tcpObj = new TCPChat(); public static String hostIP = "localhost"; public static int port = 2222;

public static int connectionStatus = BEGIN_CONNECT; public static String statusString = statusMessages[connectionStatus]; public static StringBuffer toAppend = new StringBuffer(""); public static StringBuffer toSend = new StringBuffer(""); public static JFrame mainFrame = null; public static JTextArea chatText = null; public static JTextField chatLine = null; public static JPanel statusBar = null; public static JLabel statusField = null; public static JTextField statusColor = null; public static ServerSocket hostServer = null; public static Socket socket = null; public static BufferedReader in = null; public static PrintWriter out = null; private static void initGUI() { statusField = new JLabel(); statusField.setText(statusMessages[DISCONNECTED]); statusColor = new JTextField(1); statusColor.setBackground(Color.red); statusColor.setEditable(false); statusBar = new JPanel(new BorderLayout()); statusBar.add(statusColor, BorderLayout.WEST); statusBar.add(statusField, BorderLayout.CENTER); JPanel chatPane = new JPanel(new BorderLayout()); chatText = new JTextArea(10, 20); chatText.setLineWrap(true); chatText.setEditable(false); chatText.setForeground(Color.blue); JScrollPane chatTextPane = new JScrollPane(chatText, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); chatLine = new JTextField(); chatLine.setEnabled(false); chatLine.addActionListener(new ActionAdapter() { public void actionPerformed(ActionEvent e) { String s = chatLine.getText(); if (!s.equals("")) { appendToChatBox("OUTGOING: " + s + "\n"); chatLine.selectAll();//IF WANT TO CLEAR DO HERE // Send the string sendString(s); }

} }); chatPane.add(chatLine, BorderLayout.SOUTH); chatPane.add(chatTextPane, BorderLayout.CENTER); chatPane.setPreferredSize(new Dimension(200, 200)); JPanel mainPane = new JPanel(new BorderLayout()); mainPane.add(statusBar, BorderLayout.SOUTH); mainPane.add(chatPane, BorderLayout.CENTER); mainFrame = new JFrame("GUI CHAT CLIENT"); mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainFrame.setContentPane(mainPane); mainFrame.setSize(mainFrame.getPreferredSize()); mainFrame.pack(); mainFrame.setVisible(true); } private static void changeStatusTS(int newConnectStatus, boolean noError) { if (newConnectStatus != NULL) { connectionStatus = newConnectStatus; } if (noError) { statusString = statusMessages[connectionStatus]; } else { statusString = statusMessages[NULL]; } SwingUtilities.invokeLater(tcpObj); } private static void appendToChatBox(String s) { synchronized (toAppend) { toAppend.append(s); } } private static void sendString(String s) { synchronized (toSend) { toSend.append(s + "\n"); } } private static void cleanUp() { try { if (hostServer != null) { hostServer.close(); hostServer = null; } } catch (IOException e) {

hostServer = null; } try { if (socket != null) { socket.close(); socket = null; } } catch (IOException e) { socket = null; } try { if (in != null) { in.close(); in = null; } } catch (IOException e) { in = null; } if (out != null) { out.close(); out = null; } } public void run() { switch (connectionStatus) { case CONNECTED: chatLine.setEnabled(true); statusColor.setBackground(Color.GREEN); break; case BEGIN_CONNECT: chatLine.setEnabled(false); chatLine.grabFocus(); statusColor.setBackground(Color.ORANGE); break; case DISCONNECTED: chatLine.setEnabled(false); statusColor.setBackground(Color.RED); break; } statusField.setText(statusString); chatText.append(toAppend.toString()); toAppend.setLength(0); mainFrame.repaint(); }

public static void main(String args[]) { String s; initGUI(); while (true) { try { // Poll every ~10 ms Thread.sleep(10); } catch (InterruptedException e) { } switch (connectionStatus) { case BEGIN_CONNECT: try { socket = new Socket(hostIP, port); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(socket.getOutputStream(), true); changeStatusTS(CONNECTED, true); } catch (IOException e) { cleanUp(); changeStatusTS(DISCONNECTED, false); } break; case CONNECTED: try { if (toSend.length() != 0) { out.print(toSend); out.flush(); toSend.setLength(0); changeStatusTS(NULL, true); } if (in.ready()) { s = in.readLine(); if ((s != null) && (s.length() != 0)) { if (s.equals("*** Bye ***")) { changeStatusTS(DISCONNECTED, true); } else { appendToChatBox("INCOMING: " + s + "\n"); changeStatusTS(NULL, true); } } } } catch (IOException e) { cleanUp(); changeStatusTS(DISCONNECTED, false); } break; default: break; // do nothing }

} } } class ActionAdapter implements ActionListener { public void actionPerformed(ActionEvent e) { } } OUTPUT: C:\Documents and Settings\Student>d: D:\>cd javas D:\javas>set path=D:\Java\jdk1.6\bin D:\javas>javac MultiThreadChatServer.java D:\javas>javac TCPChat.java D:\javas>java MultiThreadChatServer SERVER SIDE OUTPUT: Usage: java MultiThreadChatServer Now using port number=2222 D:\javas>java TCPChat CLIENT SIDE OUTPUT:

D:\javas>java TCPChat

D:\javas>java TCPChat

RESULT:

PROGRAM: import java.text.DateFormatSymbols; import java.util.*; public class CalendarTest

{ public static void main(String[] args) { GregorianCalendar d = new GregorianCalendar(); int today = d.get(Calendar.DAY_OF_MONTH); int month = d.get(Calendar.MONTH); d.set(Calendar.DAY_OF_MONTH, 1); int weekday = d.get(Calendar.DAY_OF_WEEK); int firstDayOfWeek = d.getFirstDayOfWeek(); int indent = 0; while (weekday != firstDayOfWeek) { indent++; d.add(Calendar.DAY_OF_MONTH, -1); weekday = d.get(Calendar.DAY_OF_WEEK); } String[] weekdayNames = new DateFormatSymbols().getShortWeekdays(); do { System.out.printf("%4s", weekdayNames[weekday]); d.add(Calendar.DAY_OF_MONTH, 1); weekday = d.get(Calendar.DAY_OF_WEEK); } while (weekday != firstDayOfWeek); System.out.println(); for (int i = 1; i <= indent; i++) System.out.print(" "); d.set(Calendar.DAY_OF_MONTH, 1); do { int day = d.get(Calendar.DAY_OF_MONTH); System.out.printf("%3d", day); if (day == today) System.out.print("*"); else System.out.print(" "); d.add(Calendar.DAY_OF_MONTH, 1); weekday = d.get(Calendar.DAY_OF_WEEK); if (weekday == firstDayOfWeek) System.out.println(); } while (d.get(Calendar.MONTH) == month); if (weekday != firstDayOfWeek) System.out.println();

} }

OUTPUT: D:> / javac CalendarTest.java D:>/java CalendarTest Sun Mon Tue Wed Thu Fri Sat 1 2 3 4* 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

RESULT:

PROGRAM: import java.awt.*; import java.awt.geom.*; import java.awt.event.*;

import java.util.*; import java.util.concurrent.*; import javax.swing.*; public class AlgorithmAnimator { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { JFrame frame = new AnimationFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }); } } class AnimationFrame extends JFrame { public AnimationFrame() { ArrayComponent comp = new ArrayComponent(); add(comp, BorderLayout.CENTER); final Sorter sorter = new Sorter(comp); JButton runButton = new JButton("Run"); runButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { sorter.setRun(); } }); JButton stepButton = new JButton("Step"); stepButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) {

sorter.setStep(); } }); JPanel buttons = new JPanel(); buttons.add(runButton); buttons.add(stepButton); add(buttons, BorderLayout.NORTH); setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); Thread t = new Thread(sorter); t.start(); } private static final int DEFAULT_WIDTH = 300; private static final int DEFAULT_HEIGHT = 300; } class Sorter implements Runnable { public Sorter(ArrayComponent comp) { values = new Double[VALUES_LENGTH]; for (int i = 0; i < values.length; i++) values[i] = new Double(Math.random()); this.component = comp; this.gate = new Semaphore(1); this.run = false; } public void setRun() { run = true; gate.release(); } public void setStep() { run = false; gate.release(); } public void run() { Comparator<Double> comp = new Comparator<Double>() { public int compare(Double i1, Double i2) {

component.setValues(values, i1, i2); try { if (run) Thread.sleep(DELAY); else gate.acquire(); } catch (InterruptedException exception) { Thread.currentThread().interrupt(); } return i1.compareTo(i2); } }; Arrays.sort(values, comp); component.setValues(values, null, null); } private Double[] values; private ArrayComponent component; private Semaphore gate; private static final int DELAY = 100; private volatile boolean run; private static final int VALUES_LENGTH = 30; } class ArrayComponent extends JComponent { public synchronized void setValues(Double[] values, Double marked1, Double marked2) { this.values = values.clone(); this.marked1 = marked1; this.marked2 = marked2; repaint(); } public synchronized void paintComponent(Graphics g) { if (values == null) return; Graphics2D g2 = (Graphics2D) g; int width = getWidth() / values.length; for (int i = 0; i < values.length; i++) { double height = values[i] * getHeight(); Rectangle2D bar = new Rectangle2D.Double(width * i, 0, width, height);

if (values[i] == marked1 || values[i] == marked2) g2.fill(bar); else g2.draw(bar); } } private Double marked1; private Double marked2; private Double[] values; } OUTPUT: D:>/javac AlgorithmAnimator.java D:>/ java AlgorithmAnimator

RESULT:

Vous aimerez peut-être aussi