Saturday, 22 March 2014

Assignment 2

Student info
import java.io.*;
class StudentInfo
{
    int rno;
    String name,course;
    float fees;
    BufferedReader br;
    StudentInfo()
    {
        br=new BufferedReader(new InputStreamReader(System.in));
        try
        {
            System.out.println("Eneter roll no");
            rno=Integer.parseInt(br.readLine());
            System.out.println("Eneter name");
            name=br.readLine();
            System.out.println("Eneter course");
            course=br.readLine();
            System.out.println("Eneter fees");
            fees=Float.parseFloat(br.readLine());
        }
        catch(Exception ex)
        {
            System.out.println("Error in input");
        }
    }

    public void show()
    {
        System.out.print("\nRoll no-  "+rno+"\nName-  "+name+"\nCourse-  "+course+"\nFees-  "+fees);
    }
    public static void main(String args[])
    {
        StudentInfo si=new StudentInfo();
        si.show();
    }
}

Account Details
import java.io.*;
class AccountDetails
{
    int acno;
    String name,type;
    float bal;
    BufferedReader br;
    AccountDetails()
    {
        br=new BufferedReader(new InputStreamReader(System.in));
        try
        {
            System.out.println("Enter account no");
            acno=Integer.parseInt(br.readLine());
            System.out.println("Enter account type");
            type=br.readLine();
            System.out.println("Enter name");
            name=br.readLine();
            System.out.println("Enter balance");
            bal=Float.parseFloat(br.readLine());
        }
        catch(Exception ex)
        {
            System.out.println("Error in input");
        }
    }

    public void deposit(float amt)
    {
        bal=bal+amt;
    }
   
    public void withdraw(float amt)
    {
        if(bal<500&&(bal-amt)<500)
        {
            System.out.println("Cannot withdraw ammount ");
            System.exit(1);
        }
        else
        {
            bal=bal-amt;
        }
    }

    public void showBal()
    {
        System.out.print("\nAccount no-  "+acno+"\nAccount type-  "+type+"\nName-  "+name+"\nBalance available-  "+bal);
    }
    public static void main(String args[])
    {
        AccountDetails ad=new AccountDetails();
        ad.showBal();
        ad.deposit(1500F);
        ad.showBal();
        ad.withdraw(500F);
        ad.showBal();
    }
}

 
String sort
class StringSort
{
    public static void main(String[] args)
    {
        String names[] = {"paul" , "john", "smith", "avery"};
        String t;
        int n = names.length;
        int i,j,c;
        for (i=0; i<n-1; i++)
        {
            for (j=i+1; j<n; j++)
            {
                c = names[i].compareTo(names[j]);
                if (c >0)
                {
                    t = names[i];
                    names[i] = names[j];
                    names[j] = t;       
                }   
            }
        }
        for (i=0; i<n ;i++)
        {
            System.out.println(names[i]);   
        }
    }
}

 
Max Min
 import java.io.*;
public class MaxMin
{
    int arr[];
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    MaxMin()
    {
        arr=new int[5];
        for(int i=0;i<5;i++)
            arr[i]=0;
    }

    public void accept()
    {
        try
        {
            System.out.println("Enter 5 elements :");
            for(int i=0;i<5;i++)
                arr[i]=Integer.parseInt(br.readLine());
        }catch(IOException ex){}
    }

    public void find()
    {
        int max,min;
        max=min=arr[0];
        for(int i=1;i<5;i++)
        {
            if(max<arr[i])
                max=arr[i];
            else if(min>arr[i])
                min=arr[i];
        }
        System.out.println("Maximum number amongst entered array is "+max);
        System.out.println("Minimum number amongst entered array is "+min);
    }

    public static void main(String args[])
    {
        MaxMin mm=new MaxMin();
        mm.accept();
        mm.find();
    }
}

Assignment 1

Perfect no

import java.io.*;
public class PerfectNo {
    public boolean isPerfectNumber(int number){
        int temp = 0;
        for(int i=1;i<=number/2;i++){
            if(number%i == 0){
                temp += i;
            }
        }
        if(temp == number){
           
            return true;
        } else {
           
            return false;
        }
    }
    
    public static void main(String a[]){
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        PerfectNo ipn = new PerfectNo();
        try{
        System.out.println("Enter The Number:   ");
        int i =  Integer.parseInt(br.readLine());
        System.out.println("Is perfect number: "+ipn.isPerfectNumber(i));}
        catch(Exception e){}
    }
}



Prime No

import java.io.*;public class PrimeNo
{
    public static void main(String[] args)
    {
             try {
                int starting_number;
                int ending_number ;
                long totals = 0;
                BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
                System.out.println(" Enter Starting No: ");
                starting_number = Integer.parseInt(br.readLine());
                System.out.println(" Enter Ending No: ");
                ending_number = Integer.parseInt(br.readLine());
                System.out.println("List of prime numbers between " + starting_number + " and " + ending_number);
                for (long current = starting_number; current <= ending_number; current++)
        {
                        long sqr_root = (long) Math.sqrt(current);
                        boolean is_prime = true;
                        for (long i = 2; i <= sqr_root; i++)
            {
                            if (current % i == 0)
                {
                                    is_prime = false; // Current is not prime.
                            }
                        }
                        if (is_prime) {
                        System.out.println(current);
                        totals++;
                        }
                }
            System.out.println("There are a total of "+totals+" prime numbers between "+starting_number+" and "+ending_number);
        }    
        catch (Exception e){}
    }
}


  Fibonacci Series
import java.io.*;
import java.util.*;
public class FibonacciSeries
{
    private static int[] F = new int[41];
    public static void main(String[] args)
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        int n=0;
        do
        {
            System.out.print("Please enter a value for n: ");
            try
            {
                n = Integer.parseInt(br.readLine());
            } catch (Exception x) {
            System.out.println("Must be a whole number!");
            System.exit(1);
            }
            if (n>40) System.out.println("Number too big! Must be 40 or less");
            if (n<1) System.out.println("Number too small! Must be 1 or more");
        } while (n>40 || n<1);

        System.out.println("first n terms in the Fibonacci Series.");
        for (int i=1; i<=n; i++)
        {
            System.out.print(fib(i)+" ");
        }
    }

    public static int fib(int n)
    {
        for (int i=1; i<=n; i++)
        {
            switch(i)
            {
                case 1 :     F[i]= 0; break;
                case 2 :
                case 3 :    F[i] = 1; break;
                default :    F[i] = F[i-2] + F[i-1];
            }
        }
        return F[n];
    }
}

 
Pattern
import java.io.*;
class pattern
{
public static void main(String args[])
{
int i,j,k,l;
for(i=1;i<=5;i++)
{
    for(j=1;j<=i;j++)
    {
        System.out.print(" ");
    }
    for(j=i;j<=5;j++)
    {
        System.out.print("$");
    }
   
System.out.print("\n");

}
}
}

50) Write a RMI application to convert dolor into rupees .Write all interfaces and required classes.

import java.rmi.*;
public interface rupees extends Remote
{
    public double convert(double rs) throws RemoteException;
}


import java.rmi.*;
import java.rmi.server.*;
public class rupees_impli extends UnicastRemoteObject implements rupees
{
    public rupees_impli() throws RemoteException
    {}

    public double convert(double rs) throws RemoteException
    {
        return (rs/65);
    }
}


import java.rmi.*;
import java.net.*;
public class rupees_server
{
    public static void main(String args[])
    {
        try
        {
        rupees_impli rsimpli=new rupees_impli();
        Naming.rebind("RmiRupee",rsimpli);
        }
        catch(Exception ex){}
    }
}


import java.io.*;
import java.rmi.*;
import java.net.*;
public class rupees_client
{
    public static void main(String args[])
    {
        try
        {
            String url="rmi://127.0.0.1/RmiRupee";
            rupees intf=(rupees)Naming.lookup(url);

            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Enter Rs : ");
            double rsval=Double.parseDouble(br.readLine());
            System.out.println("Conversion of "+rsval+" rupees is dollor "+intf.convert(rsval) );
        }
        catch(Exception ex){}
    }
}

49) Write a RMI application to reverse the given string .Write all interfaces and required classes.

import java.rmi.*;
public interface StrRev extends Remote
{
    public String reverse(String str) throws RemoteException;
}


import java.rmi.*;
import java.rmi.server.*;
import java.util.*;
public class StrRev_Impli extends UnicastRemoteObject implements StrRev
{
    public StrRev_Impli() throws RemoteException
    {}

    public String reverse(String str) throws RemoteException
    {
        String str1="";
        for(int i=str.length()-1;i>=0;i--)
            str1=str1+str.charAt(i);
        return (str1);
    }
}


import java.rmi.*;
import java.net.*;
public class StrRev_Server
{
    public static void main(String args[])
    {
        try
        {
        StrRev_Impli strimpli=new StrRev_Impli();
        Naming.rebind("RmiReverse",strimpli);
        }
        catch(Exception ex){}
    }
}


import java.io.*;
import java.rmi.*;
import java.net.*;
public class StrRev_Client
{
    public static void main(String args[])
    {
        try
        {
            String url="rmi://127.0.0.1/RmiReverse";
            StrRev strf=(StrRev)Naming.lookup(url);

            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Enter String to reverse : ");
            String str=br.readLine();
            System.out.println("Reverse of entered string is "+strf.reverse(str));
        }
        catch(Exception ex){}
    }
}

48) Write a RMI application to check whether the given number is Prime or not . Write all interfaces and required classes.

import java.rmi.*;
public interface Prime extends Remote
{
    public int check_prime(int no) throws RemoteException;
}


import java.rmi.*;
import java.rmi.server.*;
public class Prime_Impli extends UnicastRemoteObject implements Prime
{
    public Prime_Impli() throws Exception
    {
    }

    public int check_prime(int no) throws RemoteException
    {
        int i,cnt=0;
        for(i=2;i<=no/2;i++)
            if(no%i==0)
            {
                cnt++;
                break;
            }       
            return (cnt);
    }
}


import java.rmi.*;
import java.net.*;
public class Prime_server
{
    public static void main(String args[])
    {
        try
        {
        Prime_Impli primpli=new Prime_Impli();
        Naming.rebind("RmiPrime",primpli);
        }
        catch(Exception ex){}
    }
}


import java.io.*;
import java.rmi.*;
import java.net.*;
public class Prime_client
{
    public static void main(String args[])
    {
        try
        {
            String url="rmi://127.0.0.1/RmiPrime";
            Prime intf=(Prime)Naming.lookup(url);

            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Enter No : ");
            int no=Integer.parseInt(br.readLine());
            int x=intf.check_prime(no);
            if(x==0)
            System.out.println(no+" is prime number");
            else
            System.out.println(no+" is not prime number");   
    }
        catch(Exception ex){}
    }
}

34) Write a progtam to show how file class is used to display information about a directory and all the files included in current directory.

import java.io.File;
import java.io.IOException;

public class Directory
{
    public static void main(String[] args)
    {
        File currentDir = new File(".");
        DirContents(currentDir);
    }

    public static void DirContents(File dir)
    {
        try
        {
            File[] files = dir.listFiles();
            for (File file : files)
            {
                System.out.println("     file:" + file.getCanonicalPath());
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

}

33) Write a program to check whether the file is readable, Writable or hidden.

import java.util.Scanner;
import java.io.File;
class FileDemo
{
    public static void main(String[] args)
    {
        Scanner input=new Scanner(System.in);
        String s=input.nextLine();
        File f1=new File(s);   
        System.out.println("File Name:"+f1.getName());
        System.out.println("This file is:"+(f1.exists()?"Exists":"Does not exists"));
        System.out.println("Is Readable:"+f1.canRead());
        System.out.println("IS Writable:"+f1.canWrite());
        System.out.println("Is Hidden:"+f1.isHidden());
    }
}

32) Write a program to accept empno & update a file emp.dat

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

class Employee1 extends Frame implements ActionListener
{
    JLabel e_no,e_nam,e_sal;
    JTextField empno,nam,sal;
    JButton btnsav;
    Connection con;
    PreparedStatement pst;
    Statement stmt;
    Employee1() throws Exception
    {
    super("NAVIGATION");

    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    con=DriverManager.getConnection("Jdbc:Odbc:JavaProg");
   
    e_no=new JLabel("Employee Number :");
    e_nam=new JLabel("Employee Name :");
    e_sal=new JLabel("Employee Salary :");

    empno=new JTextField(20);   
    nam=new JTextField(20);
    sal=new JTextField(20);
   
    btnsav=new JButton("UPDATE");
   
    JPanel jp=new JPanel();
    jp.setLayout(new GridLayout(4,2));
    jp.add(e_no);    jp.add(empno);
    jp.add(e_nam);    jp.add(nam);
    jp.add(e_sal);    jp.add(sal);
    jp.add(btnsav);
   
    btnsav.addActionListener(this);
   
    add(jp);
    setLayout(new FlowLayout());
    setSize(400,400);
    setVisible(true);
    }

public  void actionPerformed(ActionEvent ae)
{
    try
    {
        if(ae.getActionCommand().equals("UPDATE"))
        {
           
            stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
            String que="SELECT * FROM Employee where Empno="+Integer.parseInt(empno.getText());
                ResultSet rs = stmt.executeQuery(que);
            rs.next();
                    rs.updateString(2, nam.getText());
                    rs.updateInt(3, Integer.parseInt(sal.getText()));
            rs.updateRow();
            empno.setText("");
            nam.setText("");
            sal.setText("");
            JOptionPane.showMessageDialog(null,"Values Updated");
        }
          }
    catch(Exception ex)
    {
        System.out.println(ex.getMessage());
    }
}


public static void main(String args[]) throws Exception
{
    new Employee1();
}
}

31) Design a employee form(empno,name& sal) & save the data in emp.dat file on click of button.

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

class Employee extends Frame implements ActionListener
{
    JLabel e_no,e_nam,e_sal;
    JTextField empno,nam,sal;
    JButton btnsav;
    Connection con;
    PreparedStatement pst;

    Employee() throws Exception
    {
    super("NAVIGATION");

    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    con=DriverManager.getConnection("Jdbc:Odbc:JavaProg");
   
    e_no=new JLabel("Employee Number :");
    e_nam=new JLabel("Employee Name :");
    e_sal=new JLabel("Employee Salary :");

    empno=new JTextField(20);   
    nam=new JTextField(20);
    sal=new JTextField(20);
   
    btnsav=new JButton("SAVE");
   
    JPanel jp=new JPanel();
    jp.setLayout(new GridLayout(4,2));
    jp.add(e_no);    jp.add(empno);
    jp.add(e_nam);    jp.add(nam);
    jp.add(e_sal);    jp.add(sal);
    jp.add(btnsav);
   
    btnsav.addActionListener(this);
   
    add(jp);
    setLayout(new FlowLayout());
    setSize(400,400);
    setVisible(true);
    }

public  void actionPerformed(ActionEvent ae)
{
    try
    {
        if(ae.getActionCommand().equals("SAVE"))
        {
            pst=con.prepareStatement("insert into Employee values(?,?,?)");
            pst.setInt(1,Integer.parseInt(empno.getText()));
            pst.setString(2,nam.getText());
            pst.setFloat(3,Float.parseFloat(sal.getText()));
            empno.setText("");
            nam.setText("");
            sal.setText("");
            pst.executeUpdate();
            JOptionPane.showMessageDialog(null,"Values Added");
        }
          }
    catch(Exception ex)
    {
        System.out.println(ex.getMessage());
    }
}


public static void main(String args[]) throws Exception
{
    new Employee();
}
}

11) Using Runnable interface, create two threads, one thread will print prime number and other thread will print perfect number.

import java.io.*;
class Perfect implements Runnable
{
    public void run()
    {
        int no;
        for(no=1;no<=1000;no++)
        {
            int sum=0;
            for(int i=1;i<=no/2;i++)
            {
                if(no%i==0)
                    sum=sum+i;
            }
            if(no==sum)
                System.out.println(no+" Number is perfect");
        }
    }
}

class Prime implements Runnable
{
    public void run()
    {
        int no;
        for(no=2;no<=1000;no++)
        {
            int cnt=0;
            for(int i=2;i<=no/2;i++)
                if(no%i==0)
                {
                    cnt++;
                    break;
                }
            if(cnt==0)
                System.out.println(no+" Number is prime");
        }
    }
}


class PerfectPrime
{
    public static void main(String args[])
    {
        try
        {
            Perfect p=new Perfect();
            Thread t1=new Thread(p);
            Prime p1=new Prime();
            Thread t2=new Thread(p1);
            t1.start();
            t2.start();
        }
        catch(Exception e1){}
    }
}

10) Write an application to generate following threads I. Count vowels from accepted string from user. II. Calculate sum of digits of number accepted from user.

import java.io.*;
class VowelCount implements Runnable
{
    public void run()
    {
        int cnt=0;
           try
        {
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Enter the string");
            String data=br.readLine();
            int len=data.length();
            for(int i=0;i<len;i++)
            {
                if(data.charAt(i)=='a'|| data.charAt(i)=='e'|| data.charAt(i)=='i'|| data.charAt(i)=='o'|| data.charAt(i)=='u' || data.charAt(i)=='A'|| data.charAt(i)=='E'|| data.charAt(i)=='I'|| data.charAt(i)=='O'|| data.charAt(i)=='U')
                cnt++;
            }
            System.out.println("Total number of vowels in entered string are "+cnt);
        }
        catch(Exception e){}
    }
}

class SumOfDigit implements Runnable
{
    public void run()
    {
        int sod=0;
        try
        {
            Thread.sleep(10000);
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Enter the number ");
            int no=Integer.parseInt(br.readLine());
            while(no>0)
            {
                sod=sod+no%10;
                no=no/10;
            }
            System.out.println("Sum of digit of entered number is "+sod);
        }
        catch(Exception ex){}
    }
}


class VowelSod
{
    public static void main(String args[])
    {
        try
        {
            VowelCount vc=new VowelCount();
            Thread t1=new Thread(vc);
            SumOfDigit sd=new SumOfDigit();
            Thread t2=new Thread(sd);
            t1.start();
            t2.start();
        }
        catch(Exception e1){}
    }
}

WAP that executes 3 threads. First thread displays “Good Morning” every one second, second thread displays “Hello” every two seconds, third thread displays “Welcome” every three seconds. Create the 3 threads by extending the Thread class.

import java.io.*;
import java.util.*;
class First extends Thread
{
    public void run()
    {
        int i=0;
        try
        {
            while(i<10)
            {
                System.out.println("Good Morning ");
                i++;
                Thread.sleep(1000);
            }
        }
        catch(Exception e3){}
    }
}

class Second extends Thread
{
    public void run()
    {
        int j=0;
           try
        {
            while(j<10)
            {
                System.out.println("Hello ");
                j++;
                Thread.sleep(2000);
            }
        }
        catch(Exception e2){}
    }
}

class Third extends Thread
{
    public void run()
    {
        int k=0;
           try
        {
            while(k<10)
            {
                System.out.println("Welcome ");
                k++;
                Thread.sleep(3000);
            }
        }
        catch(Exception e1){}
    }
}

class ThreeThread
{
    public static void main(String args[])
    {
        try
        {
            First f=new First();
            f.start();
            Second s=new Second();
            s.start();
            Third t=new Third();
            t.start();
        }
        catch(Exception e){}
    }
}

Define a thread using Thread class to generate the factorials of first 10 natural numbers. Create an instance for this thread & then activate it.

import java.io.*;
import java.util.*;
class Factorial extends Thread
{
    public void run()
    {
        int fact=1;
        for(int i=1;i<=10;i++)
        {
            fact=fact*i;
            System.out.println("Factorial of "+i+" is "+fact);
        }
    }

    public static void main(String args[])
    {
        Factorial f1=new Factorial();
        f1.start();
    }
}

Write a JAVA program which will create two child threads by implementing Runnable interface; one thread will print even nos from 1 to 50 and other display vowels from accepted string.

import java.io.*;
import java.util.*;
class Even implements Runnable
{
    public void run()
    {
        for(int i=1;i<=50;i++)
        {
            if(i%2==0)
                System.out.println("Even no " +i);
        }
    }
}

class Vowel implements Runnable
{
    public void run()
    {
           try
        {
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Enter the string");
            String data=br.readLine();
            int len=data.length();
            for(int i=0;i<len;i++)
            {
                if(data.charAt(i)=='a'|| data.charAt(i)=='e'|| data.charAt(i)=='i'|| data.charAt(i)=='o'|| data.charAt(i)=='u' || data.charAt(i)=='A'|| data.charAt(i)=='E'|| data.charAt(i)=='I'|| data.charAt(i)=='O'|| data.charAt(i)=='U')
                System.out.println("Vowel in entered string at position "+(i+1)+" is "+data.charAt(i));
            }
        }
        catch(Exception e){}
    }
}

class EvenVowel
{
    public static void main(String args[])
    {
        try
        {
            Even no=new Even();
            Thread t1=new Thread(no);
            t1.start();
            t1.sleep(1000);
            Vowel ch=new Vowel();
            Thread  t2=new Thread(ch);
            t2.start();

        }
        catch(Exception e){}
    }
}

Write program to accept rollno, marks of four subjects in an array from user and throw marks out of bound exception if marks are less than 0 or marks greater than 100.Also check ArrayIndexOutofBoundsException.

import java.io.*;
class MarksOutOfBoundException extends Exception
{
    public String toString()
    {
        return "Enter marks in between 1 & 100";
    }
}
class Student1
{
    int rno;
    float marks[];
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    Student1()
    {
        rno=0;
        marks=new float[4];
        for(int i=0;i<4;i++)
            marks[i]=0;
    }
    public void accept()
    {
        System.out.println("Enter roll no & marks of 4 subjects ");
        try
        {
            rno=Integer.parseInt(br.readLine());
            for(int i=0;i<4;i++)
            {
                marks[i]=Float.parseFloat(br.readLine());
                if(marks[i]<0 || marks[i]>100)
                    throw new MarksOutOfBoundException();
            }
        }
        catch(MarksOutOfBoundException me)
        {
            System.out.println(me);
        }
        catch(ArrayIndexOutOfBoundsException e)
        {
            System.out.println("Array index out of bounds");
        }
        catch(IOException ie)
        {
            System.out.println("Io Exception");
        }
    }

    public void display()
    {
        System.out.println("Roll no\tMarks1\tMarks2\tMarks3\tMarks4");
        System.out.print(rno+"\t");
        for(int i=0;i<4;i++)
        System.out.print(marks[i]+"\t");
    }

    public static void main(String args[])
    {
        Student1 s1=new Student1();
        s1.accept();
        s1.display();
    }
}




D:\Rushi>javac Student1.java

D:\Rushi>java Student1
Enter roll no & marks of 4 subjects
4
40
35
60
75
Roll no Marks1  Marks2  Marks3  Marks4
4       40.0    35.0    60.0    75.0

Write a java program to accept a number from the user, if number is zero then throw user defined exception “Number is 0” otherwise check whether no is prime or not.

import java.io.*;
class NumberZeroException extends Exception
{
    public String toString()
    {
        return("Number is 0");
    }
}

class PrimeNumber
{
    int a;
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    PrimeNumber()
    {
        try
        {
            System.out.println("Enter any integer to check prime ");
            a=Integer.parseInt(br.readLine());
            if(a==0)
                throw new NumberZeroException();
        }
        catch(NumberZeroException ex)
        {
            System.out.println(ex);
        }
        catch(IOException ex1)
        {
            System.out.println("Enter proper number");
        }
    }

    public void prime()
    {
        int cnt=0;
        for(int i=2;i<=a/2;i++)
            if(a%i==0)
            {
                cnt++;
                break;
            }
        if(cnt==0)
            System.out.println(a+" Number is prime");
        else
            System.out.println(a+" Number is not prime");
    }
    public static void main(String args[])
    {
        PrimeNumber pn=new PrimeNumber();
        pn.prime();
    }
}



D:\Rushi>javac PrimeNumber.java

D:\Rushi>java PrimeNumber
Enter any integer to check prime
7
7 Number is prime

Write 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 “Age Not Within The Range”.If name contains numbers or special symbols raise exception “Name not valid”.

import java.io.*;
class AgeNotWithInRangeException extends Exception
{
    public String toString()
    {
        return("Age is not between 15 and 21 ... Please ReEnter the Age");
    }
}

class NameNotValidException extends Exception
{
    public String validname()
    {
        return("Name is not Valid ... Please ReEnter the Name");
    }
}


class Student
{
    int roll,age;
    String name,course;
    Student()
    {
        roll=0;
        name=null;
        age=0;
        course=null;
    }
    Student(int r,String n,int a,String c)
    {
        roll=r;
        course=c;
        int l,temp=0;
        l=n.length();
        for(int i=0;i<l;i++)
        {
            char ch;
            ch=n.charAt(i);
            if(ch<'A' || ch>'Z' && ch<'a' || ch>'z')
            temp=1;
        }
                /*———-Checking Name——————–*/
        try
        {
            if(temp==1)
                throw new NameNotValidException();
            else
                name=n;
        }
        catch(NameNotValidException e2)
        {
            System.out.println(e2);
        }
                /*———-Checking Age——————–*/
        try
        {
            if(a>=15 && a<=21)
                age=a;
            else
                throw new AgeNotWithInRangeException();
        }
        catch(AgeNotWithInRangeException e1)
        {
            System.out.println(e1);
        }
    }
    void display()
    {
        System.out.println("Roll\tName\tAge\tCourse");
        System.out.println("----------------------------------");
        System.out.println(roll+"\t"+name+"\t"+age+"\t"+course);
    }
}

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

        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        int r,a;
        String n,c;

        System.out.println("Enter Roll,Name,Age,Course");

        r=Integer.parseInt(br.readLine());
        n=br.readLine();
        a=Integer.parseInt(br.readLine());
        c=br.readLine();
        Student s=new Student(r,n,a,c);
        s.display();
    }
}




D:\Rushi>javac StudentDemo.java

D:\Rushi>java StudentDemo
Enter Roll,Name,Age,Course
1
Akash
21
MCA
Roll    Name    Age     Course
-------------------------------
1       Akash   21      MCA

Define class named Course as below: i. Data Members: Courseid ii. Methods: constructor, display() Define another classes MCA,MBA,MCM that extends from Course: iii. Data Members : Course name and Duration iv. Methods: constructor, show () Create an object of classes MCA,MBA,MCM and Test them

import java.io.*;
class Course
{
    int Courseid;
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    Course()
    {
        try
        {
            System.out.println("Enter The Course ID: ");
            Courseid=Integer.parseInt(br.readLine());
        }
        catch(Exception E){}
    }
    public void display()
    {
        System.out.println("Course Id:-  "+Courseid);
    }
}       

class MCA extends Course
{
    String Name;
    int Duration;
    MCA()
    {
        Name="MCA";
        Duration=36;
    }
    public void show()
    {
        System.out.println("Course Name:- "+Name);
        System.out.println("Duration <Months> :- "+Duration);   
        display();
    }
}
       

class MBA extends Course
{
    String Name;
    int Duration;
    MBA()
    {
        Name="MBA";
        Duration=24;
    }
    public void show()
    {
        System.out.println("Course Name:- "+Name);
        System.out.println("Duration <Months> :- "+Duration);   
        display();
    }
}
       
class MCS extends Course
{
    String Name;
    int Duration;
    MCS()
    {
        Name="MCS";
        Duration=24;
    }
    public void show()
    {
        System.out.println("Course Name:- "+Name);
        System.out.println("Duration <Months> :- "+Duration);   
        display();
    }
}
       
public class ass3
{
    public static void main( String args[])
    {
        MCA C1= new MCA();
        C1.show();
        MBA C2= new MBA();
        C2.show();
        MCS C3= new MCS();
        C3.show();
    }
}   

Declare an abstract class vehicle with an abstract method name numwheels().provide the two subclasses two-wheeler and four wheeler , each one of which implements this method. Create instance of these two subclasses and demonstrate the use of numwheels() method.

import java.io.*;
public abstract class vehicle
{

    public abstract void numwheels();
}


public class TwoWheelers extends vehicle
{
    public void numwheels()
    {
        System.out.println("Vehicle Have Two Wheels.");
    }
}


public class FourWheelers extends vehicle
{

    public void numwheels()
    {
        System.out.println("Vehicle Have Four Wheels.");
    }
}

public class ass2
{
    public static void main( String args[])
    {
        TwoWheelers shine= new TwoWheelers();
        shine.numwheels();
        FourWheelers i10= new FourWheelers();
        i10.numwheels();
    }
}

Create a package MCA which will have 2 classes as class Mathematics with a methods to add two numbers, add three float numbers and class Maximum with a method to find maximum of three numbers.

package MCA;
import java.io.*;
class Mathematics
{
    float a,b,c;
    int p,q;
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

    public int add_i()
    {
        try
        {
        System.out.println("Enter two integers");
        p=Integer.parseInt(br.readLine());
        q=Integer.parseInt(br.readLine());
        }
        catch(Exception ex){}
        return (p+q);
    }

    public float add_f()
    {
        try
        {
        System.out.println("Enter three floats");
        a=Float.parseFloat(br.readLine());
        b=Float.parseFloat(br.readLine());
        c=Float.parseFloat(br.readLine());
        }
        catch(Exception ex1){}
        return (a+b+c);
    }
}

class Maximum
{
    int x,y,z,max;
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

    public int check_max()
    {
        try
        {
        System.out.println("Enter three integers");
        x=Integer.parseInt(br.readLine());
        y=Integer.parseInt(br.readLine());
        z=Integer.parseInt(br.readLine());
        if(x>y&&x>z)
            max=x;
        else if(y>z)
            max=y;
        else
            max=z;
        }
        catch(Exception ex3){}
        return max;
    }
}


class Test
{
    public static void main(String args[])
    {
        Mathematics m=new Mathematics();
        System.out.println("Addition of two integers is "+m.add_i());
        System.out.println("Addition of three floats is "+m.add_f());
        Maximum m1=new Maximum();
        System.out.println("Maximum amongst three integers is "+m1.check_max());
    }
}



D:\Rushi>javac -d D:\Rushi Test.java
D:\Rushi>java -cp D:\Rushi MCA.Test
Enter two integers
20
30
Addition of two integers is 50
Enter three floats
12.5
52.2
36.4
Addition of three floats is 101.1
Enter three integers
2
5
8
Maximum amongst three integers is 8

Monday, 10 March 2014

Calculator program using ActionListener

/*
<applet code="Calculator.class" height =200 width=200>
</applet>
*/

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class Calculator extends Applet implements ActionListener
{
String first,op;
TextField t1;
Button b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b15,b14,b0;
public void init()
{
t1=new TextField(40);
b0=new Button("0");
b1=new Button("1");
b2=new Button("2");
b3=new Button("3");
b4=new Button("4");
b5=new Button("5");
b6=new Button("6");
b7=new Button("7");
b8=new Button("8");
b9=new Button("9");
b10=new Button("+");
b11=new Button("-");
b12=new Button("*");
b13=new Button("/");
b14=new Button(".");
b15=new Button("=");
Panel p=new Panel();

p.setLayout(new GridLayout(4,4));


p.add(b0); p.add(b1);
p.add(b2); p.add(b3);
p.add(b4); p.add(b5);
p.add(b6); p.add(b7);
p.add(b8); p.add(b9);
p.add(b10); p.add(b11);
p.add(b12); p.add(b13);
p.add(b14); p.add(b15);

b10.addActionListener(this);
b11.addActionListener(this);
b12.addActionListener(this);
b13.addActionListener(this);
b14.addActionListener(this);
b15.addActionListener(this);

Panel p1=new Panel();
p1.setLayout(new BorderLayout());
p1.add("North",t1);
p1.add("Center",p);
add(p1);
}

public boolean action(Event e,Object o)
{
if(o.equals("0"))
t1.setText(t1.getText()+"0");
if(o.equals("1"))
t1.setText(t1.getText()+"1");
if(o.equals("2"))
t1.setText(t1.getText()+"2");
if(o.equals("3"))
t1.setText(t1.getText()+"3");
if(o.equals("4"))
t1.setText(t1.getText()+"4");
if(o.equals("5"))
t1.setText(t1.getText()+"5");
if(o.equals("6"))
t1.setText(t1.getText()+"6");
if(o.equals("7"))
t1.setText(t1.getText()+"7");
if(o.equals("8"))
t1.setText(t1.getText()+"8");
if(o.equals("9"))
t1.setText(t1.getText()+"9");
if(o.equals("."))
t1.setText(t1.getText()+".");
return true;
}


public void actionPerformed(ActionEvent ae)
{
if(ae.getActionCommand().equals("+"))
{
first=t1.getText();
op="+";
t1.setText("");
}
if(ae.getActionCommand().equals("-"))
{
first=t1.getText();
op="-";
t1.setText("");
}
if(ae.getActionCommand().equals("*"))
{
first=t1.getText();
op="*";
t1.setText("");
}
if(ae.getActionCommand().equals("/"))
{
first=t1.getText();
op="/";
t1.setText("");
}
if(ae.getActionCommand().equals("="))
{
float x=Float.parseFloat(first);
float y=Float.parseFloat(t1.getText());
float z=0.0f;
if(op.equals("+"))
{
z=x+y;
}
if(op.equals("-"))
{
z=x-y;
}
if(op.equals("*"))
{
z=x*y;
}
if(op.equals("/"))
{
z=x/y;
}
t1.setText(""+z);
}
}
}