Prime Number Generation - Java AWT Example - Internet & Web Programming Lab

Program:
import java.awt.*;
import java.awt.event.*;

class ex3 extends Frame implements ActionListener
{
 Label l1;
 TextField t1;
 Button b1,b2;
 List lt;
 ex3()
 {
   super("Prime number generation");
   setLayout(null);
   setSize(500,400);
   setVisible(true);
   l1=new Label("Enter the limit:");
   t1=new TextField();
   b1=new Button("Find");
   b2=new Button("Clear");
   lt=new List();
   l1.setBounds(100,50,120,20);
   add(l1);
   t1.setBounds(250,50,50,20);
   add(t1);
   lt.setBounds(100,90,100,100);
   add(lt);
   b1.setBounds(200,150,50,20);
   add(b1);
   b2.setBounds(270,150,50,20);
   add(b2);
   b1.addActionListener(this);
   b2.addActionListener(this);
   addWindowListener(new WindowAdapter()
   {
    public void windowClosing(WindowEvent we)
    {
     System.exit(0);
    }
   });
 }

 public void actionPerformed(ActionEvent ae)
 {
  int n;
  if(ae.getSource()==b1)
  {
   n=Integer.parseInt(t1.getText().trim());
       int flag=0;
       for(int i=2;i<=n;i++)
       {
        flag=0;
        for(int j=2;j<=i/2;j++)
        {
         if(i%j==0)
         {
          flag=1;
          break;
         }
        }
        if(flag==0)
          lt.add(Integer.toString(i));
       }
  }
  else
  {
   t1.setText(null);
   lt.removeAll();
   t1.requestFocus();
  }
 }



 public static void main(String s[])
 {
  ex3 ob=new ex3();
 }
}


Output:

nn@linuxmint ~/Desktop/java 7 $ javac ex3.java
nn@linuxmint ~/Desktop/java 7 $ java ex3
nn@linuxmint ~/Desktop/java 7 $


1 comment:

Related Posts Plugin for WordPress, Blogger...