PP Lab

1.palindrome

import java.util.Stack;

public class PalindromeTest {

    public static void main(String[] args) {

        String input = “test”;
        Stack<Character> stack = new Stack<Character>();

        for (int i = 0; i < input.length(); i++) {
            stack.push(input.charAt(i));
        }

        String reverseInput = “”;

        while (!stack.isEmpty()) {
            reverseInput += stack.pop();
        }

        if (input.equals(reverseInput))
            System.out.println(“Yo! that is a palindrome.”);
        else
            System.out.println(“No! that isn’t a palindrome.”);

    }
}

2.Database

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”); // custo is the DSN Name
stat = conn.createStatement();
res = stat.executeQuery(“Select * from Customers”); // Customers is the table name
res.next();
}
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(1));
name.setText(res.getString(2));
}
catch(Exception e) {}
}
class WIN extends WindowAdapter
{
public void windowClosing(WindowEvent w)
{
JOptionPane jop = new JOptionPane();
jop.showMessageDialog(null,”Database”,”Thanks”,JOptionPane.QUESTION_MESSAGE);
}
} //end of WIN class
}//end of Datas class

3. concurrent

import java.sql.*;
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:cust”);
}
catch(Exception e)
{
System.out.println(“connection error”);
}
}
void myput()
{
try
{
stmt=con.createStatement();
rs=stmt.executeQuery(“SELECT * FROM cust1”);
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[])
{
Ja j=new Ja();
j.myput();
}
}

OUTPUT:

D: Javajdk1.5.0_03bin>javac Ja.java
D: Javajdk1.5.0_03bin>java prog1

1   10   JAVA

2   20   C++

3   30   C#

4. count word repeat

import java.util.*;

class CountRepeat
{

 public static void main(String args[])
 {

 Scanner s=new Scanner(System.in);

 String st=s.nextLine();

 String find=s.nextLine();

 int count=0;

 int k=0;

  for(int i=0;i<st.length();i++)
  {

 
 
  k=st.toLowerCase().indexOf(find.toLowerCase(),k+find.length());

  System.out.println(k);

 
   if(k==-1) break; else count++;

  }

 System.out.println(“The string occurred “+count+” times”);

 }

}

5. encrypt decrypt

mport java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.spec.SecretKeySpec;

public class FileEncryptor{
   
    private String algo;
    private File file;

    public FileEncryptor(String algo,String path) {
     this.algo=algo; //setting algo
     this.file=new File(path); //settong file
    }
   
     public void encrypt() throws Exception{
         //opening streams
         FileInputStream fis =new FileInputStream(file);
         file=new File(file.getAbsolutePath()+”.enc”);
         FileOutputStream fos =new FileOutputStream(file);
         //generating key
         byte k[] = “HignDlPs”.getBytes();  
         SecretKeySpec key = new SecretKeySpec(k,algo.split(“/”)[0]);
         //creating and initialising cipher and cipher streams
         Cipher encrypt =  Cipher.getInstance(algo);
         encrypt.init(Cipher.ENCRYPT_MODE, key);
         CipherOutputStream cout=new CipherOutputStream(fos, encrypt);
       
         byte[] buf = new byte[1024];
         int read;
         while((read=fis.read(buf))!=-1)  //reading data
             cout.write(buf,0,read);  //writing encrypted data
         //closing streams
         fis.close();
         cout.flush();
         cout.close();
     }
   
     public void decrypt() throws Exception{
         //opening streams
         FileInputStream fis =new FileInputStream(file);
         file=new File(file.getAbsolutePath()+”.dec”);
         FileOutputStream fos =new FileOutputStream(file);              
         //generating same key
         byte k[] = “HignDlPs”.getBytes();  
         SecretKeySpec key = new SecretKeySpec(k,algo.split(“/”)[0]);
         //creating and initialising cipher and cipher streams
         Cipher decrypt =  Cipher.getInstance(algo);
         decrypt.init(Cipher.DECRYPT_MODE, key);
         CipherInputStream cin=new CipherInputStream(fis, decrypt);
             
         byte[] buf = new byte[1024];
         int read=0;
         while((read=cin.read(buf))!=-1)  //reading encrypted data
              fos.write(buf,0,read);  //writing decrypted data
         //closing streams
         cin.close();
         fos.flush();
         fos.close();
     }
   
     public static void main (String[] args)throws Exception {
         new FileEncryptor(“DES/ECB/PKCS5Padding”,”sample.txt”).encrypt();
         new FileEncryptor(“DES/ECB/PKCS5Padding”,”sample.txt.enc”).decrypt();
  }
}

6. insert delete record student

import java.util.*;
import java.util.Scanner;
/** * * @author Hira */publicclass SP10BSB013 {
      static  List<Integer> l=new ArrayList<Integer>();
    /**     * @param args the command line arguments     */publicstaticvoid main(String[] args) {
        Scanner in=new Scanner(System.in);
     boolean y=true;
     do{  
         System.out.println(“Enter 1 to add a no.(non zero) in listn2 to edit no.n3 to search”);
         System.out.println(“4 to deleten5 to check total no.n6 to print listn7 to exit”);
         System.out.println(“enter your choice”);
         int choice=in.nextInt();
         switch(choice)
         {
            case 1:
                insert();
                break;
            case 2:
                edit();
                break;
            case 3:
                search();
                break;
            case 4:
                delete();
                break;
            case 5:
                total();
                break;
            case 6:
                print();
                break;
            case 7:
                toexit();
                break;
            default:
                System.out.println(“bad input”);
                break;
        }
        System.out.println(“want to process more? y/n”);
        String x=in.next();
        char ch=x.charAt(0);
        if( ch==’n’)
            y=false;
    }
    while(y!=false);
 
    }
   
    //*************************************************************************************staticpublicvoid insert(){
     
     
       Scanner in=new Scanner(System.in);
       
        boolean y=true;
       do{
            System.out.println(“enter no to add in list”);
            int num=in.nextInt();
            if(num==0)
                System.out.println(“0 is not alowed”);
            else
                l.add(num);
            System.out.println(“want to insert more?y/n”);
            String x=in.next();
            char ch=x.charAt(0);
            if( ch==’n’)
                y=false;
         }
       while(y!=false);
   }
 
  //*************************************************************************************8 staticpublicvoid print(){
     
     
       if(l.isEmpty())
           System.out.println(“list is empty “);
       else
            System.out.println(“members of lists are:”);
            for(int i=0 ; i<l.size();i++)
                System.out.println(“index “+i+” : “+ l.get(i)+” “);
     
   }
 
   //********************************************************************************staticpublicvoid search(){
     
       //List<Integer> I=new ArrayList<Integer>();
       System.out.println(“enter no to search”);
       Scanner in=new Scanner(System.in);
     
       int num=in.nextInt();
       for(int i=0;i<l.size();i++){
           if(l.get(i)==num)
                System.out.println(num+” is  PRESENT at Index “+i);
       }
       
       if(l.lastIndexOf(num)==-1)
               System.out.println(num+” is NOT PRESENT”);
   }

   //*****************************************************************************8staticpublicvoid edit(){
     
     
       Scanner in=new Scanner(System.in);
       int num1,num2;
       System.out.println(“enter no you want to add”);
       num2=in.nextInt();
       if(num2==0)
             System.out.println(“0 is not alowed”);
       else{
             try{
                System.out.println(“enter position you want to edit”);
                num1=in.nextInt();
                l.set(num1, num2);
             }catch(IndexOutOfBoundsException e){
                    System.err.println(“caught IndexOutOfBoundsException: specified position is empty “+e.getMessage());
               }
     
          }
   }
 
 
    //************************************************************************************************8staticpublicvoid delete(){
       
       
        Scanner in=new Scanner(System.in);
        System.out.println(“enter position you want to delete”);
        int num=in.nextInt();
        l.remove(num);
       
    }
   
   
     //***********************************************************************88staticpublicvoid total(){
       
       
        System.out.println(“total no. in list are “+ l.size());
    }
   
    //******************************************************************************staticpublicvoid toexit(){
       
        System.exit(0);
    }
}

7. merge file

input file:
            input1.txt

Ram is a good boy

         input2.txt

He is Very poor

output file:
         output.txt

Ram is a good boy
He is very poor

7. CombineTwoFile.java

package com.test;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

public class CombineTwoFile
{
       public static void main(String[] args) throws IOException
       {    
       ArrayList<String> list = new ArrayList<String>();
       try
       {
       BufferedReader br = new BufferedReader(new FileReader( “input1.txt”));
         BufferedReader r = new BufferedReader(new FileReader( “input2.txt”));
            String s1 =null;
            String s2 = null;
         
                         while ((s1 = br.readLine()) != null)
                         {                        
                                        list.add(s1);      
                         }
                         while((s2 = r.readLine()) != null)
                         {  
                                        list.add(s2);  
                         }
       }
        catch (IOException e)
          {
            e.printStackTrace();
          }
     
           BufferedWriter writer=null;
           writer = new BufferedWriter(new FileWriter(“output.txt”));
            String listWord;            
                   for (int i = 0; i< list.size(); i++)
                  {
                        listWord = list.get(i);
                       writer.write(listWord);
                       writer.write(“n”);
                  }
                           System.out.println(“complited”);
                           writer.close();  
        }
    }

8.  sum of the series S=1+x+x2+x3+…………+xn

import java.util.Scanner;
public class sumseries
{
    int num,limit;     //instance variables
    public sumseries() //default constructor, initializes both variables to 0
    {
        num=0;
        limit=0;
    }
    public void getlimit(int n,int l) //method, assigns parameter values to variables
    {
        num=n;
        limit=l;
    }
   
    public int findpow(int x,int p)  //method, returns power value of number
    {
    int value=1;
        for(int i=0;i<p;i++)
        {
            value*=x;
        }
        return value;   //returning value
    }
   
    public void findsumseries()  //method, finds sum of the series
    {
        int sum=0;
        for(int i=0;i<limit;i++)
        {
            sum+=findpow(num,i);
        }
        System.out.println(“Sum of the series= “+sum);
    }
   
    public static void main()
    {
        sumseries ob=new sumseries();   //creating object of class sumseries
        Scanner in=new Scanner(System.in);  //creating object of class Scanner
        System.out.println(“Enetr the number”);
        int num=in.nextInt();               //inputting value
        System.out.println(“Enetr the limit”);
        int limit=in.nextInt();             //inputting value
        ob.getlimit(num,limit);             //calling method
        ob.findsumseries();                 //calling method
    }
}

OUTPUT:
Enetr the number
3
Enetr the limit
3
Sum of the series= 13

9. add 3×3 matrix

import java.lang.*;
import java.io.*;
class Matrix
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print(“enter no of rows”);
int m=Integer.parseInt(br.readLine());
System.out.print(“enter no of columns”);
int n=Integer.parseInt(br.readLine());
int a[][]=new int[m][n];
int i,j,k;
{
for( i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
a[i][j]=Integer.parseInt(br.readLine());
}
}
System.out.print(“enter no of rows”);
int p=Integer.parseInt(br.readLine());
System.out.print(“enter no of columns”);
int q=Integer.parseInt(br.readLine());
int b[][]=new int[p][q];
{
for( i=0;i<p;i++)
{
for( j=0;j<q;j++)
{
b[i][j]=Integer.parseInt(br.readLine());
}
}
}
int c[][]=new int[m][i];
if(n==p)
{
for( i=0;i<m;i++)
{
for( j=0;j<q;j++)
{
c[i][j]=0;
for( k=0;k<p;k++)
{
c[i][j]=c[i][j]+(a[i][k]*b[k][j]);
}
}
}
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
System.out.println(c[i][j]);
}
}
}
}
}
}

10. read & edit file

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {      
        try {
            File f = new File(“people.ser”);
            Scanner sc = new Scanner(f);

            List<Person> people = new ArrayList<Person>();

            while(sc.hasNextLine()){
                String line = sc.nextLine();
                String[] details = line.split(“:”);
                String gender = details[0];
                String name = details[1];
                int age = Integer.parseInt(details[2]);
                Person p = new Person(gender, name, age);
                people.add(p);
            }

            for(Person p: people){
                System.out.println(p.toString());
            }

        } catch (FileNotFoundException e) {        
            e.printStackTrace();
        }
    }
}

class Person{

    private String gender;
    private String name;
    private int age;

    public Person(String gender, String name, int age){
        this.gender = gender;
        this.setName(name);
        this.age = age;
    }

    /**
     * @return the gender
     */
public String getGender() {
    return gender;
}

/**
 * @param gender the gender to set
 */
public void setGender(String gender) {
    this.gender = gender;
}

/**
 * @param name the name to set
 */
public void setName(String name) {
    this.name = name;
}

/**
 * @return the name
 */
public String getName() {
    return name;
}

/**
 * @return the age
 */
public int getAge() {
    return age;
}

/**
 * @param age the age to set
 */
public void setAge(int age) {
    this.age = age;
}

public String toString(){
    return this.gender + ” ” + this.name + ” ” + this.age;
}

}

11. thread priority

public class Main extends Object {
   private static Runnable makeRunnable() {
      Runnable r = new Runnable() {
         public void run() {
            for (int i = 0; i < 5; i++) {
               Thread t = Thread.currentThread();
               System.out.println(“in run() – priority=”
               + t.getPriority()+ “, name=” + t.getName());
               try {
                  Thread.sleep(2000);
               }
               catch (InterruptedException x) {
               }
            }
         }
      };
      return r;
   }
   public static void main(String[] args) {
      System.out.println(“in main() – Thread.currentThread().
      getPriority()=” + Thread.currentThread().getPriority());
      System.out.println(“in main() – Thread.currentThread()
      .getName()=”+ Thread.currentThread().getName());
      Thread threadA = new Thread(makeRunnable(), “threadA”);
      threadA.start();
      try {
         Thread.sleep(3000);
      }
      catch (InterruptedException x) {
      }
      System.out.println(“in main() – threadA.getPriority()=”
      + threadA.getPriority());
   }
}

12. sort number

import java.io.*;
import java.util.*;
public class a13 {

        public static void main(String args[])throws IOException
        {
                 Scanner br = new Scanner (System.in);
                 System.out.println(“Enter the no. of elements”);

                 int n = br.nextInt();
                 int arr[]=new int[n];
                System.out.println(“Enter the elements”);
                for(int i=0;i<n;i++)
                arr[i] = br.nextInt();

                for(int i=0;i<n;i++)
                {
                        for(int j=0;j<n-1;j++)
                        {
                                if(arr[j]>arr[j+1]){
                                                     int temp=arr[j];
                                                     arr[j]=arr[j+1];
                                                     arr[j+1]=temp;
                                         }
                        }
                 }System.out.println(“nsorted array”);
                 System.out.println(“n”);
                for(int i=0;i<n;i++)

                System.out.println(arr[i]);
        }
 }
OUTPUT:
Enter the no. of elements
4
Enter the elements
2
1
53
22

sorted array
1
2
22
53

13. producer consumer

import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Java program to solve Producer Consumer problem using wait and notify
 * method in Java. Producer Consumer is also a popular concurrency design pattern.
 *
 * @author Javin Paul
 */
public class ProducerConsumerSolution {

    public static void main(String args[]) {
        Vector sharedQueue = new Vector();
        int size = 4;
        Thread prodThread = new Thread(new Producer(sharedQueue, size), “Producer”);
        Thread consThread = new Thread(new Consumer(sharedQueue, size), “Consumer”);
        prodThread.start();
        consThread.start();
    }
}

class Producer implements Runnable {

    private final Vector sharedQueue;
    private final int SIZE;

    public Producer(Vector sharedQueue, int size) {
        this.sharedQueue = sharedQueue;
        this.SIZE = size;
    }

    @Override
    public void run() {
        for (int i = 0; i < 7; i++) {
            System.out.println(“Produced: ” + i);
            try {
                produce(i);
            } catch (InterruptedException ex) {
                Logger.getLogger(Producer.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    }

    private void produce(int i) throws InterruptedException {

        //wait if queue is full
        while (sharedQueue.size() == SIZE) {
            synchronized (sharedQueue) {
                System.out.println(“Queue is full ” + Thread.currentThread().getName()
                                    + ” is waiting , size: ” + sharedQueue.size());

                sharedQueue.wait();
            }
        }

        //producing element and notify consumers
        synchronized (sharedQueue) {
            sharedQueue.add(i);
            sharedQueue.notifyAll();
        }
    }
}

class Consumer implements Runnable {

    private final Vector sharedQueue;
    private final int SIZE;

    public Consumer(Vector sharedQueue, int size) {
        this.sharedQueue = sharedQueue;
        this.SIZE = size;
    }

    @Override
    public void run() {
        while (true) {
            try {
                System.out.println(“Consumed: ” + consume());
                Thread.sleep(50);
            } catch (InterruptedException ex) {
                Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    }

    private int consume() throws InterruptedException {
        //wait if queue is empty
        while (sharedQueue.isEmpty()) {
            synchronized (sharedQueue) {
                System.out.println(“Queue is empty ” + Thread.currentThread().getName()
                                    + ” is waiting , size: ” + sharedQueue.size());

                sharedQueue.wait();
            }
        }

        //Otherwise consume element and notify waiting producer
        synchronized (sharedQueue) {
            sharedQueue.notifyAll();
            return (Integer) sharedQueue.remove(0);
        }
    }
}

Output:
Produced: 0
Queue is empty Consumer is waiting , size: 0
Produced: 1
Consumed: 0
Produced: 2
Produced: 3
Produced: 4
Produced: 5
Queue is full Producer is waiting , size: 4
Consumed: 1
Produced: 6
Queue is full Producer is waiting , size: 4
Consumed: 2
Consumed: 3
Consumed: 4
Consumed: 5
Consumed: 6
Queue is empty Consumer is waiting , size: 0

14. text in 3 color

import java.awt.*;
import jpb.*;

public class DisplayText {
  public static void main(String[] args) {
    // Create drawable frame
    DrawableFrame df = new DrawableFrame(“Display Text”);
    df.show();
    df.setSize(210, 85);

    // Obtain graphics context
    Graphics g = df.getGraphicsContext();

    // Display “Monospaced Bold”
    g.setColor(Color.red);
    g.setFont(new Font(“Monospaced”, Font.BOLD, 20));
    g.drawString(“Monospaced Bold”, 15, 25);

    // Display “SansSerif Italic”
    g.setColor(Color.green);
    g.setFont(new Font(“SansSerif”, Font.ITALIC, 20));
    g.drawString(“SansSerif Italic”, 15, 50);

    // Display “Serif Plain”
    g.setColor(Color.blue);
    g.setFont(new Font(“Serif”, Font.PLAIN, 20));
    g.drawString(“Serif Plain”, 15, 75);

    // Repaint frame
    df.repaint();
  }
}

15. client server chat

client-server chat
// TCP Chat Server–tcpchatserver.java
import java.io.*;
import java.net.*;
class tcpchatserver
{
public static void main(String args[])throws Exception
{
PrintWriter toClient;
BufferedReader fromUser, fromClient;
try
{
ServerSocket Srv = new ServerSocket(5555);
System.out.print(“nServer startedn”);
Socket Clt = Srv.accept();
System.out.println(“Client connected”);
toClient = new PrintWriter(new BufferedWriter(new
OutputStreamWriter(Clt.getOutputStream())), true);
fromClient = new BufferedReader(new
InputStreamReader(Clt.getInputStream()));
fromUser = new BufferedReader(new
InputStreamReader(System.in));
String CltMsg, SrvMsg;
10
while(true)
{
CltMsg= fromClient.readLine();
if(CltMsg.equals(“end”))
break;
else
{
System.out.println(“nServer <<< ” +CltMsg);
System.out.print(“Message to Client : “);
SrvMsg = fromUser.readLine();
toClient.println(SrvMsg);
}
}
System.out.println(“nClient Disconnected”);
fromClient.close();
toClient.close();
fromUser.close();
Clt.close();
Srv.close();
}
catch (Exception E)
{
System.out.println(E.getMessage());
11
}
}
}

// TCP Chat Client–tcpchatclient.java
import java.io.*;
import java.net.*;
class tcpchatclient
{
public static void main(String args[])throws Exception
{
Socket Clt;
PrintWriter toServer;
BufferedReader fromUser, fromServer;
try
{
if (args.length > 1)
{
System.out.println(“Usage: java hostipaddr”);
System.exit(-1);
}
if (args.length == 0)
Clt = new Socket(InetAddress.getLocalHost(),5555);
else
12
Clt = new Socket(InetAddress.getByName(args[0]),5555);
toServer = new PrintWriter(new BufferedWriter(new
OutputStreamWriter(Clt.getOutputStream())), true);
fromServer = new BufferedReader(new
InputStreamReader(Clt.getInputStream()));
fromUser = new BufferedReader(new
InputStreamReader(System.in));
String CltMsg, SrvMsg;
System.out.println(“Type “end” to Quit”);
while (true)
{
System.out.print(“nMessage to Server : “);
CltMsg = fromUser.readLine();
toServer.println(CltMsg);
if (CltMsg.equals(“end”))
break;
SrvMsg = fromServer.readLine();
System.out.println(“Client <<< ” + SrvMsg);
}
}
catch(Exception E)
{
System.out.println(E.getMessage());
13
}
}
}

16. calc

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.lang.*;
public class Calculator
{
public static void main(String[] args)
{
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);
pack();
}
}
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(6,5));
     
addButton(“7”, insert);
addButton(“8”, insert);
addButton(“9”, insert);
addButton(“/”, command);
addButton(“CE”, command);

addButton(“4”, insert);
addButton(“5”, insert);
addButton(“6”, insert);
addButton(“*”, command);
addButton(“m+”, command);

addButton(“1”, insert);
addButton(“2”, insert);
addButton(“3”, insert);
addButton(“-“, command);
addButton(“m-“, command);

addButton(“0”, insert);
addButton(“.”, insert);
addButton(“+/-“, command);
addButton(“+”, command);
addButton(“n!”, command);

addButton(“pow”, command);
addButton(“1/x”, insert);
addButton(“SQRT”, insert);
addButton(“log”, insert);
addButton(“%”, command);

addButton(“sin”, insert);
addButton(“cos”, insert);
addButton(“tan”, insert);
addButton(“x2”, insert);
addButton(“=”, 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==true)
{
display.setText(“”);
start = false;
}
if(input.equals(“1/x”))
display.setText(“”+1/Double.parseDouble(display.getText()));
else
if(input.equals(“SQRT”))
display.setText(“”+Math.sqrt(Double.parseDouble(display.getText())));

else
if(input.equals(“log”))
display.setText(“”+Math.log(Double.parseDouble(display.getText())));

else
if(input.equals(“x2”))
display.setText(“”+Double.parseDouble(display.getText())* Double.parseDouble(display.getText()));

else
if(input.equals(“sin”))
{
Double angle=Double.parseDouble(display.getText())*2.0*Math.PI/360.0;
display.setText(“”+Math.sin(angle));
}
else if(input.equals(“cos”))
{
Double angle=Double.parseDouble(display.getText())*2.0*Math.PI/360.0;
display.setText(“”+Math.cos(angle));
}
else
if(input.equals(“tan”))
{
Double angle=Double.parseDouble(display.getText())*2.0*Math.PI/360.0;
display.setText(“”+Math.tan(angle));
}
else
display.setText(display.getText() + input);
}
}
private class CommandAction implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String command = event.getActionCommand();

if (start==true)
{
if (command.equals(“-“))
{
display.setText(command);
start = false;
}
else
lastCommand = command;
}
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(“CE”)) result = 0.0;
else if (lastCommand.equals(“m+”)) result = result;
else if (lastCommand.equals(“m-“)) result = 0.0;
else if (lastCommand.equals(“pow”))
{
double powval=1.0;
for(double i=0.0;i<x;i++)
powval*=result;
result=powval;
}
display.setText(“”+ result);
}
private JButton display;
private JPanel panel;
private double result;
private String lastCommand;
private boolean start;
}