Sie sind auf Seite 1von 49

CS2309 JAVA LAB Ex No: 1 IMPLEMENTATION OF RATIONAL NUMBER AIM: To write a java program to print rational numbers using

scanner classes. ALGORITHM: 1. Start the program. 2. Include necessary package in java. 3. Declare the class as public and class name as rational. 4. In constructor, get the values of Numerator and denominator. 5. By using gcd(), find the great common divisor between num and den. 6. Print the lowest possible value for the num and den. 7. Stop the program.

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 : "); int denominator = scanner.nextInt(); Rational rational = new Rational(numerator, denominator); System.out.println("Efficient Representation for the rational number :" + rational); } } OUTPUT: D:\rat>javac Rational.java D:\rat>java Rational Enter Numerator : 120 Enter Denominator : 10 Efficient Representation for the rational number :12/1

Ex.No.2
Program:

IMPLEMENTATION OF DATE SERVER

import java.io.*; import java.util.Date; class DateDemo { public static void main(String args[]) { Date date=new Date(); System.out.println(date); long msec=date.getTime(); System.out.println("milliseconds:" +msec); } }

OUTPUT: Mon Aug 08 09.45.35 IST 2011 Millisecond : 1312776935468

Ex.No.2
AIM:

IMPLEMENT LISP_LIST
To implement a java program to define IN Lisp_like Use JavaDoc

comments ALGORITHM:

ALGORITHM STEP 1: Create a node of a list having data part and link part. STEP 2: Create a menu having the following choices : insert, car, cdr, adjoin and display. STEP 3: Read the choice from the user and call the respective m ethods. STEP 4: Create another class which implements the same interface to implement the concept of stack through linked list. INSERT STEP 1: Create an object of node and append to the list. CAR STEP 1: Return the first node data. CDR STEP 1: Return all the node (data part) in the list except the first node. ADJOIN STEP 1: Check if the node to be inserted is already present in the list, if not present append to the list.

Program:
class Lisp { public Vector car(Vector v) {

Vector t = new Vector(); t.addElement(v.elementAt(0)); return t; } public Vector cdr(Vector v) { Vector t = new Vector(); for(int i=1;i<v.size();i++) t.addElement(v.elementAt(i)); return t; } public Vector cons(String x, Vector v) { v.insertElementAt(x,0); return v; } public Vector cons(int x, Vector v) { v.insertElementAt(x,0); return v; } } class Lisp_List2 { public static void main(String[] args) { Lisp a = new Lisp();

Vector v = new Vector(4,1); Vector v1 = new Vector(); System.out.println("\n Creating a List of Strings....\n"); v.addElement("S.R.Tendulkar"); v.addElement("M.S.Dhoni"); v.addElement("V.Sehwag"); v.addElement("S.Raina"); System.out.println("\n The Contents of the List are " + v); System.out.print("\n The CAR of this List...."); System.out.println(a.car(v)); System.out.print("\n The CDR of this List...."); v1 = a.cdr(v); System.out.println(v1); System.out.println("\n The Contents of this list after CONS.."); v1 = a.cons("Gambhir",v); System.out.print(" " + v1); v.removeAllElements(); v1.removeAllElements(); System.out.println("\n\n Creating a List of Integers....\n"); v.addElement(3); v.addElement(0); v.addElement(2); v.addElement(5); System.out.println("\n The Contents of the List are " + v); System.out.print("\n The CAR of this List...."); System.out.println(a.car(v)); System.out.print("\n The CDR of this List....");

v1 = a.cdr(v); System.out.println(v1); System.out.println("\n The Contents of this list after CONS.."); v1 = a.cons(9,v); System.out.print(" " + v1); } }

OUTPUT:
Enter the Size of the list:4 Enter the element 1 of the list:3 Enter the element 2 of the list:0 Enter the element 3 of the list:2 Enter the element 4 of the list:5 The contents of the List are:[ 3 0 2 5 ] CAR of the List: 3 The CDR of the List is:[ 0 2 5 ] The List after using CONS and adding an element:[ 5 3 0 2 5 ] The length of the list is 5

Ex No: 4 IMPLEMENTATION OF STACK

AIM: To implement a java program to define an Stack ADT by using array.

ALGORITHM: 1. Start the program and include the necessary packages. 2. Declare a class in java named Stack. 3. Declare and define methods named pop and push. 4. The method named push() has to perform the push operation in stack. 5. The method named pop() has to perform the pop operation in stack. 6. Declare a class named stackprog to define the main method. 7. Create object for the class stack. 8. Perform push() and pop() by using while loop. 9. Execute program and tend the output.

PROGRAM: import java.io.*; interface IntStack { void push(int item); int pop(); } class FixedStack implements IntStack { private int stck[]; private int tos; FixedStack(int size) { stck=new int[size]; tos=-1; } public void push(int item) { if(tos==stck.length-1)

System.out.println("stack is full"); else stck[++tos]=item; } public int pop() { if(tos<0) { System.out.println("stack underflow"); return 0; } else return stck[tos--]; } } class iftest { public static void main(String args[]) { FixedStack mystack1=new FixedStack(5); FixedStack mystack2=new FixedStack(8); for(int i=0;i<5;i++) mystack1.push(i); for(int i=0;i<8;i++) mystack2.push(i); System.out.println("stack in mystack1:"); for(int i=0;i<5;i++) System.out.println(mystack1.pop()); System.out.println("stack in mystack2:"); for(int i=0;i<8;i++) System.out.println(mystack2.pop()); } } OUTPUT:

D:\ssr>java iftest stack in mystack1:

4 3 2 1 0 stack in mystack2: 7 6 5 4 3 2 1 0

Ex No: 5 IMPLEMENTATION OF VEHICLE CLASS USING POLYMORPHISM AIM: To create a vehicle class hierarchy in java and write a program to demonstrate polymorphism. ALGORITHM: 1. Start the program. 2. Include necessary package in java.

3. Create a class as vehicle. 4. Using class vehicle create any three sub classes. 5. In sub classes create vehicle name, registration no, model no, no of leaf for each. 6. Declare the main class as Polymorphism. 7. Call the subclass using main class to display the vehicle name, registration no, model no, no of leaf for each. 8. Stop the program. 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(); 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 45677",5,4); t1.display(); th1.display(); f1.display(); } } OUTPUT: C:\Documents and Settings\Admin.VKKNCE-44FC3114>e: E:\>cd java E:\java>javac Vehicledemo.java E:\java>java Vehicledemo Two wheeler tvs registration no:TN74 12345 model no:1 no of wheel2 three wheeler auto Ex No: 6 IMPLEMENTATION OF CURRENCY CONVERTER AIM: To implement a program to read and store the currency. ALGORITHM: 1. Start the program and to include necessary packages. 2. Using currency declare a class to get the value and to declare the methods.

3. Declare a class named Rupee to implement the value and to print the Rupee value in standards of INR. 4. Declare a class named Dollar to implement the value and to print the Dollar value in standards of US $. 5. Declare a class named Read Currency to read the currency value. 6. Declare a class named Store Currency to store the value in a doc file named currency.doc.

PROGRAM: Currency.java import java.io.Serializable; public abstract class Currency implements Serializable { protected static final double DOLLAR_RUPEE_EXCHANGE_RATE=44.445; public Currency(double money) { super(); this.money=money; } protected double money; public abstract double getValue(); public abstract String getPrintableValue(); } Dollar.java public class Dollar extends Currency { public Dollar(double money) { super(money); } public double getValue() { return (this.money*DOLLAR_RUPEE_EXCHANGE_RATE); }

public String getPrintableValue() { String str="ObjectName:Dollar\nUSD:$"+this.money+"\nINR:Rs"+getValue()+"\n_____ ____________________________\n"; return str; } }

Rupee.java 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 \nINR: Rs"+getValue()+"\n_______________\n"; return strValue; } }

ReadCurrency.java import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; public class ReadCurrency {

public static void main(String args[])throws IOException,ClassNotFoundException { Currency currency=null; ObjectInputStream in=new ObjectInputStream(new FileInputStream(new File("currency.dat"))); while((currency=(Currency)in.readObject())!=null) { System.out.println(currency.getPrintableValue()); } in.close(); } } StoreCurrency.java

import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import j ava.io.IOException; import java.io.ObjectOutputStream; import java.util.Random; public class StoreCurrency { public static void main(String[] args)throws IOException,ClassNotFoundException { Currency currency=null; ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream(new File("currency.dat"))); Random random=new Random(); for(int i=0;i<10;i++) { int decide=random.nextInt(); double value=(random.nextDouble() *10); if((decide%2)==0) { currency=new Rupee(value); } else

{ currency=new Dollar(value); } out.writeObject(currency); } out.writeObject(null); out.closea(); } }

OUTPUT: C:\currency>java ReadCurrency ObjectName: Dollar USD:$3.9450164432586177 INR:Rs175.33625582062928 ObjectName:Dollar USD:$5.605485723528298 INR:Rs249.1358129822152 ObjectName:Dollar USD:$2.3208304627144627 INR:Rs103.14930991534429 object Name: Rupee INR: Rs3.0181563687516544 ObjectName:Dollar USD:$8.350218711605683 INR:Rs371.12547063731455 ObjectName:Dollar USD:$9.125496776442645 INR:Rs405.58270422899335 object Name: Rupee INR: Rs5.844095738688654 ObjectName:Dollar

USD:$9.078227460713496 INR:Rs403.48181949141133 ObjectName:Dollar USD:$8.991445194590783 INR:Rs399.62478167358734 object Name: Rupee INR: Rs0.11136365452823815

Ex No: 7 IMPLEMENTATION OF CALCULATOR AIM: To implement a calculator using GUI Environment with the help of javax.swing package. ALGORITHM: 1. Start the program. 2. Include the necessary packages in java. 3. Create the scientific calculator frame and added window listener to close the calculator. 4. Create the instance of objects such as menu bar, font, text field display, font, menu item bold. 5. Declaring boolean buttons such as add button, sub button, multiple button, divide buttons. 6. Initialize the scientific keys 1 to 9.

7. Initialize the commands buttons. 8. Save the file with the filename. 9. Stop the program. PROGRAM: import java.awt.*; import java.awt.event.*; 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); } }); } } public class Calculator implements ActionListener, ItemListener { CalcFrame fr; MenuBar mb; Menu view, font, about; MenuItem bold, regular, author; CheckboxMenuItem basic, scientific; CheckboxGroup cbg; Checkbox 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 boolean addButtonPressed, subtractButtonPressed, multiplyButtonPressed; boolean divideButtonPressed, decimalPointPressed, powerButtonPressed;

boolean roundButtonPressed = false; double initialNumber; // the first number for the two number operation double currentNumber = 0; //the number shown in the screen while it is //being pressed int decimalPlaces = 0; public static void main (String args[]) { Calculator calc = new Calculator(); calc.makeCalculator(); } public void makeCalculator() { final int BWIDTH = 25; final int BHEIGHT = 25; int count =1; fr = new CalcFrame("Basic Calculator"); fr.setSize(200,270); fr.setBackground(Color.white);; mb = new MenuBar(); view = new Menu("View"); font = new Menu ("Font"); about = new Menu("About"); basic = new CheckboxMenuItem("Basic",true); basic.addItemListener(this); scientific = new CheckboxMenuItem("Scientific"); scientific.addItemListener(this); bold = new MenuItem("Arial Bold"); bold.addActionListener(this); regular = new MenuItem("Arial Regular"); regular.addActionListener(this); author = new MenuItem("Author"); author.addActionListener(this); view.add(basic); view.add(scientific);

font.add(bold); font.add(regular); about.add(author); mb.add(view); mb.add(font); mb.add(about); fr.setMenuBar(mb); fr.setLayout(null); for (int row = 0; row < 3; ++row) { for (int col = 0; col < 3; ++col) { key[count] = new Button(Integer.toString(count)); key[count].addActionListener(this); key[count].setBounds(30*(col + 1), 30*(row + 4),BWIDTH,BHEIGHT); key[count].setBackground(Color.white); fr.add(key[count++]); } } key[0] = new Button("0"); key[0].addActionListener(this); key[0].setBounds(30,210,BWIDTH,BHEIGHT); key[0].setBackground(Color.white); fr.add(key[0]); key[10] = new Button("."); key[10].addActionListener(this); key[10].setBounds(60,210,BWIDTH,BHEIGHT); key[10].setBackground(Color.white); fr.add(key[10]); key[11] = new Button("="); key[11].addActionListener(this); key[11].setBounds(90,210,BWIDTH,BHEIGHT); key[11].setBackground(Color.white); fr.add(key[11]); //multiply key[12] = new Button("*"); key[12].addActionListener(this); key[12].setBounds(120,120,BWIDTH,BHEIGHT);

key[12].setBackground(Color.white); fr.add(key[12]); //divide key[13] = new Button("/"); key[13].addActionListener(this); key[13].setBounds(120,150,BWIDTH,BHEIGHT); key[13].setBackground(Color.white); fr.add(key[13]); //addition key[14] = new Button("+"); key[14].addActionListener(this); key[14].setBounds(120,180,BWIDTH,BHEIGHT); key[14].setBackground(Color.white); fr.add(key[14]); //subtract key[15] = new Button("-"); key[15].addActionListener(this); key[15].setBounds(120,210,BWIDTH,BHEIGHT); key[15].setBackground(Color.white); fr.add(key[15]); //reciprocal key[16] = new Button("1/x"); key[16].addActionListener(this); key[16].setBounds(150,120,BWIDTH,BHEIGHT); key[16].setBackground(Color.white); 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.white); fr.add(key[17]); //change sign

key[18] = new Button("+/-"); key[18].addActionListener(this); key[18].setBounds(150,180,BWIDTH,BHEIGHT); key[18].setBackground(Color.white); fr.add(key[18]); //factorial key[19] = new Button("x!"); key[19].addActionListener(this); key[19].setBounds(150,210,BWIDTH,BHEIGHT); key[19].setBackground(Color.white); fr.add(key[19]); // CA clearAll = new Button("CA"); clearAll.addActionListener(this); clearAll.setBounds(30, 240, BWIDTH+20, BHEIGHT); clearAll.setBackground(Color.white); fr.add(clearAll); // CE clearEntry = new Button("CE"); clearEntry.addActionListener(this); clearEntry.setBounds(80, 240, BWIDTH+20, BHEIGHT); clearEntry.setBackground(Color.white); fr.add(clearEntry);

// round round = new Button("Round"); round.addActionListener(this); round.setBounds(130, 240, BWIDTH+20, BHEIGHT); round.setBackground(Color.white); fr.add(round); // set display area display = 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.white); fr.add(scientificKey[0]); // cosine scientificKey[1] = new Button("Cos"); scientificKey[1].addActionListener(this); scientificKey[1].setBounds(180, 150, BWIDTH + 10, BHEIGHT); scientificKey[1].setBackground(Color.white); scientificKey[1].setVisible(false); fr.add(scientificKey[1]); // Tan scientificKey[2] = new Button("Tan"); scientificKey[2].addActionListener(this); scientificKey[2].setBounds(180, 180, BWIDTH + 10, BHEIGHT); scientificKey[2].setBackground(Color.white); scientificKey[2].setVisible(false); fr.add(scientificKey[2]); // PI scientificKey[3] = new Button("Pi"); scientificKey[3].addActionListener(this); scientificKey[3].setBounds(180, 210, BWIDTH + 10, BHEIGHT); scientificKey[3].setBackground(Color.white); 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.white);

scientificKey[4].setVisible(false); fr.add(scientificKey[4]); // aCos scientificKey[5] = new Button("aCos"); scientificKey[5].addActionListener(this); scientificKey[5].setBounds(220, 150, BWIDTH + 10, BHEIGHT); scientificKey[5].setBackground(Color.white); scientificKey[5].setVisible(false); fr.add(scientificKey[5]); // aTan scientificKey[6] = new Button("aTan"); scientificKey[6].addActionListener(this); scientificKey[6].setBounds(220, 180, BWIDTH + 10, BHEIGHT); scientificKey[6].setBackground(Color.white); scientificKey[6].setVisible(false); fr.add(scientificKey[6]); // E scientificKey[7] = new Button("E"); scientificKey[7].addActionListener(this); scientificKey[7].setBounds(220, 210, BWIDTH + 10, BHEIGHT); scientificKey[7].setBackground(Color.white); scientificKey[7].setVisible(false); fr.add(scientificKey[7]); // to degrees scientificKey[8] = new Button("todeg"); scientificKey[8].addActionListener(this); scientificKey[8].setBounds(180, 240, BWIDTH + 10, BHEIGHT); scientificKey[8].setBackground(Color.white); scientificKey[8].setVisible(false); fr.add(scientificKey[8]); // to radians scientificKey[9] = new Button("torad"); scientificKey[9].addActionListener(this); scientificKey[9].setBounds(220, 240, BWIDTH + 10, BHEIGHT);

scientificKey[9].setBackground(Color.white); 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 9 if((buttonText.charAt(0) >= '0') & (buttonText.charAt(0) <= '9')) { if(decimalPointPressed) { for (int i=1;i <=decimalPlaces; ++i) currentNumber *= 10; currentNumber +=(int)buttonText.charAt(0)- (int)'0'; for (int i=1;i <=decimalPlaces; ++i) { currentNumber /=10; } ++decimalPlaces; display.setText(Double.toString(currentNumber)); } else if (roundButtonPressed)

{ int decPlaces = (int)buttonText.charAt(0) - (int)'0'; for (int i=0; i< decPlaces; ++i) displayNumber *=10; displayNumber = Math.round(displayNumber);

for (int i = 0; i < decPlaces; ++i) { displayNumber /=10; } display.setText(Double.toString(displayNumber)); roundButtonPressed = false; } else { currentNumber = currentNumber * 10 + (int)buttonText.charAt(0)(int)'0'; display.setText(Integer.toString((int)currentNumber)); } } if(buttonText == "+") { addButtonPressed = true; initialNumber = displayNumber; currentNumber = 0; decimalPointPressed = false; } // if button pressed is subtract if (buttonText == "-") { subtractButtonPressed = true; initialNumber = displayNumber; currentNumber = 0; decimalPointPressed = false; } // if button pressed is divide if (buttonText == "/")

{ divideButtonPressed = true; initialNumber = displayNumber; currentNumber = 0; decimalPointPressed = false; } // if button pressed is multiply if (buttonText == "*") { multiplyButtonPressed = true; initialNumber = displayNumber; currentNumber = 0; decimalPointPressed = false; } // if button pressed is reciprocal if (buttonText == "1/x") { // call reciprocal method display.setText(reciprocal(displayNumber)); currentNumber = 0; decimalPointPressed = false; } // if button is pressed to change a sign if (buttonText == "+/-") { // call change sign method to change the sign display.setText(changeSign(displayNumber)); currentNumber = 0; decimalPointPressed = false; } // factorial button if (buttonText == "x!") { display.setText(factorial(displayNumber)); currentNumber = 0;

decimalPointPressed = false; } // power button if (buttonText == "x^n") { powerButtonPressed = true; initialNumber = displayNumber; currentNumber = 0; decimalPointPressed = false; } // now for scientific buttons if (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))); 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 displayed to degrees if (buttonText == "todeg") display.setText(Double.toString(Math.toDegrees(displayNumber))); // this will convert the numbers displayed to radians if (buttonText == "torad") { display.setText(Double.toString(Math.toRadians(displayNumber))); } if (buttonText == "Pi") { display.setText(Double.toString(Math.PI)); currentNumber =0; decimalPointPressed = false; } if (buttonText == "Round") { roundButtonPressed = true; } // check if decimal point is pressed if (buttonText == ".") { String displayedNumber = display.getText(); boolean decimalPointFound = false; int i; decimalPointPressed = true;

// check for decimal point for (i =0; i < displayedNumber.length(); ++i) { if(displayedNumber.charAt(i) == '.') { decimalPointFound = true; continue; } } if (!decimalPointFound) { decimalPlaces = 1; } } if(buttonText == "CA") { // set all buttons to false resetAllButtons(); 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 action

if (buttonText == "=") { currentNumber = 0; // if add button is pressed if(addButtonPressed) display.setText(Double.toString(initialNumber + displayNumber)); // if subtract button is pressed if(subtractButtonPressed) display.setText(Double.toString(initialNumber - displayNumber)); // if divide button is pressed if (divideButtonPressed) { // check if the divisor is zero if(displayNumber == 0) { MessageBox mb = new MessageBox ( fr, "Error ", true, "Cannot divide by zero."); mb.show(); } else display.setText(Double.toString(initialNumber/displayNumber)); } // if multiply button is pressed if(multiplyButtonPressed) display.setText(Double.toString(initialNumber * displayNumber)); // if power button is pressed if (powerButtonPressed) display.setText(power(initialNumber, displayNumber)); // set all the buttons to false resetAllButtons(); } 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 version 1.0 ", true, "Author:MEDS."); mb.show(); } } // end of action events public void itemStateChanged(ItemEvent ie) { if (ie.getItem() == "Basic") { 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 them if (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 visi // ble. if true display them if (!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) { 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 the reciprocal of 0"); mb.show();

} else num = 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"); 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:

Ex No: 8 IMPLEMENTATION OF FIBONACCI SERIES USING FRAMES AIM: To write a program to generate a fibonacci series using GUI environment on java using swing header. ALGORITHM:

1. Start the program and include the necessary packages. 2. Declare the class Fibonacci. 3. Inside the main method create the objects for the classes 4. Using li print the fibonacci values generated. 5. Create a frame by declaring frameshower class. 6. To print the values use the run method. 7. Now the required fibonacci values are printed.

8. Stop the program.

PROGRAM: import javax.swing.text.*; import javax.swing.*; import java.net.*; import java.io.*; import java.awt.*; class Fibonacci { public static void main(String[] args) { StringBuffer result=new StringBuffer("<html><body><h1>fibonacci sequence</h1><o/>"); long f1=0; long f2=1; for(int i=0;i<25;i++) { result.append("<li>"); result.append(f1); long temp=f2; f2=f1+f2; f1=temp; } result.append("</01></body></html>"); JEditorPane jep=new JEditorPane("text/html",result.toString()); jep.setEditable(false); JScrollPane scrollpane=new JScrollPane(jep); JFrame f=new JFrame("Fibonacci Series"); f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); f.setContentPane(scrollpane); f.setSize(200,650); EventQueue.invokeLater(new FrameShower(f)); } private static class FrameShower implements Runnable { private final Frame frame; FrameShower(Frame frame)

{ this.frame=frame; } public void run() { frame.setVisible(true); } } OUTPUT:

Ex No: 10 MULTITHREADED ECHO SERVER AND ECHO CLIENT AIM: To implement a program for the EchoServer and EchoClient using Multi Threading Concepts to send and receive information creation in java. ALGORITHM: 1. Start the program. 2. Include the necessary header files. 3. Create a class EchoServer and EchoClient and declare and define a required methods. 4. In main class , Create the socket connection to the EchoServer and Create the streams to send and receive information Print the result. 5. Obtain the input stream and the output stream for the socket . To encapsulate them with a BufferedReader and a PrintWriter. 6. Stop the execution. Program : EchoServer.java : /**Program for Client *@version 1.0 */ import java.net.*; import java.io.*; // A client for our multithreaded EchoServer. public class EchoClient {

public static void main(String[] args) { // First parameter has to be machine name if(args.length == 0) { System.out.println("Usage : EchoClient <serverName>"); return; } Socket s = null; // Create the socket connection to the EchoServer. try { s = new Socket(args[0], 12111); } catch(UnknownHostException uhe) { // Host unreachable System.out.println("Unknown Host :" + args[0]); s = null; } catch(IOException ioe) { // Cannot connect to port on given host 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 { // Create the streams to send and receive information in = new BufferedReader(new InputStreamReader(s.getInputStream())); out = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));

// Since this is the client, we will initiate the talking. // Send a string. out.println("Hello"); out.flush(); // receive the reply. System.out.println("Server Says : " + in.readLine()); // Send a string. out.println("This"); out.flush(); // receive a reply. System.out.println("Server Says : " + in.readLine()); // Send a string. out.println("is"); out.flush(); // receive a reply. System.out.println("Server Says : " + in.readLine()); // Send a string. out.println("a"); out.flush(); // receive a reply. System.out.println("Server Says : " + in.readLine()); // Send a string. out.println("Test"); out.flush(); // receive a reply. System.out.println("Server Says : " + in.readLine()); // Send the special string to tell server to quit. out.println("Quit"); out.flush(); } catch(IOException ioe) { System.out.println("Exception during communication. Server probably closed connection."); } finally {

try { // Close the streams out.close(); in.close(); // Close the socket before quitting s.close(); } catch(Exception e) { e.printStackTrace(); } } } } EchoClient.java : /**Program for Server *@version 1.0 */ import java.net.*; import java.io.*; public class EchoServer { ServerSocket m_ServerSocket;

public EchoServer() { try { // Create the server socket. 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.....");

// successfully created Server Socket. Now wait for connections. int id = 0; while(true) { try { // Accept incoming connections. Socket clientSocket = m_ServerSocket.accept(); // accept() will block until a client connects to the server. // If execution reaches this point, then it means that a client // socket has been accepted. // Start a service thread 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)

{ m_clientSocket = s; m_clientID = clientID; } public void run() { // Obtain the input stream and the output stream for the socket // To encapsulate them with a BufferedReader // and a PrintWriter. BufferedReader in = null; PrintWriter out = null; // Print out details of this connection 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())); // Run in a loop until m_bRunThread is set to false while(m_bRunThread) { // read incoming stream String clientCommand = in.readLine(); System.out.println("Client Says :" + clientCommand); if(clientCommand.equalsIgnoreCase("quit")) { // Special command. Quit this thread m_bRunThread = false; System.out.print("Stopping client thread for client : " + m_clientID); } else { // Echo it back to the client.

out.println(clientCommand); out.flush(); } } } catch(Exception e) { e.printStackTrace(); } finally { // Clean up try { in.close(); out.close(); m_clientSocket.close(); System.out.println("...Stopped"); } catch(IOException ioe) { ioe.printStackTrace(); } } } } } OUTPUT : EchoServer.java C:\Program Files\Java \jdk1.6.0\bin > java EchoServer Listening for clients .. Accepting Clients : ID 0 : Address localhost Client Says : Hello Client Says : is Client Says : a Client Says : Test Client Says : Quit Stopping client thread for client : 0.. Stopped Accepting Clients : ID 1 : Address localhost Client Says : Hello

Client Says : is Client Says : a Client Says : Test Client Says : Quit Stopping client thread for client : 0.. Stopped EchoClient.java : C:\Program Files\Java \jdk1.6.0\bin > java EchoClient localhost Server Says : Hello Server Says : is Server Says : a Server Says : Test C:\Program Files\Java \jdk1.6.0\bin > java EchoClient localhost Server Says : Hello Server Says : is Server Says : a Server Says : Test C:\Program Files\Java \jdk1.6.0\bin > java EchoClient localhost Server Says : Hello Server Says : is Server Says : a Server Says : Test

Das könnte Ihnen auch gefallen