TYBCS Java Assignment 2 - Sem I


 SET A 

1.  Define a Student class (roll number, name, percentage). Define a default and parameterized constructor. Keep a count of objects created. Create objects using parameterized constructor and display the object count after each object is created. (Use static member and method). Also display the contents of each object.  

2.  Modify the above program to create n objects of the Student class. Accept details from the user for each object. Define a static method “sortStudent” which sorts the array on the basis of percentage.  

SET B
  
1.  Create a package named Series having three different classes to print series:  
a. Prime numbers 
b. Fibonacci series 
c. Squares of numbers 
Write a program to generate ‘n’ terms of the above series. 

2. Write a Java program to create a Package “SY” which has a class SYMarks (members – ComputerTotal, MathsTotal, and ElectronicsTotal). Create another package TY which has a class TYMarks (members – Theory, Practicals). Create n objects of Student class (having rollNumber, name, SYMarks and TYMarks).  Add the marks of SY and TY computer subjects and calculate the Grade (‘A’ for >= 70, ‘B’ for >= 60 ‘C’ for >= 50 , Pass Class for > =40 else ‘FAIL’) and display the result of the student in proper format. 

Post a Comment

17 Comments

  1. This link is good for the program learning as well as program beginner

    ReplyDelete
  2. Slip7_1: Design a class for Bank. Bank Class should support following operations;
    a. Deposit a certain amount into an account
    b. Withdraw a certain amount from an account
    c. Return a Balance value specifying the amount with details
    class Bank
    {
    private double balance;
    public Bank()
    {
    balance = 0;
    }
    public Bank(double initialBalance)
    {
    balance = initialBalance;
    }
    public void deposit(double amount)
    {
    balance = balance + amount;
    }
    public void withdraw(double amount)
    {
    balance = balance - amount;
    }
    public double getBalance()
    {
    return balance;
    }
    public static void main(String[] args)
    {
    Bank b = new Bank(1000);
    b.withdraw(250);
    System.out.println("the withdraw is:"+ b.balance);
    b.deposit(400);
    System.out.println("the deposit is:"+ b.balance);
    System.out.println("the balance is:"+ b.getBalance());
    }

    }
    Slip7_2: Write a program to accept a text file from user and display the contents of a file in
    reverse order and change its case.
    import java.io.*;
    import java.util.*;
    class ReverseFile
    {
    public static void main(String args[])throws IOException
    {
    Scanner sc = new Scanner(System.in);
    System.out.println("enter file name:");
    String fnm = sc.next();
    File f = new File(fnm);
    if(f.isFile())
    {
    BufferedInputStream bis = new BufferedInputStream(new
    FileInputStream(fnm));
    int size =bis.available();
    for(int i = size-1;i>=0;i--)
    {
    bis.mark(i);
    bis.skip(i);
    char ch=((char)bis.read());
    if(Character.isLowerCase(ch))
    ch=Character.toUpperCase(ch);
    else if(Character.isUpperCase(ch))
    ch = Character.toLowerCase(ch);
    System.out.print(ch);
    bis.reset();
    }
    bis.close();
    }
    else
    System.out.println("file not found");

    }
    }

    ReplyDelete
  3. Slip no:- [1] [9 ] [16]


    Create an abstract class “order” having members id,description.Create two subclasses
    “Purchase Order” and “Sales Order” having members customer name and Vendor name
    respectively.Define methods accept and display in all cases. Create 3 objects each of
    Purchase Order and Sales Order and accept and display details.

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    abstract class Order{
    String id,description;
    }
    class PurchaseOrder extends Order{
    String Customername,Vendorname;
    public void accept() throws IOException{
    System.out.println("Enter the
    id,description,names of customers and vendors:
    ");
    BufferedReader br=new BufferedReader(new
    InputStreamReader(System.in));
    id=br.readLine();
    description=br.readLine();
    Customername=br.readLine();
    Vendorname=br.readLine();
    }
    public void display(){
    System.out.println("id: "+id);
    System.out.println("Description: "+description);
    System.out.println("Customername:
    "+Customername);
    System.out.println("Vendorname:
    "+Vendorname);
    System.out.println("----------------------");
    }
    }
    class SalesOrder extends Order{
    String Customername,Vendorname;
    public void accept() throws IOException{
    System.out.println("Enter the
    id,description,names of customers and vendors:
    ");
    BufferedReader br=new BufferedReader(new
    InputStreamReader(System.in));
    id=br.readLine();
    description=br.readLine();
    Customername=br.readLine();
    Vendorname=br.readLine();
    }
    public void display(){
    System.out.println("id: "+id);
    System.out.println("Description: "+description);
    System.out.println("Customername:
    "+Customername);
    System.out.println("Vendorname:
    "+Vendorname);
    System.out.println("----------------------");
    }
    }
    class Main {
    public static void main(String [] args) throws
    IOException{
    int i;
    System.out.println("Select Any One: ");
    BufferedReader br=new BufferedReader(new
    InputStreamReader(System.in));
    System.out.println("1.Purchase Order");
    System.out.println("2.Sales Order");
    int ch=Integer.parseInt(br.readLine());
    switch(ch){
    case 1:
    System.out.println("Enter the number of
    purchase Orders: ");
    int n=Integer.parseInt(br.readLine());
    PurchaseOrder [] l=new PurchaseOrder[n];
    for(i=0;i<n;i++){
    l[i]=new PurchaseOrder();
    l[i].accept();
    }
    for(i=0;i<n;i++){
    l[i].display();
    System.out.println ("Object is created");
    }
    break;
    case 2:
    System.out.println("Enter the number of sales
    orders: ");
    int m=Integer.parseInt(br.readLine());
    SalesOrder [] h=new SalesOrder[m];
    for(i=0;i<m;i++){
    h[i]=new SalesOrder();
    h[i].accept();
    }
    for(i=0;i<m;i++){
    h[i].display();
    System.out.println(" Object is created ");
    }
    }
    }
    }

    ReplyDelete
  4. Slip no:- [2] [3] [17]


    Write a program to using marker interface create a class product(product_id,
    product_name, product_cost, product_quantity) define a default and parameterized
    constructor. Create objects of class product and display the contents of each object and
    Also display the object count.


    import java.util.Scanner;
    class Product implements Cloneable
    {
    int pid;
    String pname;
    double pcost;
    //Product class constructor
    public Product (int pid, String pname, double
    pcost)
    {
    this.pid = pid;
    this.pname = pname;
    this.pcost = pcost;
    }
    //method that prints the detail on the console
    public void showDetail()
    {
    System.out.println("Product ID: "+pid);
    System.out.println("Product Name: "+pname);
    System.out.println("Product Cost: "+pcost);
    }
    public static void main (String args[]) throws
    CloneNotSupportedException
    {
    //reading values of the product from the user
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter product ID: ");
    int pid = sc.nextInt();
    System.out.print("Enter product name: ");
    String pname = sc.next();
    System.out.print("Enter product Cost: ");
    double pcost = sc.nextDouble();
    System.out.println("-------Product Detail--------");
    Product p1 = new Product(pid, pname, pcost);
    //cloning the object of the Product class using
    the clone() method
    Product p2 = (Product) p1.clone();
    //invoking the method to print detail
    p2.showDetail();
    }
    }

    ReplyDelete
  5. Slip no :- [6 ] [28]

    Write a menu driven program to perform the following operations on multidimensional
    array ie matrix :
    i. Addition
    ii. Multiplication
    iii. Transpose of any matrix.
    iv. Exit

    import java.util.Scanner;
    public class multidimensional{
    public static void main(String args[])
    {
    //Scanner class to take input
    Scanner scan = new Scanner(System.in);
    int row, col;
    int mat1[][] = new int[3][3];
    int mat2[][] = new int[3][3];
    //Entering first matrix
    System.out.println("Enter the 3x3 matrix
    elements for 1st matrix : ");
    // Loop to take array elements as user input for
    first matrixn i.e mat1
    for(row=0;row<3;row++)
    for(col=0;col<3;col++)
    mat1[row][col] = scan.nextInt();
    //print the elements of first matrix i.e mat1
    System.out.print("1st matrix : ");
    for(row=0;row<3;row++)
    {
    // Used for formatting
    System.out.print("\n");
    for(col=0;col<3;col++)
    {
    System.out.print(mat1[row][col]+" ");
    }
    }
    //Entering second matrix
    System.out.println("\nEnter the 3x3 matrix
    elements for 2nd matrix : ");
    // Loop to take array elements as user input for
    second matrix
    for(row=0;row<3;row++)
    for(col=0;col<3;col++)
    mat2[row][col] = scan.nextInt();
    //print the elements of second matrix i.e mat2
    System.out.print("2nd matrix : ");
    for(row=0;row<3;row++)
    {
    // Used for formatting
    System.out.print("\n");
    for(col=0;col<3;col++)
    {
    System.out.print(mat2[row][col]+" ");
    }
    }
    int res[][] = new int[3][3], operationHolder = 0;
    int choice ;
    while(true)
    {
    //Prints the menu to choose operation from
    System.out.println("\n\nBASIC MATRIX
    OPERATIONS");
    System.out.println("______________________
    _");
    System.out.println("1. Addition of two
    matrices");
    System.out.println("2. Subtraction of two
    matrices");
    System.out.println("3. Multiplication of two
    matrices");
    System.out.println("4. Transpose");
    System.out.println("5. Exit");
    System.out.println("______________________
    _");
    System.out.println("Enter your choice : ");
    choice = scan.nextInt();
    // Switch cases to run the menu
    switch(choice)
    {
    case 1: res = add(mat1,mat2);
    System.out.println("After add operation");
    printMatrix(res);
    break;
    case 2: res = sub(mat1,mat2);
    System.out.println("After subtract operation");
    printMatrix(res);
    break;
    case 3: res = prod(mat1,mat2);
    System.out.println("After multiply operation");
    printMatrix(res);
    break;
    case 4: res = trans(mat1);
    System.out.println("After transpose operation");
    printMatrix(res);
    break;
    case 5: System.out.println("Exited from the
    program");
    return;
    default: System.out.println("Wrong input,
    please try again!!");
    }
    }
    }
    // Function to print the matrix
    static void printMatrix(int arr[][])
    {
    int row, col;
    System.out.print("The array elements are : ");
    // Loop to print the elements
    for(row=0;row<3;row++)
    {
    // Used for formatting
    System.out.print("\n");
    for(col=0;col<3;col++)
    {
    System.out.print(arr[row][col]+" ");
    }
    }
    }
    // Function to calculate the sum
    static int[][] add(int[][] mat1,int[][] mat2)
    {
    int row, col, add[][] = new int[3][3];
    for(row=0;row<3;row++)
    for(col=0;col<3;col++)
    add[row][col] = mat1[row][col]+mat2[row][col];
    return add;
    }
    // Function to calculate the difference
    static int[][] sub(int[][] mat1,int[][] mat2)
    {
    int row, col, sub[][] = new int[3][3];
    for(row=0;row<3;row++)
    for(col=0;col<3;col++)
    sub[row][col] = mat1[row][col]-mat2[row][col];
    return sub;
    }
    // Function to calculate the product
    static int[][] prod(int[][] mat1,int[][] mat2)
    {
    int row, col, prod[][] = new int[3][3];
    for(row=0;row<3;row++)
    for(col=0;col<3;col++)
    {
    // Initializes the array element to zero first
    prod[row][col] = 0;
    for(int i = 0; i<3; i++)
    prod[row][col]+=mat1[row][i]*mat2[i][col];
    }
    return prod;
    }
    // Function to find the transpose
    static int[][] trans(int[][] mat)
    {
    int row, col, trans[][] = new int[3][3];
    for(row=0;row<3;row++)
    for(col=0;col<3;col++)
    trans[row][col] = mat[col][row];
    return trans;
    }
    }

    ReplyDelete
  6. Slip no:- [7] [12] [15 ]

    Define a class CricketPlayer (name,no_of_innings,no_of_times_notout, totatruns,
    bat_avg). Create an array of n player objects .Calculate the batting average for each
    player using static method avg(). Define a static sort method which sorts the array on
    the basis of average. Display the player details in sorted order.


    import java.io.*;
    class Cricket
    {
    String name;
    int inning, tofnotout, totalruns;
    float batavg;
    public Cricket()
    {
    name=null;
    inning=0;
    tofnotout=0;
    totalruns=0;
    batavg=0;
    }
    public void get() throws IOException
    {
    BufferedReader br=new BufferedReader(new
    InputStreamReader(System.in));
    System.out.println("Enter the name, no of
    innings, no of times not out, total runs: ");
    name=br.readLine();
    inning=Integer.parseInt(br.readLine());
    tofnotout=Integer.parseInt(br.readLine());
    totalruns=Integer.parseInt(br.readLine());
    }
    public void put()
    {
    System.out.println("Name="+name);
    System.out.println("no of innings="+inning);
    System.out.println("no times
    notout="+tofnotout);
    System.out.println("total runs="+totalruns);
    System.out.println("bat avg="+batavg);
    }
    static void avg(int n, Cricket c[])
    {
    try
    {
    for(int i=0;i<n;i++)
    {
    c[i].batavg=c[i].totalruns/c[i].inning;
    }
    }
    catch(ArithmeticException e)
    {
    System.out.println("Invalid arg");
    }
    }
    static void sort(int n, Cricket c[]){
    String temp1;
    int temp2,temp3,temp4;
    float temp5;
    for(int i=0;i<n;i++)
    {
    for(int j=i+1;j<n;j++)
    {
    if(c[i].batavg<c[j].batavg)
    {
    temp1=c[i].name;
    c[i].name=c[j].name;
    c[j].name=temp1;
    temp2=c[i].inning;
    c[i].inning=c[j].inning;
    c[j].inning=temp2;
    temp3=c[i].tofnotout;
    c[i].tofnotout=c[j].tofnotout;
    c[j].tofnotout=temp3;
    temp4=c[i].totalruns;
    c[i].totalruns=c[j].totalruns;
    c[j].totalruns=temp4;
    temp5=c[i].batavg;
    c[i].batavg=c[j].batavg;
    c[j].batavg=temp5;
    }
    }
    }
    }
    }
    class calculate
    {
    public static void main(String args[])throws
    IOException
    {
    BufferedReader br=new BufferedReader(new
    InputStreamReader(System.in));
    System.out.println("Enter the limit:");
    int n=Integer.parseInt(br.readLine());
    Cricket c[]=new Cricket[n];
    for(int i=0;i<n;i++)
    {
    c[i]=new Cricket();
    c[i].get();
    }
    Cricket.avg(n,c);
    Cricket.sort(n, c);
    for(int i=0;i<n;i++){
    c[i].put();
    }
    }
    }

    ReplyDelete
  7. Slip no :- [ 8] [11]
    Write a Java program to create a Package “SY” which has a class SYMarks (members
    – ComputerTotal, MathsTotal, and ElectronicsTotal). Create another package TY
    which has a class TYMarks (members – Theory, Practicals). Create an objects of
    Student class (having rollNumber, name, SYMarks and TYMarks). Add the marks of
    SY and TY computer subjects and calculate the Grade (‘A’ for >= 70, ‘B’ for >= 60
    ‘C’ for >= 50 , Pass Class for > =40 else ‘FAIL’) and display the result of the student
    in proper format.

    package Assignment2.SY;
    import java.io.BufferedReader;
    import java.io.*;
    public class SYClass {
    public int ct,mt,et;
    public void get() throws IOException{
    System.out.println("Enter marks of students for
    computer, maths and electronics subject out of
    200
    ");
    BufferedReader br=new BufferedReader(new
    InputStreamReader(System.in));
    ct=Integer.parseInt(br.readLine());
    mt=Integer.parseInt(br.readLine());
    et=Integer.parseInt(br.readLine());
    }
    }
    /**************************************
    *************************/
    package Assignment2.TY;
    import java.io.*;
    public class TYClass {
    public int tm,pm;
    public void get() throws IOException{
    System.out.println("Enter the marks of the
    theory out of 400 and practicals out of 200: ");
    BufferedReader br=new BufferedReader(new
    InputStreamReader(System.in));
    tm=Integer.parseInt(br.readLine());
    pm=Integer.parseInt(br.readLine());
    }
    }
    /**************************************
    **********************/
    package Assignment2;
    import Assignment2.SY.*;
    import Assignment2.TY.*;
    import java.io.*;
    class StudentInfo{
    int rollno;
    String name,grade;
    public float gt,tyt,syt;
    public float per;
    public void get() throws IOException{
    System.out.println("Enter roll number and
    name of the student: ");
    BufferedReader br=new BufferedReader(new
    InputStreamReader(System.in));
    rollno=Integer.parseInt(br.readLine());
    name=br.readLine();
    }
    }
    public class StudentMarks {
    public static void main(String[] args) throws
    IOException{
    BufferedReader br=new BufferedReader(new
    InputStreamReader(System.in));
    System.out.println("Enter the number of
    students:");
    int n=Integer.parseInt(br.readLine());
    SYClass sy[]=new SYClass[n];
    TYClass ty[]=new TYClass[n];
    StudentInfo si[]=new StudentInfo[n];
    for(int i=0;i=70) si[i].grade="A";
    else if(si[i].per>=60) si[i].grade="B";
    else if(si[i].per>=50) si[i].grade="C";
    else if(si[i].per>=40) si[i].grade="Pass";
    else si[i].grade="Fail";
    }
    System.out.println("Roll
    No\tName\tSyTotal\tTyTotal\tGrandTotal\tPerc
    entage\tGrade");
    for(int i=0;i<n;i++)
    {
    System.out.println(si[i].rollno+"\t"+si[i].name+"
    \t"+si[i].syt+"\t"+si[i].tyt+"\t"+si[i].gt+"\t\t"+si[i].
    p
    er+"\t\t"+si[i].grade);
    }
    }
    }

    ReplyDelete
  8. Slip no:- [10] [14]

    Define an interface “Operation” which has methods area(),volume().Define a constant
    PI having a value 3.142.Create a class cylinder which implements this interface
    (members – radius, height) Create one object and calculate the area and volume.

    import java.util.Scanner;
    interface Operation{
    double PI=3.142;
    double area();
    double volume();
    }
    class Cylinder implements Operation{
    private double radius;
    private double height;
    public Cylinder(double radius, double height){
    this.radius=radius;
    this.height=height;
    }
    @Override
    public double area(){
    return 2*PI*radius*(radius+height);
    }
    @Override
    public double volume(){
    return PI*radius*radius*height;
    }
    }
    public class AreaVolume{
    public static void main(String[] args){
    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter the radius of
    Cylinder :");
    double radius = scanner.nextDouble();
    System.out.print("Enter the height of
    Cylinder :");
    double height = scanner.nextDouble();
    Operation c= new Cylinder(radius,height);
    System.out.println("Cylinder
    Area :"+c.area());
    System.out.println("Cylinder
    Volumne :"+c.volume());
    scanner.close();
    }
    }

    ReplyDelete
  9. Slip no:- [19]

    Define an abstract class Staff with protected members id and name. Define a
    parameterized constructor. Define one subclass OfficeStaff with member epartment.
    Create n objects of OfficeStaff and display all details.

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    abstract class Staff{
    String name,address;
    }
    class FullTimeStaff extends Staff{
    String department;
    double salary;
    public void accept() throws IOException{
    System.out.println("Enter the name, address,
    department and salary: ");
    BufferedReader br=new BufferedReader(new
    InputStreamReader(System.in));
    name=br.readLine();
    address=br.readLine();
    department=br.readLine();
    salary=Double.parseDouble(br.readLine());
    }
    public void display(){
    System.out.println("Name: "+name);
    System.out.println("Address: "+address);
    System.out.println("Department:
    "+department);
    System.out.println("Salary: "+salary);
    System.out.println("----------------------");
    }
    }
    class PartTimeStaff extends Staff{
    int hours, rate;
    public void accept() throws IOException{
    System.out.println("Enter the name, address,
    No of working hours and rate per hour: ");
    BufferedReader br=new BufferedReader(new
    InputStreamReader(System.in));
    name=br.readLine();
    address=br.readLine();
    hours=Integer.parseInt(br.readLine());
    rate=Integer.parseInt(br.readLine());
    }
    public void display(){
    System.out.println("Name: "+name);
    System.out.println("Address: "+address);
    System.out.println("No of Working Hours:
    "+hours);
    System.out.println("Rate per hour: "+rate);
    System.out.println("----------------------");
    }
    }
    class stafftime{
    public static void main(String [] args) throws
    IOException{
    int i;
    System.out.println("Select Any One: ");
    BufferedReader br=new BufferedReader(new
    InputStreamReader(System.in));
    System.out.println("1.Full Time Staff");
    System.out.println("2.Part Time Satff");
    int ch=Integer.parseInt(br.readLine());
    switch(ch){
    case 1:
    System.out.println("Enter the number of Full
    Time Staff: ");
    int n=Integer.parseInt(br.readLine());
    FullTimeStaff [] l=new FullTimeStaff[n];
    for(i=0;i<n;i++){
    l[i]=new FullTimeStaff();
    l[i].accept();
    }
    for(i=0;i<n;i++){
    l[i].display();
    }
    break;
    case 2:
    System.out.println("Enter the number of Part
    Time Staff: ");
    int m=Integer.parseInt(br.readLine());
    PartTimeStaff [] h=new PartTimeStaff[m];
    for(i=0;i<m;i++){
    h[i]=new PartTimeStaff();
    h[i].accept();
    }
    for(i=0;i<m;i++){
    h[i].display();
    }
    break;
    }
    }
    }

    ReplyDelete
  10. Slip no:- [20]

    Accept the names of two files and copy the contents of the first to the second. First file
    having Book name and Author name in file. Second file having the contents of First file
    and also add the comment ‘end of file’ at the end.

    import java.io.*;
    import java.util.*;
    class Seta3{
    public static void main(String[] args)throws
    IOException
    {
    int c;
    String f1,f2;
    Scanner sc=new Scanner(System.in);
    System.out.println("Enter name of first file: ");
    f1=sc.next();
    System.out.println("Enter name of second file:
    ");
    f2=sc.next();
    FileReader fr=new FileReader(f1);
    FileWriter fw=new FileWriter(f2,true);
    while((c=fr.read())!=-1)
    {
    fw.write(c);
    }
    fw.append("\nEND OF FILE");
    fr.close();
    fw.close();
    }
    }

    ReplyDelete
  11. Slip no :- [21]

    Write a program to read book information (bookid, bookname, bookprice, bookqty) in
    file “book.dat”. Write a menu driven program to perform the following operationsusing
    Random access file: [20]
    i. Search for a specific book by name.
    ii. Display all book and total cost

    .
    import java.io.*;
    import java.util.*;
    class Setb1{
    public static void main(String[] args)throws
    IOException
    {
    String name,line;
    int cost=0,ch,flag=0,i,tcost=0;
    BufferedReader br=new BufferedReader(new
    InputStreamReader(System.in));
    File f=new File("book.dat");
    RandomAccessFile rf=new
    RandomAccessFile(f,"rw");
    do{
    System.out.println("MENU");
    System.out.println("1.Search\n2.Display book
    and total cost");
    System.out.println("Enter your choice: ");
    ch=Integer.parseInt(br.readLine());
    switch(ch)
    {
    case 1:
    rf.seek(0);
    System.out.println("Enter book name to search:
    ");
    name=br.readLine();
    while(rf.getFilePointer()!=f.length())
    {
    line=rf.readLine();
    String a[]=line.split(" ");
    if(a[1].equals(name))
    {
    System.out.println("Book available");
    flag=1;
    break;
    }
    else
    flag=2;
    }
    if(flag==2)
    System.out.println("Book Unavailable");
    break;
    case 2:
    rf.seek(0);
    while(rf.getFilePointer()!=f.length())
    {
    line=rf.readLine();
    String a[]=line.split(" ");
    cost=cost+(Integer.parseInt(a[2])*Integer.parseI
    nt(a[3]));
    System.out.println(a[1]+"\t"+cost);
    tcost=tcost+(Integer.parseInt(a[2])*Integer.pars
    eInt(a[3]));
    }
    System.out.println("Total cost\t"+tcost);
    break; }
    }while(ch!=2); }}

    ReplyDelete
  12. Slip no:- [ 22] [ 30]

    Define class EmailId with members ,username and password. Define default and
    parameterized constructors. Accept values from the command line Throw user defined
    exceptions – “InvalidUsernameException” or “InvalidPasswordException” if the
    username and password are invalid.

    import java.io.*;
    class InvalidUsernameException extends
    Exception{
    public InvalidUsernameException(){
    System.out.println("Invalid Username"); }}
    class InvalidPasswordException extends
    Exception{
    public InvalidPasswordException(){
    System.out.println("Invalid Password"); }}
    class EmailId{
    String uname,pwd;
    public EmailId() {
    uname="";
    pwd=""; }
    public EmailId(String uname,String pwd) {
    this.uname=uname;
    this.pwd=pwd; }
    public static void main(String[] args) {
    String uname,pwd;
    uname=args[0];
    pwd=args[1];
    EmailId ob=new EmailId(uname,pwd);
    try{
    if(("preranasherla").equals(ob.uname))
    System.out.println("Valid Username");
    else
    throw new InvalidUsernameException();
    }catch(InvalidUsernameException e){ }
    try{
    if(("prerana1234").equals(ob.pwd))
    System.out.println("Valid Password");
    else
    throw new InvalidPasswordException();
    }catch(InvalidPasswordException e1){ }
    }
    }

    ReplyDelete
  13. Slip no:- [23]

    Define a class MyDate (day, month, year) with methods to accept and display a MyDate
    object. Accept date as dd, mm, yyyy. Throw user defined exception
    “InvalidDateException” if the date is invalid. Examples of invalid dates : 03 15 2019,
    31 6 2000, 29 2 2021

    import java.io.*;
    class invaliddateexception extends Exception
    {
    invaliddateexception(int n)
    {
    System.out.println("The given date is invalid");
    }
    }
    class invalidmonthexception extends Exception
    {
    invalidmonthexception(int m)
    {
    System.out.println("The given month is invalid");
    }
    }
    class Date
    {
    public static void main(String args[])
    {
    int dd=Integer.parseInt(args[0]);
    int mm=Integer.parseInt(args[1]);
    long yy=Long.parseLong(args[2]);
    try
    {
    if(mm<1||mm>12)
    throw new invalidmonthexception(mm);
    }
    catch(invalidmonthexception e)
    {
    }
    {
    if(mm>=1 && mm<=12)
    {
    switch(mm)
    {
    case 1:
    case 3:
    case 5:
    case 7:
    case 8:
    case 10:
    case 12:
    try
    {
    if(dd>=1 && dd<=31)
    System.out.println("The given Date is Valid");
    else
    throw new invaliddateexception(dd);
    }
    catch(invaliddateexception e)
    {
    }
    break;
    case 4:
    case 6:
    case 9:
    case 11:
    try
    {
    if(dd>=1 && dd<=30)
    System.out.println("The given date valid one");
    else
    throw new invaliddateexception(dd);
    }
    catch(invaliddateexception e)
    {
    }
    break;
    case 2:
    try
    {
    if(yy%4==0 || yy%100==0)
    {
    if(dd>=1 && dd<=29)
    System.out.println("The date is valid and it is a
    leap year");
    }
    else if(dd>=1 && dd<=28)
    System.out.println("The given date is valid");
    else
    throw new invaliddateexception(dd);
    }
    catch(invaliddateexception e)
    {
    }
    break;
    }
    }
    }
    }
    }

    ReplyDelete
  14. Slip no:- [26]

    Create the following GUI screen using appropriate layout managers. Accept the name,
    class , hobbies of the user and apply the changes and display the selected options in a
    text box.

    importjava.awt.event.*;
    importjavax.swing.*;
    importjava.awt.*;
    public class HobbiesDemo extends JFrame
    implements ActionListener,ItemListener
    {
    JLabel l1,l2,l3,l4,l5;
    JTextField tf1;
    JRadioButton rb1,rb2,rb3;
    ButtonGroupbg;
    JCheckBox cb1,cb2,cb3;
    JPanel p1,p2,p3,p4;
    HobbiesDemo()
    {
    l1=new JLabel("Your Name : ");
    l2=new JLabel("Your Class ");
    l3=new JLabel("Your Hobbies");
    l4=new JLabel("");//used to display name &
    class
    l5=new JLabel("");//used to display hobbies
    tf1=new JTextField();
    rb1=new JRadioButton("FYBCS");
    rb2=new JRadioButton("SYBCS");
    rb3=new JRadioButton("TYBCS");
    rb1.addActionListener(this);
    rb2.addActionListener(this);
    rb3.addActionListener(this);
    bg=new ButtonGroup();
    bg.add(rb1);
    bg.add(rb2);
    bg.add(rb3);
    cb1=new JCheckBox("Music");
    cb2=new JCheckBox("Dance");
    cb3=new JCheckBox("Sports");
    cb1.addItemListener(this);
    cb2.addItemListener(this);
    cb3.addItemListener(this);
    p1=new JPanel();
    p1.setLayout(new GridLayout(1,2));
    p1.add(l1); p1.add(tf1);
    p2=new JPanel();
    p2.setLayout(new GridLayout(4,1));
    p2.add(l2);
    p2.add(rb1);
    p2.add(rb2);
    p2.add(rb3);
    p3=new JPanel();
    p3.setLayout(new GridLayout(4,1));
    p3.add(l3);
    p3.add(cb1);
    p3.add(cb2);
    p3.add(cb3);
    p4=new JPanel();
    p4.setLayout(new GridLayout(1,2));
    p4.add(l4);
    p4.add(l5);
    BorderLayout bob=new BorderLayout();
    setLayout(bob);
    add(p1,BorderLayout.NORTH);
    add(p2,BorderLayout.WEST);
    add(p3,BorderLayout.EAST);
    add(p4,BorderLayout.SOUTH);
    setTitle("INFORMATION");
    setSize(500,300);
    setVisible(true);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
    public void actionPerformed(ActionEventae)
    {
    String s="NAME : "+tf1.getText()+" CLASS :
    "+ae.getActionCommand();
    l4.setText(s);
    }
    public void itemStateChanged(ItemEventie)
    {
    String s="";
    if(cb1.isSelected())
    s=s+cb1.getText()+" ";
    if(cb2.isSelected())
    s=s+cb2.getText()+" ";
    if(cb3.isSelected())
    s=s+cb3.getText()+" ";
    l5.setText(" HOBBIES : "+s);
    }
    public static void main(String args[])
    {
    HobbiesDemo hob=new HobbiesDemo();
    }
    }

    ReplyDelete
  15. Slip no:- [4] [25] [29]


    Design a screen to handle the Mouse Events such as MOUSE_MOVED and
    MOUSE_CLICK and display the position of the Mouse_Click in a TextField.


    Import java.awt.*;
    Import java.awt.event.*;
    Import javax.swing.*;
    Class MouseEvents extends JFrame implements
    MouseListener, MouseMotionListener
    {
    String str="";
    JTextArea ta;
    Container c;
    Int x,y;
    MouseEvents()
    {
    }
    c=getContentPane();
    c.setLayout(new FlowLayout());;
    ta=new JTextArea("Click the mouse or move it",
    5,20);
    ta.setFont(new Font("Arial",Font.BOLD,30));
    c.add(ta);
    ta.addMouseListener(this);
    ta.addMouseMotionListener(this);
    public void mouseClicked(MouseEvent me)
    {
    int i=me.getButton();
    if(i==1)
    str+="Clicked Button: Left";
    else if(i==2)
    str+="Clicked Button: Middle";
    else if(i==3)
    str+="Clicked Button: Right";
    this.display();
    }
    public void mouseEntered(MouseEvent me)
    {
    }
    str+="Mouse Entered ";
    this.display();
    public void mouseExited(MouseEvent me)
    {
    }
    str+="MouseExited";
    this.display();
    public void mousePressed(MouseEvent me)
    {
    }
    x=me.getX();
    y=me.getY();
    str+="MousePressed at: "+x+"\t"+y;
    this.display();
    public void mouseReleased(MouseEvent me)
    {
    x=me.getX();
    y=me.getY();
    str+="Mouse Released at:"+x+"\t"+y;
    this.display();
    }
    public void mouseDragged(MouseEvent me)
    {
    }
    x=me.getX();
    y=me.getY();
    str+="MouseDragged at:"+x+"\t"+y;
    this.display();
    public void mouseMoved(MouseEvent me)
    {
    }
    x=me.getX();
    y=me.getY();
    str+="Mouse Moved at:"+x+"\t"+y;
    this.display();
    public void display()
    {
    }
    ta.setText(str);
    str="";
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    MouseEvents mes=new MouseEvents();
    mes.setSize(400,400);
    mes.setVisible(true);
    mes.setDefaultCloseOperation(JFrame.EXIT_ON
    _CLOSE);
    }
    }

    ReplyDelete
  16. Slip no :- [5] [27]

    Write a Java program to design a screen using Awt that will take a user name and
    password. If the user name and password are not same, raise an Exception with
    appropriate message. User can have 3 login chances only. Use clear button to clear the
    TextFields.

    import java.awt.*;
    import java.awt.event.*;
    class InvalidPasswordException extends
    Exception
    {
    InvalidPasswordException()
    {
    System.out.println(” User name and Password is
    not same”);
    }
    }
    public class PasswordDemo extends Frame
    implements ActionListener
    {
    Label uname,upass;
    TextField nametext;
    TextField passtext,msg;
    Button login,Clear;
    Panel p;
    int attempt=0;
    char c= ‘ * ‘ ;
    public void login()
    {
    p=new Panel();
    uname=new Label(“Use Name: ” ,Label.CENTER);
    upass=new Label (“Password: “,Label.RIGHT);
    nametext=new TextField(20);
    passtext =new TextField(20);
    passtext.setEchoChar(c);
    msg=new TextField(10);
    msg.setEditable(false);
    login=new Button(“Login”);
    Clear=new Button(“Clear”);
    login.addActionListener(this);
    Clear.addActionListener(this);
    p.add(uname);
    p.add(nametext);
    p.add(upass);
    p.add(passtext);
    p.add(login);
    p.add(Clear);
    p.add(msg);
    add(p);
    setTitle(“Login “);
    setSize(290,200);
    setResizable(false);
    setVisible(true);
    }
    public void actionPerformed(ActionEvent ae)
    {
    Button btn=(Button)(ae.getSource());
    if(attempt<3)
    {
    if((btn.getLabel())==”Clear”)
    {
    nametext.setText(“”);
    passtext.setText(“”);
    }
    if((btn.getLabel()).equals(“Login”))
    {
    try
    {
    String user=nametext.getText();
    String upass=passtext.getText();
    if(user.compareTo(upass)==0)
    {
    msg.setText(“Valid”);
    System.out.println(“Username is valid”);
    }
    else
    {
    throw new InvalidPasswordException();
    }
    }
    catch(Exception e)
    {
    msg.setText(“Error”);
    }
    attempt++;
    }
    }
    else
    {
    System.out.println(“you are using 3 attempt”);
    System.exit(0);
    }
    }
    public static void main(String args[])
    {
    PasswordDemo pd=new PasswordDemo();
    pd.login();
    }
    }

    ReplyDelete