Coding Lab - TechOnTechnology

Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

JAVA Swing Program to implement desktop calculator.




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

/**
 * In this applet, the user can type in two real numbers.  The
 * user can click on buttons labeled +, - , *, and / to perform
 * basic arithmetic operations on the numbers.  When the user
 * clicks on a button the answer is displayed.  The applet
 * should be about 300 by 160 pixels.
 * Note that this class also contains a main() routine, so that
 * it can be run as a stand-alone application.  When it is run
 * in this way, it opens a window that shows that same panel that
 * is used in the applet version.
 */
public class SimpleCalc extends JApplet {
  
   /**
    * This main() routine makes it possible to run the SimpleCalc1 class
    * as a stand-alone application.  This routine just opens a window that
    * uses an object of type CalcPanel as its content pane, where CalcPanel
    * is the nested class defined below.
    */
   public static void main(String[] args) {
      JFrame window = new JFrame("Simple Calculator");
      CalcPanel content = new CalcPanel();
      window.setContentPane(content);
      window.pack();  // Sizes window to preferred size of contents.
      window.setLocation(100,100);
      window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
      window.setVisible(true);
   }
  
  
   /**
    * The init() method for the applet just sets the content pane
    * of the applet to be an object of type CalcPanel, where CalcPanel
    * is the nested class defined below.
    */
   public void init() {
      setContentPane( new CalcPanel() );
   }
  
  
   public static class CalcPanel extends JPanel implements ActionListener {
     
      private JTextField xInput, yInput;  // Input boxes for the numbers.
     
        private JLabel answer;  // JLabel for displaying the answer, or an
                              //    error message if appropriate.
     
     
      public CalcPanel() {
                 
         /* Assign a background color to the panel and its
          content panel.  This color will show through in the gaps
          between components. */
        
         setBackground(Color.GRAY);
        
         /* Add an empty border around the panel, which will also
          * appear in the gray background color. */
        
         setBorder( BorderFactory.createEmptyBorder(5,5,5,5) );
        
         /* Create the input boxes, and make sure that the background
          color is white.  (They are likely to be white by default.) */
        
         xInput = new JTextField("0", 10);
         xInput.setBackground(Color.WHITE);
         yInput = new JTextField("0", 10);
         yInput.setBackground(Color.WHITE);
        
         /* Create panels to hold the input boxes and labels "x =" and
          "y = ".  These panels use the default FlowLayout layout manager. */
        
         JPanel xPanel = new JPanel();
         xPanel.add( new JLabel(" x = "));
         xPanel.add(xInput);
        
         JPanel yPanel = new JPanel();
         yPanel.add( new JLabel(" y = "));
         yPanel.add(yInput);
        
         /* Create a panel to hold the four buttons for the four
          operations.  A GridLayout is used so that the buttons
          will all have the same size and will fill the panel.
          The main panel servers as ActionListener for the buttons. */
        
         JPanel buttonPanel = new JPanel();
         buttonPanel.setLayout(new GridLayout(1,4));
        
         JButton plus = new JButton("+");
         plus.addActionListener(this);
         buttonPanel.add(plus);
        
         JButton minus = new JButton("-");
         minus.addActionListener(this);
         buttonPanel.add(minus);
        
         JButton times = new JButton("*");
         times.addActionListener(this);
         buttonPanel.add(times);
        
         JButton divide = new JButton("/");
         divide.addActionListener(this);
         buttonPanel.add(divide);
        
         /* Create the label for displaying the answer in red
          on a white background.  The label is set to be
          "opaque" to make sure that the white background
          is painted. */
        
         answer = new JLabel("x + y = 0", JLabel.CENTER);
         answer.setForeground(Color.red);
         answer.setBackground(Color.white);
         answer.setOpaque(true);
        
         /* Set up the layout for the main panel, using a GridLayout,
          and add all the components that have been created. */
        
         setLayout(new GridLayout(4,1,3,3));
         add(xPanel);
         add(yPanel);
         add(buttonPanel);
         add(answer);
        
         /* Try to give the input focus to xInput, which is the natural
          place for the user to start. */
        
         xInput.requestFocus();
        
      }  // end constructor
     
           
      /**
       * When the user clicks a button, get the numbers from the input boxes
       * and perform the operation indicated by the button.  Put the result in
       * the answer label.  If an error occurs, an error message is put in the label.
       */
      public void actionPerformed(ActionEvent evt) {
        
         double x, y;  // The numbers from the input boxes.
        
         /* Get a number from the xInput JTextField.  Use
          xInput.getText() to get its contents as a String.
          Convert this String to a double.  The try...catch
          statement will check for errors in the String.  If
          the string is not a legal number, the error message
          "Illegal data for x." is put into the answer and
          the actionPerformed() method ends. */
        
         try {
            String xStr = xInput.getText();
            x = Double.parseDouble(xStr);
         }
         catch (NumberFormatException e) {
            // The string xStr is not a legal number.
            answer.setText("Illegal data for x.");
            xInput.requestFocus();
            return;
         }
        
         /* Get a number from yInput in the same way. */
        
         try {
            String yStr = yInput.getText();
            y = Double.parseDouble(yStr);
         }
         catch (NumberFormatException e) {
            answer.setText("Illegal data for y.");
            yInput.requestFocus();
            return;
         }
        
         /* Perform the operation based on the action command
          from the button.  Note that division by zero produces
          an error message. */
        
         String op = evt.getActionCommand();
         if (op.equals("+"))
            answer.setText( "x + y = " + (x+y) );
         else if (op.equals("-"))
            answer.setText( "x - y = " + (x-y) );
         else if (op.equals("*"))
            answer.setText( "x * y = " + (x*y) );
         else if (op.equals("/")) {
            if (y == 0)
               answer.setText("Can't divide by zero!");
            else
               answer.setText( "x / y = " + (x/y) );
         }
        
      } // end actionPerformed()
     
   } // end nested class CalcPanel
  

}  // end class SimpleCalculator


HTML code to load Applet.
Make Sure that JAVA configured Properly.

<html>
<body>
<applet code=SimpleCalc.class width=300 height=200>
</applet>
</body>
</html>

Java Program to Demonstrates Multi Threadng Using Prime and Fibonacci Number Concepts.





Write a multi-threaded Java program to print all numbers below 100,000 that are both prime and fibonacci number (some examples are 2, 3, 5, 13, etc.). Design a thread that generates prime numbers below 100,000 and writes them into an array. Design another thread that generates fibonacci numbers and writes them to another array. The main thread should read both the arrays to identify numbers common to both. 


import java.io.*;
import java.io.PipedWriter;
import java.io.PipedReader;
class fibonacci extends Thread
{
            PipedWriter fw=new PipedWriter();
            public PipedWriter getwrite()
            {
                        return fw;
            }
            public void run()
            {
                        super.run();
                        fibo();
            }
            int f(int n)
            {
                        if(n<2)
                                    return n;
                                    else
                                                return f(n-1)+f(n-2);
            }
            void fibo()
            {
                        for(int i=2,fibv=0;(fibv=f(i))<100000;i++)
                        {
                                    try{
                                  
                                    fw.write(fibv);
                                    }
                                    catch(IOException e){
                                    }
                        }
            }
}
class receiver extends Thread
{
            PipedReader fibr,primer;
            public receiver(fibonacci fib,prime pr)throws IOException
            {
                        fibr=new PipedReader(fib.getwrite());
                        primer=new PipedReader(pr.getwrite());
            }
            public void run()
            {
                        int p=0,f=0;
                        try{
                      
                        p=primer.read();
                        f=fibr.read();
                        }
                        catch(IOException e)
                        {
                        }
                        while(true)
                        {
                                    try
                                                {
                                  
                                    if(p==f){
                                  
                                                System.out.println ("Match:"+p);
                                                p=primer.read();
                                                f=fibr.read();
                                    }
                                    else if(f<p)
                                                f=fibr.read();
                                                else
                                                            p=primer.read();
                        }catch(IOException e)
                        {System.exit(-1);
                        }
                        }
                      
            }
}
class prime extends Thread
{
            PipedWriter pw=new PipedWriter();
            public PipedWriter getwrite()
            {
                        return pw;
            }
            public void run()
            {
                        super.run();
                        prim();
            }
            public void prim()
            {
                        for(int i=2;i<100000;i++)
                        {
                                    if(isprime(i))
                                    {
                                                try{
                                                            pw.write(i);
                                                }
                                                catch(IOException e){
                                                }
                                    }
                        }
            }
            boolean isprime(int n)
            {
                        boolean p=true;
                        int s=(int)Math.sqrt(n);
                        for(int i=2;i<=s;i++)
                        {
                                    if(n%i==0)
                                                p=false;
                        }
                        return p;
            }
}
class fibprime
{
            public static void main (String[] args)throws IOException {
                        fibonacci fi=new fibonacci();
                        prime pri=new prime();
                        receiver r=new receiver(fi,pri);
                        fi.start();
                        pri.start();
                        r.start();
                      
}
}

Java GUI program to handle the various keyboard events for printable characters.




// Demonstrate some virtual key codes.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="KeyEvents" width=300 height=100>
</applet>
*/
public class KeyEvents extends Applet
implements KeyListener {
String msg = "";
int X = 10, Y = 20; // output coordinates
public void init() {
addKeyListener(this);
requestFocus(); // request input focus
}
public void keyPressed(KeyEvent ke) {
showStatus("Key Down");
int key = ke.getKeyCode();
switch(key) {
case KeyEvent.VK_F1:
msg += "<F1>";
break;
case KeyEvent.VK_F2:
msg += "<F2>";
break;
case KeyEvent.VK_F3:
msg += "<F3>";
break;
case KeyEvent.VK_PAGE_DOWN:
msg += "<PgDn>";
break;
case KeyEvent.VK_PAGE_UP:
msg += "<PgUp>";
break;
case KeyEvent.VK_LEFT:
msg += "<Left Arrow>";
break;
case KeyEvent.VK_RIGHT:
msg += "<Right Arrow>";
break;
}
repaint();
}
public void keyReleased(KeyEvent ke) {
showStatus("Key Up");
}
public void keyTyped(KeyEvent ke) {
msg += ke.getKeyChar();
repaint();
}
// Display keystrokes.
public void paint(Graphics g) {
g.drawString(msg, X, Y);
}
}

HTML File Code to load Applet.
Make Sure that Java Configured Properly.

<html>
<body>
<applet code=KeyEvents.class width=300 height=200>
</applet>
</body>
</html>

Java GUI program to handle the various mouse events.




// Demonstrate the mouse event handlers.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="MouseEvents" width=300 height=100>
</applet>
*/
public class MouseEvents extends Applet
implements MouseListener, MouseMotionListener {
String msg = "";
int mouseX = 0, mouseY = 0; // coordinates of mouse
public void init() {
addMouseListener(this);
addMouseMotionListener(this);
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse clicked.";
repaint();
}
// Handle mouse entered.
public void mouseEntered(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse entered.";
repaint();
}
// Handle mouse exited.
public void mouseExited(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse exited.";
repaint();
}
// Handle button pressed.
public void mousePressed(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Down";
repaint();
}
// Handle button released.
public void mouseReleased(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Up";
repaint();
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
repaint();
}
// Handle mouse moved.
public void mouseMoved(MouseEvent me) {
// show status
showStatus("Moving mouse at " + me.getX() + ", " + me.getY());
}
// Display msg in applet window at current X,Y location.
public void paint(Graphics g) {
g.drawString(msg, mouseX, mouseY);
}
}



HTML Code to Load Applet.
Make Sure that Java Configured properly.


<html>
<body>
<applet code=MouseEvents.class width=300 height=200>
</applet>
</body>
</html>

Java Program to implement Various Operations Using Student Concept.

 



Create a class Student with attributes roll no, name, age and course. Initialize values through parameterized constructor. If age of student is not in  between 15 and 21 then generate user-defined exception “AgeNotWithinRangeException”. If name contains numbers or special symbols raise exception “NameNotValidException”. Define the two exception classes.  

 
import java.io.*;

class AgeOutOfRangeException extends Exception{}

class NameNotValidException extends Exception{}

class Student
{
    int RollNo, Age,j,k=-1;
    String Name,Course;
    char ch[]={'!','@','#','$','%','^','&','*'};
    Student(int rno, String name, int age, String course)
    {
    try
    {
        RollNo = rno;
        Name = name;
        Age = age;
        Course = course;
        if(Age<15 || Age>21)
        throw new AgeOutOfRangeException();
        for(int i=0,j=0; i<Name.length() && j<ch.length ; i++,j++)
        if(Character.isDigit(Name.charAt(i))||(k!=Name.indexOf(ch[j])))
        throw new NameNotValidException();
    }
    catch(AgeOutOfRangeException e)
    {
        System.out.println("\nAGE NOT WITHIN RANGE !!!");
        System.exit(0);
    }
    catch(NameNotValidException e)
    {
        System.out.println("\nNAME IS NOT VALID !!!");
        System.exit(0);
    }
    }
    public void printData()
    {
        System.out.println("\nROLL NO :"+RollNo+"\n"+
        "NAME :"+Name+"\n"+
        "AGE :"+Age+"\n"+
        "COURSE  :"+Course);
    }
}
class StudentException
{
    public static void main(String args[]) throws Exception
    {
       
        DataInputStream in=new DataInputStream(System.in);

        System.out.print("\nENTER ROLL NO :");
        int rno=Integer.parseInt(in.readLine());
       
        System.out.print("ENTER NAME :");
        String sn=in.readLine();
       
        System.out.print("ENTER AGE :");
        int age=Integer.parseInt(in.readLine());
       
        System.out.print("ENTER COURSE :");
        String cn=in.readLine();
       
        Student s1 = new Student(rno,sn,age,cn);
       
        s1.printData();
    }
}a

Java program to implement Producer Consumer Program.




class Q
{
    int n;
    boolean valueset=false;
       synchronized int get()
       {
       if(!valueset)
       try
       {
          wait();
       }
      catch(InterruptedException e){
        System.out.println("Interrupted Exception cought !! ");
        }
        System.out.println("Get:"+n);
        valueset=false;
        notify();
        return n;
    }
    synchronized void put(int n)
    {
       if(valueset)
       try
       {
          wait();
       }
       catch(InterruptedException e){
                  System.out.println("Interrupt");
        }
     this.n=n;
     valueset=true;
    System.out.println("Put:"+n);
    notify();
    }

 }

class Producer implements Runnable
{
    Q q;
    Producer(Q q)
    {
        this.q=q;
        new Thread(this,"Producer").start();
    }
   public void run()
    {
        int i=0;
        while(true)
        {
         q.put(i++);
        }
    }
 }

class Consumer implements Runnable
{
   Q q;
   Consumer(Q q)
   {
        this.q=q;
        new Thread(this,"Consumer").start();
   }
   public void run()
   {
      while(true)
      {
          q.get();
      }
   }
}
class Producerconsumer
 {
    public static void main(String args[])
        {
          Q q=new Q();
        new Producer(q);
        new Consumer(q);
        System.out.println("Press Control plus c to stop");
        }
}

Java Program to do Following : Define a class called Time. Implement the following methods Add T1 and T2 ,Display the Time.




import java.io.*;
import java.lang.*;
class timedemo
{
    int hour,min,sec;
    timedemo(int x,int y,int z)
    {
        hour=x;
        min=y;
        sec=z;
    }
}
class time
{
public static timedemo add(timedemo t1,timedemo t2)
{
    int hour=t1.hour+t2.hour;
    int min=t1.min+t2.min;
    int sec=t1.sec+t2.sec;
    if ( sec>= 60)
    {
        sec=sec-60;
        min=min+1;
    }
    if(min>=60)
    {
        min=min-60;
        hour=hour+1;
    }
    if(hour>=12)
    {
        hour=hour-12;
    }
timedemo t3=new timedemo(hour,min,sec);
return (t3);
}
public static void display(timedemo t)
{
    System.out.println("TIME : "+t.hour+"hours :"+t.min+"minutes :"+t.sec+"seconds");
}
public static void main(String args[]) throws IOException
{
    int h,m,s;
    DataInputStream in=new DataInputStream(System.in);
   
        System.out.println("\nENTER TIME : ");
        System.out.println("\nENTER Ist [ T1 ] TIME [ HH:MM:SS ] : ");
        System.out.print("Hours : ");
        h = Integer.parseInt(in.readLine());
        System.out.print("Minutes : ");
        m = Integer.parseInt(in.readLine());
        System.out.print("Seconds : ");
        s = Integer.parseInt(in.readLine());
       
        timedemo t1=new timedemo(h,m,s);
       
        System.out.println("\nENTER IInd [ T2 ] TIME [ HH:MM:SS ] : ");
        System.out.print("Hours : ");
        h = Integer.parseInt(in.readLine());
        System.out.print("Minutes : ");
        m = Integer.parseInt(in.readLine());
        System.out.print("Seconds : ");
        s = Integer.parseInt(in.readLine());

        timedemo t2=new timedemo(h,m,s);
   
        timedemo t3;
        t3=add(t1,t2);    // calling add method to add two time
        System.out.println("\nIst ");display(t1);      // calling display method
        System.out.println("\nIInd ");display(t2);
        System.out.println("\nI+II ");display(t3);
}
}

Java recursive program to compute the determinant of a matrix.




import java.io.*;
import java.lang.*;
class Matrixdet{

public static double determinent(int b[][],int m)
    {
        int c[][]=new int[m][m];

        int i,j,k;
        double sum=0;
        if(m==1) { sum=b[0][0];  }
        else if(m==2)
        {
            sum=(( b[0][0]*b[1][1] ) - ( b[0][1]*b[1][0] ));
        }
        else
        {
            for(int p=0;p<m;p++)
            {
              int h=0;k=0;
              for(i=1;i<m;i++)
              {
                for(j=0;j<m;j++)
                    {
                     if(j==p)
                     continue;
                     c[h][k]=b[i][j];
                     k++;
                     if(k==m-1)
                      {
                         h++;
                         k=0;
                      }
                    }
              }
            sum=sum+b[0][p]*Math.pow((-1),p)*determinent(c,m-1);
            }
        }
        return sum;
    }

        public static void main(String[] args) throws IOException{
            DataInputStream in=new DataInputStream(System.in);
            System.out.println("\nMATRIX  :");
            System.out.print("\nENTER THE ORDER OF THE MATRIX YOU HAVE : ");
            int order=Integer.parseInt(in.readLine());
           
            int[][] A = new int[order][order];
           
            System.out.println("\nENTER ELEMENTS OF MATRIX : ");
            for (int i=0 ; i < order ; i++)
            for  (int j=0 ; j < order ; j++)
            {
            A[i][j] = Integer.parseInt(in.readLine());
            }
           
            System.out.println("MATRIX : ");
                    for (int i=0 ; i < order ; i++)
                    {       System.out.println();
                            for  (int j=0 ; j < order ; j++)
                              {
                            System.out.print(A[i][j]+" ");
                              }
                    }
            System.out.println();
            System.out.println("\nDETERMINENT OF MATRIX : "+ determinent(A,order));
        }
}

Java Program to implement the different operations on the Matrix.




import java.io.*;
class Matrix{
        public static void main(String[] args) throws IOException{
            DataInputStream in=new DataInputStream(System.in);
            System.out.println("\nMATRIX  :");
            System.out.print("\nENTER THE ORDER OF THE MATRIX YOU HAVE : ");
            int order=Integer.parseInt(in.readLine());
           
            int[][] A = new int[order][order];
            int[][] B = new int[order][order];
            int[][] C = new int[order][order];
           
            System.out.println("ENTER ELEMENTS OF Ist MATRIX : ");
            for (int i=0 ; i < order ; i++)
            for  (int j=0 ; j < order ; j++){
            A[i][j] = Integer.parseInt(in.readLine());
            }
           
            System.out.println("ENTER ELEMENTS OF IIst MATRIX : ");
            for (int i=0 ; i < order ; i++)
            for  (int j=0 ; j < order ; j++){
            B[i][j] = Integer.parseInt(in.readLine());
            }
           
            System.out.println("Matrix I: ");
                    for (int i=0 ; i < order ; i++)
                    {       System.out.println();
                            for  (int j=0 ; j < order ; j++)
                              {
                            System.out.print(A[i][j]+" ");
                              }
                    }
            System.out.println();
           
            System.out.println("Matrix II: ");
                    for (int i=0 ; i < order ; i++)
                    {       System.out.println();
                               for  (int j=0 ; j < order ; j++)
                                 {
                            System.out.print(B[i][j]+" ");
                              }
                    }
            System.out.println();
           
            int menu = 0;
            System.out.println("\n1. ADD\n2. SUBSTRACT\n3. MULTIPLY\n4. DIVISION\n5. QUIT");
            boolean quit = false;
            do{
            System.out.print("ENTER YOUR CHOICE : ");
            menu = Integer.parseInt(in.readLine());
            System.out.println();
           
                switch(menu) {
                case 1:
                        System.out.println("SUM OF 2 MATRICES :");
                        for(int i=0;i<order;i++){
                        for(int j=0;j<order;j++){
                        C[i][j]=A[i][j]+B[i][j];
                        System.out.print(C[i][j]+" ");
                        }
                        System.out.println();
                        }
                        break;
                case 2:
                            System.out.println("SUBSTRCTION OF 2 MATRICES :");
                            for(int i=0;i<order;i++){
                        for(int j=0;j<order;j++){
                        C[i][j]=A[i][j]-B[i][j];
                        System.out.print(C[i][j]+" ");
                        }
                        System.out.println();
                        }
                        break;
                case 3:
                        System.out.println("MULTIPICATION OF 2 MATRICES :");
                       
                        for(int i=0;i<order;i++){
                        for(int j=0;j<order;j++){
                        for(int k=0;k<order;k++){
                        C[i][j]+=A[i][k]*B[k][j];
                        }
                        }
                        }
                        for(int i=0;i<order;i++){
                        for(int j=0;j<order;j++){
                        System.out.print(+C[i][j]+" ");
                        }
                        System.out.println();
                        }
                        break;
                case 4:
                           System.out.println("DIVISION OF 2 MATRICES : ");
                          for(int i = 0; i < order; i++) {
                          for(int j = 0; j < order; j++) {
                          C[i][j]=A[i][j]/B[i][j];
                          System.out.print(C[i][j]+" ");
                          }
                          System.out.println(" ");
                          }
                          break;
                case 5:
                        quit = true;
                        break;
                default:
                        System.out.println("INVALID OPTION !!");
                 }
            }while (!quit);
        }
}

Java recursive program to find the volume of a box. Use constructors to initialize the width, height and breadth.




import java.io.*;
class volofbox{
double width,height,breadth;
volofbox(double x,double y,double z)   /*constructor */
{
width=x;
height=y;
breadth=z;
}
    public static void main(String[] args) throws IOException
    {
        DataInputStream in=new DataInputStream(System.in);
       
        System.out.println("\nCALCULATE VOLUME OF A BOX :");
        System.out.print("\nENTER WIDTH : ");       
        double a = Integer.parseInt(in.readLine());
        System.out.print("ENTER HEIGHT : ");       
        double b = Integer.parseInt(in.readLine());
        System.out.print("ENTER BREADTH : ");       
        double c = Integer.parseInt(in.readLine());

        volofbox v=new volofbox(a,b,c);    /* calling constructor with parameter a,b,c */
        System.out.print("\nVOLUME OF A BOX : "+(v.width*v.height*v.breadth)+"\n");
    }
}

Java program to convert a decimal number to binary.




import java.io.*;

import java.lang.*;

class decitobin
{

public static void main(String args[])throws IOException
{

int num,rem,deci,a,b,d,c,f=0,bin;

double i,power;
DataInputStream in=new DataInputStream(System.in);

while ( f == 0 )

{

System.out.println("\nENTER YOUR CHOICE  :\n");

System.out.println("1. BINARY TO DECIMAL.\n");

System.out.println("2. DECIMAL TO BINARY \n");

System.out.println("3. EXIT \n");

c=Integer.parseInt(in.readLine());

switch(c)
{
case 1:           
        System.out.println();
        System.out.println("ENTER A VALID BINARY NUMBER  :\n");

                num=Integer.parseInt(in.readLine());

                d=num;
        deci=0;
        i=0;  

                while( num > 0 )

                {

                a=num;

                num = num/10;

                rem= a%10;

                power=Math.pow(2,i);

                int x;

                x=(int)power;

                b=rem*x;

                deci=deci+b;

                i=i+1;

                }

                System.out.println("\nTHE DECIMAL EQUIVALENT OF "+d+" IS "+deci);

              break;
case 2:

        bin=0;
        i=0;
        System.out.println();
                System.out.println("\nENTER DECIMAL NUMBER  :\n");

                num=Integer.parseInt(in.readLine());

                d=num;

                while( num > 0 )

                {

                a=num;

                num = num/2;

                rem= a%2;

                power=Math.pow(10,i);

                int x;

                x=(int)power;

                b=rem*x;

                bin=bin+b;

                i=i+1;

                }

                System.out.println("\nTHE BINARY EQUIVALENT OF "+d+" IS "+bin);

        break;
case 3:            f=1;
        break;
default :       System.out.println("\nINVALID OPTION \n");

}

}

}

}

Java recursive program to compute a Power n. Where ‘a’ and ‘n’ are integers.




import java.io.*;
class apowern{
    public static void main(String[] args) throws IOException{
        DataInputStream in=new DataInputStream(System.in);

        System.out.println("\nCALCULATE a POWER n :");
        System.out.print("\nENTER VALUE FOR a : ");       
        double a = Integer.parseInt(in.readLine());
        System.out.print("ENTER VALUE FOR n : ");       
        double n = Integer.parseInt(in.readLine());

        if ( a == 0 && n == 0 )
            {
                System.out.println("\nTHIS OPERATION CAN NOT BE PERFORMED ! ");
            }
        else
            {
                System.out.println("\na POWER n = "+power(a,n));
            }
    }

public static double power(double x, double y) /* Recursive method */
{

    if (x==0)
    {
        return 0;
    }
    else if(y==0)
    {
        return 1;
    }
    else if (y>0)
    {
        return( x* power(x,y-1));
    }
    else
    {
        return ((1/x)*power(x,y+1));
    }
}

}

Java program to find the roots of a quadratic equation.




import java.io.*;
class Quadratic{
    public static void main(String[] args) throws IOException{
        DataInputStream in=new DataInputStream(System.in);
        System.out.println("\nQUADRATIC EQUATION aX^2+bx+c :");
        System.out.print("\nENTER VALUE FOR a : ");       
        int a = Integer.parseInt(in.readLine());
        System.out.print("ENTER VALUE FOR b : ");       
        int b = Integer.parseInt(in.readLine());
        System.out.print("ENTER VALUE FOR c : ");       
        int c = Integer.parseInt(in.readLine());

        double temp;
        temp = (b * b) - (4 * a * c);

        if ( temp > 0 )
            {
                double Root1 = (- b + Math.sqrt(temp)) / (2 * a);
                double Root2 = (- b - Math.sqrt(temp)) / (2 * a);
                System.out.println("\nTHE ROOTS ARE " + Root1 + " AND " + Root2);
            }
        else if ( temp == 0 )
            {
                double root = - b / (2 * a);
                System.out.println("\nTHE ROOTS ARE " + root + " AND " + root );
            }
        else if ( temp < 0 )
            {
                System.out.println("\nTHE ROOTS ARE IMAGINARY  ");
            }
    }
}

Java program to find the factorial of a number.




import java.io.*;
class Factorial{
    public static void main(String[] args) throws IOException{
        DataInputStream in=new DataInputStream(System.in);
        System.out.println("\nENTER NUMBER : ");
        int num = Integer.parseInt(in.readLine());
        System.out.print(num+"! = ");       
        if(num == 0){System.out.print("1 \n");}
        else if(num == 1){System.out.print("1 \n");}
        else{
                int fact= 1;
                for (int i=1; i<=num; i++)
                {
                fact=fact*i;
                }
                System.out.print(fact+"\n");
        }
    }
}

Java program to generate first N Fibonacci numbers.




import java.io.*;
public class Fibonacci
{
public static void main(String[] args) throws IOException
{
DataInputStream in=new DataInputStream(System.in);
System.out.println("\nENTER THE NUMBER OF TERMS TO BE GENERATED : ");
int n = Integer.parseInt(in.readLine());
System.out.println("\nFIBONACCI SERIES UPTO "+ n + " TERMS ");
for (int i = 1; i <= n; i++)
{
int f = fibo(i);
System.out.print(f +" ");
}
System.out.println("\n");
}
//to find nth Fibonacci number
public static int fibo(int n)
{
if (n <= 2)
return 1;
else
return fibo(n - 1) + fibo(n - 2);
}
}

Java program to generate N prime numbers





import java.io.*;
class Primenumber {
    public static void main(String[] args) throws IOException{
        int i,j,count,m;
        DataInputStream in=new DataInputStream(System.in);
        System.out.println("\nENTER THE NUMBER OF TERMS TO BE GENERATED : ");
        int num = Integer.parseInt(in.readLine());
        System.out.println("\n"+num+" PRIME NUMBERS :\n");       
        if(num == 1){System.out.println("1 ");}
        else{
            System.out.print("1 ");
            i=1;m=2;
            do
            {
                count=0;
                for (j=1; j<=i; j++)
                {
                    int n = i%j;
                    if (n==0)
                    {
                        count++;
                    }
                }
                if(count == 2){System.out.print(i+" ");m++;}
                i++;
            }while(m<=num);
            System.out.println("\n");
        }
    }
}

Name

Email *

Message *