java lab printout

Upload: balaji-prakasam

Post on 07-Apr-2018

288 views

Category:

Documents


2 download

TRANSCRIPT

  • 8/4/2019 JAVA LAB PRINTOUT

    1/49

    1.D EVELOP R ATIONAL NUMBER CLASS IN J AVA .U SE J AVA DOC COMMENTS FOR DOCUMENTATION .Y OUR IMPLEMENTATION SHOULD USE EFFICIENT REPRESENTATION FOR A RATIONAL NUMBER ,I.E .(40/80) SHOULD BE REPRESENTED AS (1/2)

    PROGRAM :

    import java.util.Scanner; public class Rational{

    private int numerator; private int denominator; public Rational(int numerator,int denominator){if(denominator==0){throw new RuntimeException("Denominator is zero");}int g=gcd(numerator,denominator);if(g==1){System.out.println("No Common Divisor for Numerator and Denominator");this.numerator=numerator;this.denominator=denominator;}else{this.numerator=numerator/g;this.denominator=denominator/g;}}

    public String toString(){return numerator+"/"+denominator;}

    private static int gcd(int m,int n){if(0==n)return m;else return gcd(n,m%n);}

    public static void main(String[]args){Scanner scanner=new Scanner(System.in);System.out.print("Enter Numerator:");int numerator=scanner.nextInt();System.out.print("Enter Denominator:");

  • 8/4/2019 JAVA LAB PRINTOUT

    2/49

    int denominator=scanner.nextInt();Rational rational;rational=new Rational(numerator,denominator);System.out.println("Efficient Representation for the rational number:"+rational);}

    }

  • 8/4/2019 JAVA LAB PRINTOUT

    3/49

    OUTPUT:

  • 8/4/2019 JAVA LAB PRINTOUT

    4/49

    2.D EVELOPE DATE CLASS IN J AVA SIMILAR TO THE ONE AVAILABLE IN J AVA .UTIL PACKAGE .U SE J AVADOC COMMANDS .

    PROGRAM:

    import java.util.*; public class Datedemo{

    public static void main(String args[]){Date date=new Date();System.out.println("Today is "+date);}}

  • 8/4/2019 JAVA LAB PRINTOUT

    5/49

    OUTPUT:

  • 8/4/2019 JAVA LAB PRINTOUT

    6/49

    3.I MPLEMENT L ISP -LIKE LIST IN J AVA .W RITE BASIC OPERATIONS SUCH AS CAR , CDR AND CONS .I F L IS A LIST [3,0,2,5] ,L. CAR () RETURNS 3, WHILE L. CDR () RETURNS [0,2,5].

    PROGRAM:

    import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.List;import java.util.StringTokenizer;import java.util.logging.Logger;

    public class LispCommands{

    private String[] tokenList; private static Logger LOGGER=Logger.getLogger(LispCommands.class.getName()); public LispCommands(){}

    private void car(){LOGGER.info(tokenList[0]);}

    private void cdr(){Listlist=Arrays.asList(tokenList);ArrayListslist=new ArrayList(list);slist.remove(0);display(slist);}

    private void cons(String args){ListarrayList=new ArrayList(Arrays.asList(tokenList));arrayList.add(args);Collections.reverse(arrayList);display(arrayList);}

    private void parse(String args){ArrayListtokenList=new ArrayList();if(args!=null){StringTokenizer tokens=new StringTokenizer(args,"[]");while(tokens.hasMoreElements()){StringTokenizer commaTokens=new StringTokenizer(tokens.nextToken(),",");while(commaTokens.hasMoreElements())

  • 8/4/2019 JAVA LAB PRINTOUT

    7/49

    {String token=commaTokens.nextToken();if(token!=null && !token.trim().equals("")){tokenList.add(token.trim());

    }}}}this.tokenList=tokenList.toArray(new String[0]);}

    private void display(Object result){System.out.println();if(result instanceof String){

    LOGGER.info(result.toString());}else if(result.getClass().getName().equals("java.util.ArrayList")){LOGGER.info(result.toString());}}

    public static void main(String[] args){LispCommands L=new LispCommands();L.parse("[3,0,2,5]");L.car();L.cdr();L.cons("7");}}

  • 8/4/2019 JAVA LAB PRINTOUT

    8/49

    OUTPUT:

  • 8/4/2019 JAVA LAB PRINTOUT

    9/49

    4.D ESIGN A J AVA INTERFACE FOR ADTS TACK .D EVELOP TWO DIFFERENT CLASSES THAT IMPLEMENT THIS INTERFACE ,ONE USING ARRAY AND THE OTHER USING LINKED -LIST .P ROVIDE NECESSARY EXCEPTION HANDLING IN BOTH THE IMPLEMENTION .

    PROGRAM:

    public class ADTArray implements ADTStack {Object[] array;int index;

    public ADTArray(){this.array=new Object[128];this.index=0;}

    public Object pop(){index--;return array[index];}

    public void push(Object item){array[index]=item;index++;}

    public static void main(String[] args){ADTStack stack=new ADTArray();stack.push("Hi");stack.push(new Integer(100));

    System.out.println(stack.pop());System.out.println(stack.pop());}}

    public class ADTList implements ADTStack {

    private StackElement top; private int count=0; public void push(Object obj){StackElement stackElement=new StackElement(obj);stackElement.next=top;top=stackElement;count++;}

  • 8/4/2019 JAVA LAB PRINTOUT

    10/49

    public Object pop(){if(top==null)return null;Object obj=top.value;

    top=top.next;count--;return obj;}class StackElement{Object value;StackElement next;

    public StackElement(Object obj){value=obj;

    next=null;}}

    public static void main(String[] args){ADTStack stack=new ADTList();stack.push("Hi");stack.push(new Integer(100));System.out.println(stack.pop());System.out.println(stack.pop());}}

    public interface ADTStack {

    public void push(Object item); public Object pop();}

    OUTPUT:

  • 8/4/2019 JAVA LAB PRINTOUT

    11/49

    5.D ESIGN A VEHICLE CLASS HIERARCHY IN J AVA .W RITE A TEST PROGRAM TO DEMONSTRATE POLYMORPHISM

  • 8/4/2019 JAVA LAB PRINTOUT

    12/49

    PROGRAM:

    import java.io.*;class Vehicle

    {String regno;int model;Vehicle(String r,int m){regno=r;model=m;}void display(){System.out.println("registration no:"+regno);

    System.out.println("model no:"+model);}}class Twowheeler extends Vehicle{int noofwheel;Twowheeler(String r,int m,int n){super(r,m);noofwheel=n;}

    void display(){System.out.println("Two wheeler tvs");super.display();System.out.println("no of wheel"+noofwheel);}}class Threewheeler extends Vehicle{int noofleaf;Threewheeler(String r,int m,int n)

    {super(r,m);noofleaf=n;}void display(){System.out.println("Three wheeler auto");super.display();

  • 8/4/2019 JAVA LAB PRINTOUT

    13/49

    System.out.println("no of leaf"+noofleaf);}}class Fourwheeler extends Vehicle{

    int noofleaf;Fourwheeler(String r,int m,int n){super(r,m);noofleaf=n;}void display(){System.out.println("Four wheeler car");super.display();System.out.println("no of leaf"+noofleaf);

    }} public class Vehicledemo{

    public static void main(String arg[]){Twowheeler t1;Threewheeler th1;Fourwheeler f1;t1=new Twowheeler("TN74 12345",1,2);th1=new Threewheeler("TN74 54321",4,3);f1=new Fourwheeler("TN34 45678",5,4);t1.display();th1.display();f1.display();}}

    OUTPUT:

  • 8/4/2019 JAVA LAB PRINTOUT

    14/49

    6.D ESIGN CLASSES FOR C URRENCY ,R UPEE AND DOLLAR .W RITE A PROGRAM THAT RANDOMLY GENERATES R UPEE AND DOLLAR OBJECTS AND WRITE THEM INTO A FILE USING OBJECT SERIALIZATION .W RITE ANOTHER PROGRAM TO READ THAT

  • 8/4/2019 JAVA LAB PRINTOUT

    15/49

    FILE ,CONVERT TO R UPEE IF IT READS A DOLLAR ,WHILE LEAVE THE VALUE AS IT IS IF IT READS A R UPEE .

    PROGRAM:

    import java.io.Serializable; public abstract class Currency implements Serializable{

    protected static final Double DOLLAR_RUPEE_EXCHAGERATE=44.445D; public Currency(Double money){super();this.money=money;}

    protected Double money; public abstract Double getValue(); public abstract String getPrintableValue();}

    public class Rupee extends Currency{

    public Rupee(Double amount){super(amount);}

    public Double getValue(){return this.money;}

    public String getPrintableValue(){String strValue="Object Name : Rupee \n INR : Rs"+getValue()+"\n----------------------------------\n";return strValue;}}

    public class Dollar extends Currency{

    public Dollar(Double money){super(money);}

    public Double getValue(){return (this.money * DOLLAR_RUPEE_EXCHAGERATE);}

  • 8/4/2019 JAVA LAB PRINTOUT

    16/49

    public String getPrintableValue(){String strValue="Object Name : Dollar \n USD :$" +this.money+"\n INR : Rs"+getValue() + "\n-----------------\n";return strValue;

    }}

    import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.ObjectOutputStream;import java.util.Random;

    public class StoreCurrency{ public static void main(String[] args)throws FileNotFoundException,IOException{Currency currency=null;ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream(newFile("currency.dat")));Random random=new Random();for(int i=0;i

  • 8/4/2019 JAVA LAB PRINTOUT

    17/49

    public class ReadCurrency{

    public static void main(String[] args)throws IOException,ClassNotFoundException{Currency currency=null;

    ObjectInputStream in=new ObjectInputStream(new FileInputStream(newFile("currency.dat")));while((currency=(Currency)in.readObject())!=null){System.out.println(currency.getPrintableValue());}in.close();}}

    OUTPUT:

  • 8/4/2019 JAVA LAB PRINTOUT

    18/49

    7.D ESIGN A SCIENTIFIC CALCULATOR USING EVENT -DRIVEN PROGRAMMING PARADIGM OF J AVA .

    PROGRAM :

  • 8/4/2019 JAVA LAB PRINTOUT

    19/49

    import java.awt.*;import java.awt.event.*;

    // class CalcFrame for creating a calcul// ator frame and added windolistener to

    // close the calculator class CalcFrame extends Frame{CalcFrame( String str)

    {// call to superclass

    super(str);// to close the calculator(Frame)

    addWindowListener(new WindowAdapter()public void windowClosing (WindowEvent we)

    {

    System.exit(0);}});

    }}

    // main class Calculator implemnets two// interfaces ActionListener // and ItemListener

    public class Calculator implements ActionListener, ItemListener {// creating instances of objects

    CalcFrame fr;MenuBar mb;Menu view, font, about;MenuItem bold, regular, author;CheckboxMenuItem basic, scientific;CheckboxGroup cbgCheckbox radians, degrees;TextField display;Button key[] = new Button[20];// creates a button object array of 20 Button clearAll, clearEntry, round;

    Button scientificKey[] = new Button[10];// creates a button array of 8// declaring variables

    boolean addButtonPressed, subtractButtonPressed, multiplyButtonPressed; boolean divideButtonPressed, decimalPointPressed, powerButtonPressed; boolean roundButtonPressed = false;double initialNumber;

    // the first number for the two number operationdouble currentNumber = 0;

    //the number shown in the screen while it is being pressed

  • 8/4/2019 JAVA LAB PRINTOUT

    20/49

    int decimalPlaces = 0; public static void main (String args[]){

    // constructor Calculator calc = new Calculator();

    calc.makeCalculator();}

    public void makeCalculator(){

    // size of the buttonfinal int BWIDTH = 25;final int BHEIGHT = 25;int count =1;

    // create frame for the calculator

    fr = new CalcFrame("Basic Calculator");// set the sizefr.setSize(200,270);fr.setBackground(Color.blue);;

    // create a menubar for the framemb = new MenuBar();

    // add menu the menubar view = new Menu("View");font = new Menu ("Font");about = new Menu("About");

    // create instance of object for View me//nu

    basic = new CheckboxMenuItem("Basic",true);// add a listener to receive item events// when the state of an item changes

    basic.addItemListener(this);scientific = new CheckboxMenuItem("Scientific");

    //add a listener to receive item events//when the state of an item changes

    scientific.addItemListener(this);// create instance of object for font me

    // nu bold = new MenuItem("Arial Bold"); bold.addActionListener(this);regular = new MenuItem("Arial Regular");regular.addActionListener(this);

    // for about menuauthor = new MenuItem("Author");author.addActionListener(this);

    // add the items in the menu

  • 8/4/2019 JAVA LAB PRINTOUT

    21/49

    view.add(basic);view.add(scientific);font.add(bold);font.add(regular);about.add(author)

    // add the menus in the menubar mb.add(view);mb.add(font);mb.add(about);

    // add menubar to the framefr.setMenuBar(mb);

    // override the layout manager fr.setLayout(null);for (int row = 0; row < 3; ++row){for (int col = 0; col < 3; ++col)

    { // this will set the key from 1 tokey[count] = new Button(Integer.toString(count));key[count].addActionListener(this);

    // set the boundry for the keyskey[count].setBounds(30*(col + 1), 30*(row + 4),BWIDTH,BHEIGHT);key[count].setBackground(Color.yellow);

    // add to the framefr.add(key[count++]);}}

    // Now create, addlistener and add to fr // ame all other keys

    //0key[0] = new Button("0");key[0].addActionListener(this);key[0].setBounds(30,210,BWIDTH,BHEIGHT);key[0].setBackground(Color.yellow);fr.add(key[0]);

    //decimalkey[10] = new Button(".");key[10].addActionListener(this)key[10].setBounds(60,210,BWIDTH,BHEIGHT);key[10].setBackground(Color.yellow);fr.add(key[10]);

    //equals tokey[11] = new Button("=");key[11].addActionListener(this);key[11].setBounds(90,210,BWIDTH,BHEIGHT);key[11].setBackground(Color.yellow);

  • 8/4/2019 JAVA LAB PRINTOUT

    22/49

    fr.add(key[11]);//multiply

    key[12] = new Button("*");key[12].addActionListener(this);key[12].setBounds(120,120,BWIDTH,BHEIGHT);

    key[12].setBackground(Color.yellow);fr.add(key[12]);//divide

    key[13] = new Button("/");key[13].addActionListener(this);key[13].setBounds(120,150,BWIDTH,BHEIGHT);key[13].setBackground(Color.yellow);fr.add(key[13]);

    //additionkey[14] = new Button("+");key[14].addActionListener(this);

    key[14].setBounds(120,180,BWIDTH,BHEIGHT);key[14].setBackground(Color.yellow);fr.add(key[14]);

    //subtractkey[15] = new Button("-");key[15].addActionListener(this);key[15].setBounds(120,210,BWIDTH,BHEIGHT);key[15].setBackground(Color.yellow);fr.add(key[15]);

    //reciprocalkey[16] = new Button("1/x");key[16].addActionListener(this);key[16].setBounds(150,120,BWIDTH,BHEIGHT);key[16].setBackground(Color.yellow);fr.add(key[16]);

    //power key[17] = new Button("x^n");key[17].addActionListener(this);key[17].setBounds(150,150,BWIDTH,BHEIGHT);key[17].setBackground(Color.yellow);fr.add(key[17]);

    //change signkey[18] = new Button("+/-");key[18].addActionListener(this);key[18].setBounds(150,180,BWIDTH,BHEIGHT);key[18].setBackground(Color.yellow);fr.add(key[18]);

    //factorialkey[19] = new Button("x!");key[19].addActionListener(this);

  • 8/4/2019 JAVA LAB PRINTOUT

    23/49

    key[19].setBounds(150,210,BWIDTH,BHEIGHT);key[19].setBackground(Color.yellow);fr.add(key[19]);

    // CAclearAll = new Button("CA");

    clearAll.addActionListener(this);clearAll.setBounds(30, 240, BWIDTH+20, BHEIGHT);clearAll.setBackground(Color.yellow);fr.add(clearAll);

    // CEclearEntry = new Button("CE");clearEntry.addActionListener(this);clearEntry.setBounds(80, 240, BWIDTH+20, BHEIGHT);clearEntry.setBackground(Color.yellow);fr.add(clearEntry);

    // round

    round = new Button("Round");round.addActionListener(this);round.setBounds(130, 240, BWIDTH+20, BHEIGHT);round.setBackground(Color.yellow);fr.add(round);

    // set display areadisplay = new TextField("0");display.setBounds(30,90,150,20);display.setBackground(Color.white);

    // key for scientific calculator // Sine

    scientificKey[0] = new Button("Sin");scientificKey[0].addActionListener(this);scientificKey[0].setBounds(180, 120, BWIDTH + 10, BHEIGHT);scientificKey[0].setVisible(false);scientificKey[0].setBackground(Color.yellow);fr.add(scientificKey[0]);scientificKey[1] = new Button("Cos");scientificKey[1].addActionListener(this);scientificKey[1].setBounds(180, 150, BWIDTH + 10, BHEIGHT);scientificKey[1].setBackground(Color.yellow);scientificKey[1].setVisible(false);fr.add(scientificKey[1]);

    // TanscientificKey[2] = new Button("Tan");scientificKey[2].addActionListener(this);scientificKey[2].setBounds(180, 180, BWIDTH + 10, BHEIGHT);scientificKey[2].setBackground(Color.yellow);scientificKey[2].setVisible(false);fr.add(scientificKey[2]);

  • 8/4/2019 JAVA LAB PRINTOUT

    24/49

    // PIscientificKey[3] = new Button("Pi");scientificKey[3].addActionListener(this);scientificKey[3].setBounds(180, 210, BWIDTH + 10, BHEIGHT);scientificKey[3].setBackground(Color.yellow);

    scientificKey[3].setVisible(false);fr.add(scientificKey[3]);// aSine

    scientificKey[4] = new Button("aSin");scientificKey[4].addActionListener(this);scientificKey[4].setBounds(220, 120, BWIDTH + 10, BHEIGHT);scientificKey[4].setBackground(Color.yellow);scientificKey[4].setVisible(false);fr.add(scientificKey[4]);

    // aCosscientificKey[5] = new Button("aCos");

    scientificKey[5].addActionListener(this);scientificKey[5].setBounds(220, 150, BWIDTH + 10, BHEIGHT);scientificKey[5].setBackground(Color.yellow);scientificKey[5].setVisible(false);fr.add(scientificKey[5]);

    // aTanscientificKey[6] = new Button("aTan");scientificKey[6].addActionListener(this);scientificKey[6].setBounds(220, 180, BWIDTH + 10, BHEIGHT);scientificKey[6].setBackground(Color.yellow);scientificKey[6].setVisible(false);fr.add(scientificKey[6]);

    // EscientificKey[7] = new Button("E");scientificKey[7].addActionListener(this);scientificKey[7].setBounds(220, 210, BWIDTH + 10, BHEIGHT);scientificKey[7].setBackground(Color.yellow);scientificKey[7].setVisible(false);fr.add(scientificKey[7]);

    // to degreesscientificKey[8] = new Button("todeg");scientificKey[8].addActionListener(this);scientificKey[8].setBounds(180, 240, BWIDTH + 10, BHEIGHT);scientificKey[8].setBackground(Color.yellow);scientificKey[8].setVisible(false);fr.add(scientificKey[8]);// to radiansscientificKey[9] = new Button("torad");scientificKey[9].addActionListener(this);scientificKey[9].setBounds(220, 240, BWIDTH + 10, BHEIGHT);

  • 8/4/2019 JAVA LAB PRINTOUT

    25/49

    scientificKey[9].setBackground(Color.yellow);scientificKey[9].setVisible(false);fr.add(scientificKey[9]);cbg = new CheckboxGroup();degrees = new Checkbox("Degrees", cbg, true);

    radians = new Checkbox("Radians", cbg, false);degrees.addItemListener(this);radians.addItemListener(this);degrees.setBounds(185, 75, 3 * BWIDTH, BHEIGHT);radians.setBounds(185, 95, 3 * BWIDTH, BHEIGHT);degrees.setVisible(false);radians.setVisible(false);fr.add(degrees);fr.add(radians);fr.add(display);fr.setVisible(true);

    } // end of makeCalculator public void actionPerformed(ActionEvent ae)String buttonText = ae.getActionCommand();double displayNumber = Double.valueOf(display.getText()).doubleValue();

    // if the button pressed text is 0 to 9if((buttonText.charAt(0) >= '0') & (buttonText.charAt(0)

  • 8/4/2019 JAVA LAB PRINTOUT

    26/49

    roundButtonPressed = false;else{currentNumber = currentNumber * 10 + (int)buttonText.charAt(0)-(int)'0';display.setText(Integer.toString((int)currentNumber));

    }}// if button pressed is addition

    if(buttonText == "+") {addButtonPressed = true;initialNumber = displayNumber;currentNumber = 0;decimalPointPressed = false;}

    // if button pressed is subtractif (buttonText == "-") {

    subtractButtonPressed = true;initialNumber = displayNumber;currentNumber = 0;decimalPointPressed = false;}

    // if button pressed is divideif (buttonText == "/"){divideButtonPressed = true;initialNumber = displayNumber;currentNumber = 0;decimalPointPressed = false;}

    // if button pressed is multiplyif (buttonText == "*"){

    multiplyButtonPress;initialNumber = displayNumber;currentNumber = 0;decimalPointPressed = false}if (buttonText == "1/x") {

    // call reciprocal methoddisplay.setText(reciprocal(displayNumber));currentNumber = 0;decimalPointPressed = false;}

    // if button is pressed to change a signif (buttonText == "+/-") {

  • 8/4/2019 JAVA LAB PRINTOUT

    27/49

    // call changesign meyhod to change the// sign

    display.setText(changeSign(displayNumber));currentNumber = 0;decimalPointPressed = false;

    } // factorial buttonif (buttonText == "x!"){display.setText(factorial(displayNumber));currentNumber = 0;decimalPointPressed = false;

    // power buttonif (buttonText == "x^n") {

    powerButtonPressed = true;initialNumber = displayNumber;

    currentNumber = 0;decimalPointPressed = false;}

    // now for scientific buttonsif (buttonText == "Sin"){if (degrees.getState())display.setText(Double.toString(Math.sin(Math.PI * displayNumber/180)));else{display.setText(Double.toString(Math.sin(displayNumber)));currentNumber = 0;decimalPointPressed = false;}}if (buttonText == "Cos"){if (degrees.getState())display.setText(Double.toString(Math.cos(Math.PI * displayNumber/180)));else{display.setText(Double.toString(Math.cos(displayNumber)));currentNumber = 0;decimalPointPressed = false;}}if (buttonText == "Tan"){if (degrees.getState())display.setText(Double.toString(Math.tan(Math.PI * displayNumber/180)));

  • 8/4/2019 JAVA LAB PRINTOUT

    28/49

    else{display.setText(Double.toString(Math.tan(displayNumber)));currentNumber = 0;decimalPointPressed = false;

    }}if (buttonText == "aSin"){if (degrees.getState())display.setText(Double.toString(Math.asin(displayNumber)* 180/Math.PI));else{display.setText(Double.toString(Math.asin(displayNumber)));currentNumber = 0;decimalPointPressed = false;

    }}if (buttonText == "aCos"){if (degrees.getState())display.setText(Double.toString(Math.acos(displayNumber)* 180/Math.PI ));else {display.setText(Double.toString(Math.acos(displayNumber)));currentNumber = 0;decimalPointPressed = false;}} if (buttonText == "aTan") {if (degrees.getState())display.setText(Double.toString(Math.atan(displayNumber)* 180/Math.PI ));else {display.setText(Double.toString(Math.atan(displayNumber)));currentNumber = 0;decimalPointPressed = false;}}// this will convert the numbers display// ed to degreesif (buttonText == "todeg")display.setText(Double.toString(Math.toDegrees(displayNumber)));// this will convert the numbers display// ed to radiansif (buttonText == "torad")display.setText(Double.toString(Math.toRadians(displayNumber)));if (buttonText == "Pi") {display.setText(Double.toString(Math.PI));

  • 8/4/2019 JAVA LAB PRINTOUT

    29/49

    currentNumber =0;decimalPointPressed = false;}if (buttonText == "Round")roundButtonPressed = true;

    // check if decimal point is pressedif (buttonText == ".") {String displayedNumber = display.getText();

    boolean decimalPointFound = false;int i;decimalPointPressed = true;// check for decimal pointfor (i =0; i < displayedNumber.length(); ++i){if(displayedNumber.charAt(i) == '.'){

    decimalPointFound = true;continue;}}if (!decimalPointFound)decimalPlaces = 1;}if(buttonText == "CA"){// set all buttons to falseresetAllButtons();display.setText("0");currentNumber = 0;}if (buttonText == "CE"){

    display.setText("0");currentNumber = 0;decimalPointPressed = false;}if (buttonText == "E"){

    display.setText(Double.toString(Math.E));currentNumber = 0;decimalPointPressed = false;}// the main actionif (buttonText == "="){

    currentNumber = 0;

  • 8/4/2019 JAVA LAB PRINTOUT

    30/49

    // if add button is pressedif(addButtonPressed)display.setText(Double.toString(initialNumber + displayNumber));// if subtract button is pressedif(subtractButtonPressed)

    display.setText(Double.toString(initialNumber - displayNumber));// if divide button is pressedif (divideButtonPressed){// check if the divisor is zeroif(displayNumber == 0){MessageBox mb = new MessageBox ( fr, "Error ", true, "Cannot divide by zero.");mb.show();}else

    display.setText(Double.toString(initialNumber/displayNumber));}if(multiplyButtonPressed)display.setText(Double.toString(initialNumber * displayNumber));// if power button is pressedif (powerButtonPressed)display.setText(power(initialNumber, displayNumber));// set all the buttons to falseresetAllButtons();}if (buttonText == "Arial Regular"){

    for (int i =0; i < 10; ++i)key[i].setFont(new Font("Arial", Font.PLAIN, 12));}if (buttonText == "Arial Bold"){for (int i =0; i < 10; ++i)key[i].setFont(new Font("Arial", Font.BOLD, 12));}if (buttonText == "Author"){

    MessageBox mb = new MessageBox ( fr, "Calculator ver 1.0 beta ", true, "Author:Inder Mohan Singh.");mb.show();}} // end of action events

    public void itemStateChanged(ItemEvent ie){

    if (ie.getItem() == "Basic")

  • 8/4/2019 JAVA LAB PRINTOUT

    31/49

    { basic.setState(true);scientific.setState(false);fr.setTitle("Basic Calculator");fr.setSize(200,270);

    // check if the scientific keys are visi// ble. if true hide themif (scientificKey[0].isVisible()){

    for (int i=0; i < 8; ++i)scientificKey[i].setVisible(false);radians.setVisible(false);degrees.setVisible(false);}

    }

    if (ie.getItem() == "Scientific"){ basic.setState(false);scientific.setState(true);fr.setTitle("Scientific Calculator");fr.setSize(270,270);// check if the scientific keys are visible. if true display themif (!scientificKey[0].isVisible()){

    for (int i=0; i < 10; ++i)scientificKey[i].setVisible(true);radians.setVisible(true);degrees.setVisible(true);}}} // end of itemState// this method will reset all the button// Pressed property to false public void resetAllButtons()addButtonPressed = false;subtractButtonPressed = false;multiplyButtonPressed = false;divideButtonPressed = false;decimalPointPressed = false;

    powerButtonPressed = false;roundButtonPressed = false;}

    public String factorial(double num)

  • 8/4/2019 JAVA LAB PRINTOUT

    32/49

    {int theNum = (int)num;if (theNum < 1){

    MessageBox mb = new MessageBox (fr, "Facorial Error", true,

    "Cannot find the factorial of numbers less than 1.");mb.show();return ("0");}else{for (int i=(theNum -1); i > 1; --i)theNum *= i;return Integer.toString(theNum);}}

    public String reciprocal(double num){if (num ==0){

    MessageBox mb = new MessageBox(fr,"Reciprocal Error", true,"Cannot find thereciprocal of 0");mb.show();}elsenum = 1/num;return Double.toString(num);}

    public String power (double base, double index) {return Double.toString(Math.pow(base, index));}

    public String changeSign(double num){

    return Double.toString(-num);}}

    class MessageBox extends Dialog implements ActionListener {Button ok;

    MessageBox(Frame f, String title, boolean mode, String message) {super(f, title, mode);Panel centrePanel = new Panel();Label lbl = new Label(message);centrePanel.add(lbl);add(centrePanel, "Center");

  • 8/4/2019 JAVA LAB PRINTOUT

    33/49

    Panel southPanel = new Panel();ok = new Button ("OK");ok.addActionListener(this);southPanel.add(ok);add(southPanel, "South");

    pack();

    addWindowListener (new WindowAdapter(){

    public void windowClosing (WindowEvent we){

    System.exit(0);}});}

    public void actionPerformed(ActionEvent ae){dispose();}}

    OUTPUT:

  • 8/4/2019 JAVA LAB PRINTOUT

    34/49

    8.W RITE A MULTI -THREADED J AVA PROGRAM TO PRINT ALL NUMBERS BELOW 100,000 THAT ARE BOTH PRIME AND FIBONACCI NUMBER

  • 8/4/2019 JAVA LAB PRINTOUT

    35/49

    PROGRAM:

    MULTITHREAD .JAVAimport java.io.*;

    import java.util.*;class MyThread1 extends Thread{

    private PipedReader pr; private PipedWriter pw;MyThread1(PipedReader pr,PipedWriter pw){this.pr=pr;this.pw=pw;}

    public void run()

    {try{int i;for(i=1;i

  • 8/4/2019 JAVA LAB PRINTOUT

    36/49

    private PipedWriter pw;MyThread2(PipedReader pr,PipedWriter pw){this.pr=pr;this.pw=pw;

    } public void run(){Try{int f1,f2=1,f3=1;for(int i=1;i

  • 8/4/2019 JAVA LAB PRINTOUT

    37/49

    MyThread2 mt2=new MyThread2(pr2,pw2);System.out.println("Fibonacci Numbers:");mt2.start();int item2;while((item2=pr2.read())!=-1)

    {char ch2=((char)item2);System.out.print(Character.toString(ch2));list2.add(Character.toString(ch2));}

    pr2.close();System.out.println("Elements common to both lists are:");list1.retainAll(list2);for(int i=0;i

  • 8/4/2019 JAVA LAB PRINTOUT

    38/49

    9.D EVELOP A SIMPLE OPAC SYSTEM FOR LIBRARY USING EVEN -DRIVEN AND CONCURRENT PROGRAMMING PARADIGMS OF J AVA .U SE JDBC TO CONNECT TO A

    BACK -END DATABASE .

  • 8/4/2019 JAVA LAB PRINTOUT

    39/49

    PROGRAM:

    Event driven:import java.sql.*;

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

    public class Datas extends JFrame implements ActionListener {JTextField id;JTextField name;JButton next;JButton addnew;JPanel p;static ResultSet res;

    static Connection conn;static Statement stat;

    public Datas(){super("Our Application");Container c=getContentPane();c.setLayout(new GridLayout(5,1));id=new JTextField(20);name=new JTextField(20);next=new JButton("Next BOOK");

    p=new JPanel();

    c.add(new JLabel("ISBN",JLabel.CENTER));c.add(id);c.add(new JLabel("Book Name",JLabel.CENTER));c.add(name);c.add(p);

    p.add(next);next.addActionListener(this);

    pack();setVisible(true);addWindowListener(new WIN());}

    public static void main(String args[]){Datas d=new Datas();try{Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");conn=DriverManager.getConnection("jdbc:odbc:custo");stat=conn.createStatement();

  • 8/4/2019 JAVA LAB PRINTOUT

    40/49

    res=stat.executeQuery("Select * from stu");}catch(Exception e){System.out.println("Error"+e);

    }d.showRecord(res);}

    public void actionPerformed(ActionEvent e){if(e.getSource()==next){try{res.next();}

    catch(Exception ee){}showRecord(res);}}

    public void showRecord(ResultSet res){try{id.setText(res.getString(2));name.setText(res.getString(3));}catch(Exception e){}}class WIN extends WindowAdapter {

    public void windowClosing(WindowEvent w){JOptionPane jop=new JOptionPane();

    jop.showMessageDialog(null,"Database","Thanks",JOptionPane.QUESTION_MESSAGE);}}}OUTPUT:

  • 8/4/2019 JAVA LAB PRINTOUT

    41/49

    C ONCURRENTPROGRAM:

    import java.sql.*;

  • 8/4/2019 JAVA LAB PRINTOUT

    42/49

    import java.sql.DriverManager.*;class Ja{String bookid,bookname;int booksno;

    Connection con;Statement stmt;ResultSet rs;Ja(){try{Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");con=DriverManager.getConnection("jdbc:odbc:co");}catch(Exception e)

    {System.out.println("connection error");}}void myput(){try{stmt=con.createStatement();rs=stmt.executeQuery("SELECT * FROM opac");while(rs.next()){

    booksno=rs.getInt(1); bookid=rs.getString(2); bookname=rs.getString(3);System.out.println("\n"+ booksno+"\t"+bookid+"\t"+bookname);}rs.close();stmt.close();con.close();}catch(SQLException e){System.out.println("sql error");}}}class prog1{

    public static void main(String arg[])

  • 8/4/2019 JAVA LAB PRINTOUT

    43/49

    {Ja j=new Ja();

    j.myput();}}

    OUTPUT:

  • 8/4/2019 JAVA LAB PRINTOUT

    44/49

    10.D EVELOP MULTI -THREADED ECHO SERVER AND A CORRESPONDING GUI CLIENT IN J AVA

  • 8/4/2019 JAVA LAB PRINTOUT

    45/49

    PROGRAM:

    import java.net.*;import java.io.*;

    public class EchoServer

    {ServerSocket m_ServerSocket; public EchoServer(){try{m_ServerSocket=new ServerSocket(12111);}catch(IOException ioe){System.out.println("Could not create server socket at 12111.Quitting");

    System.exit(-1);}System.out.println("Listening for clients........");int id=0;while(true){try{Socket clientSocket=m_ServerSocket.accept();ClientServiceThread cliThread=new ClientServiceThread(clientSocket,id++);cliThread.start();

    }catch(IOException ioe){System.out.println("Exception encountered on accept.Ignoring.Stack Trace:");ioe.printStackTrace();}}}

    public static void main(String[] args){new EchoServer();

    }class ClientServiceThread extends Thread{Socket m_clientSocket;int m_clientID=-1;

    boolean m_bRunThread=true;ClientServiceThread(Socket s,int clientID)

  • 8/4/2019 JAVA LAB PRINTOUT

    46/49

    {m_clientSocket=s;m_clientID=clientID;}

    public void run()

    {BufferedReader in=null;PrintWriter out=null;System.out.println("Accepted Client:ID-"+m_clientID+":Address-"+m_clientSocket.getInetAddress().getHostName());try{in=new BufferedReader(new InputStreamReader(m_clientSocket.getInputStream()));out=new PrintWriter(new OutputStreamWriter(m_clientSocket.getOutputStream()));while(m_bRunThread){

    String clientCommand=in.readLine();System.out.println("Client Says:"+clientCommand);if(clientCommand.equalsIgnoreCase("quit")){m_bRunThread=false;System.out.println("Stopping client thread for client:"+m_clientID);}else{out.println(clientCommand);out.flush();}}}catch(Exception e){e.printStackTrace();}finally{try{in.close();out.close();m_clientSocket.close();System.out.println("....Stopped");}catch(IOException ioe){ioe.printStackTrace();

  • 8/4/2019 JAVA LAB PRINTOUT

    47/49

    }}}}}

    import java.net.*;import java.io.*;

    public class EchoClient{

    public static void main(String[] args){if(args.length==0)

    {System.out.println("Usage:EchoClient ");return;}Socket s=null;try{s=new Socket(args[0],12111);}catch(UnknownHostException uhe){System.out.println("Unknown Host:"+args[0]);s=null;}catch(IOException ioe){System.out.println("Cant connect to server at 12111.Make sure it is running");s=null;}if(s==null)System.exit(-1);BufferedReader in=null;PrintWriter out=null;try{in=new BufferedReader(new InputStreamReader(s.getInputStream()));out=new PrintWriter(new OutputStreamWriter(s.getOutputStream()));

    out.println("Hello");out.flush();

  • 8/4/2019 JAVA LAB PRINTOUT

    48/49

    System.out.println("Server Says:"+in.readLine());

    out.println("This");out.flush();System.out.println("Server Says:"+in.readLine());

    out.println("is");out.flush();System.out.println("Server Says:"+in.readLine());

    out.println("a");out.flush();System.out.println("Server Says:"+in.readLine());

    out.println("Test");out.flush();

    System.out.println("Server Says:"+in.readLine());out.println("Quit");out.flush();}catch(IOException ioe){System.out.println("Exception during communication.Server probably closedconnection.");}finally{try{out.close();in.close();s.close();}catch(Exception e){e.printStackTrace();}}}}

    OUTPUT:

  • 8/4/2019 JAVA LAB PRINTOUT

    49/49