Tuesday, July 30, 2024

Java-I Assignment-2

 Assignment 2: Array of Objects and Packages



Set A

a) Create an employee class(id,name,deptname,salary). Define a default and parameterized constructor. Use ‘this’ keyword to initialize instance variables. 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.

Steps:-

i]save program as employee.java

ii]Run the code as

iii] javac employee.java 

iv] java employee

v]Then insert the values as per asked in the program.

Code:-

import java.util.*;


class employee {

    int id;

    String name;

    String deptname;

    double salary;

    static int cnt = 0;


    employee() {


    }//default counstructor


    void setdata(int id, String name, String deptname, double salary) {

        this.id = id;

        this.name = name;

        this.deptname = deptname;

        this.salary = salary;

        cnt++;

        System.out.println("Count of object : " + cnt);

    }//setdata


    void display() {

        System.out.println(this.id + "\t\t" + this.name + "\t\t" + this.deptname + "\t\t" + this.salary);

    }//displat


    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.println("Enter number of employee:");

        int n = sc.nextInt();

        employee e[] = new employee[n];


        for (int i = 0; i < n; i++) {

            e[i] = new employee();


            System.out.println("Enter " + (i + 1) + " employee data");


            System.out.println("Enter id:");

            int id = sc.nextInt();

            sc.nextLine();


            System.out.println("Enter Employee Name:");

            String en = sc.nextLine();


            System.out.println("Enter DeptName:");

            String dn = sc.nextLine();


            System.out.println("Enter Salary:");

            double salary = sc.nextDouble();


            e[i].setdata(id, en, dn, salary);

        }//for


        System.out.println("Employee Records Are:");

        System.out.println("Id\tEmployee Name\t\tDept Name\tSalary");

        for (int i = 0; i < n; i++) {

            e[i].display();

        }

        sc.close();

    }//main

}//class



b) Define Student class(roll_no, name, percentage) 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.

Steps:-

i] save program as studentsort.java

ii]Run the code as

iii] javac studentsort.java 

iv] java studentsort

v]Then insert the values as per asked in the program.


Code:-
import java.util.*;

public class studentsort {
    int roll_no;
    String name;
    double per;

    studentsort() {

    }// default counstructor

    void setdata(int roll_no, String name, double per) {
        this.roll_no = roll_no;
        this.name = name;
        this.per = per;

    }// setdata

    void display() {
        System.out.println(this.roll_no + "\t\t" + this.name + "\t\t" + this.per);
    }// display

    static void sort(studentsort a[], int n) {
        studentsort temp = new studentsort();
        for (int i = 0; i < n - 1; i++) {
            for (int j = i + 1; j < n; j++) {
                if (a[i].per > a[j].per) {
                    temp = a[i];
                    a[i] = a[j];
                    a[j] = temp;
                }
            }
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter number of student:");
        int n = sc.nextInt();
        studentsort s[] = new studentsort[n];

        for (int i = 0; i < n; i++) {
            s[i] = new studentsort();

            System.out.println("Enter " + (i + 1) + " student data");

            System.out.println("Enter Roll no:");
            int rn = sc.nextInt();
            sc.nextLine();

            System.out.println("Enter Student Name:");
            String name = sc.nextLine();

            System.out.println("Enter Percentage:");
            double per = sc.nextDouble();

            s[i].setdata(rn, name, per);
        } // for

        System.out.println("\nStudent Records Are:\n");
        System.out.println("R.No\t\tStud Name\tPercentage");
        for (int i = 0; i < n; i++) {
            s[i].display();
        }

        studentsort.sort(s, n);
        System.out.println("\nSorted Student Details:\n");
        System.out.println("R.No\t\tStud Name\tPercentage");
        for (int i = 0; i < n; i++) {
            s[i].display();
        }
        sc.close();
    }// main
}// class


c) Write a java program to accept 5 numbers using command line arguments sort and display them.

Steps:-

i] save program as sort.java

ii]Run the code as 

iii] javac sort.java 

iv] java sort     // java sort 5 6 2 7 9 3

Code:-

public class Sort {

    public static void main(String[] args) {

        if (args.length == 5) {

            int a[] = new int[5];


            for (int i = 0; i < 5; i++) {

                a[i] = Integer.parseInt(args[i]);

            }

            for (int i = 0; i < 5; i++) {

                for (int j = i + 1; j < 5; j++) {

                    if (a[i] > a[j]) {

                        int t = a[i];

                        a[i] = a[j];

                        a[j] = t;


                    } // if

                } // for


                System.out.println(a[i] + " ");

            } // for

        } // if


    }

}



d) Write a java program that take input as a person name in the format of first, middle and last name and then print it in the form last, first and middle name, where in the middle name first character is capital letter.

Steps:-

i] save program as DisplayName.java

ii]Run the code as

iii] javac DisplayName.java

iv] java DisplayName

v]Then insert the values as per asked in the program.

Code:-
import java.util.*;

public class DisplayName {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.println("Enter first name:");
        String fname = sc.nextLine();

        System.out.println("Enter middle name:");
        String mname = sc.nextLine();

        System.out.println("Enter last name:");
        String lname = sc.nextLine();

        System.out.println("\nFull Name: " + fname + " " + mname + " " + lname + " ");

        String finalname = lname;
        finalname = finalname.concat(" ");
        String ab = mname.substring(0, 1).toUpperCase();

        finalname = finalname.concat(fname);

        String cd = mname.substring(1, mname.length());

        finalname = finalname.concat(" ");
        finalname = finalname.concat(ab);
        finalname = finalname.concat(cd);

        System.out.println("\n--------Updated Name---------\n");
        System.out.println(finalname);
        System.out.println();
        sc.close();
    }
}


Set B

a) 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.

1]First of all u have to create a package as name SY (i.e you have to create one folder named as SY) in this folder save the program SYMarks.java and then compile this program in same directory as javac SYMarks.java and then java SYMarks.(Use program SYMarks.java)

package SY;

public class SYMarks {

    public int ComputerTotal;

    public int MathsTotal;

    public int ElectronicsTotal;

    public SYMarks(int c, int m, int e) {

        ComputerTotal = c;

        MathsTotal = m;

        ElectronicsTotal = e;

    }

    public String toString() {

        return (ComputerTotal + "\t\t" + MathsTotal + "\t\t" + ElectronicsTotal);

    }

}



2]And then you have to create second  package as name TY (i.e you have to create one folder named as TY) in this folder save the program TYMarks.java and then compile this program in same directory as javac TYMarks.java and then java TYMarks.(Use program TYMarks.java).

package TY;

public class TYMarks {

        public int Theory;

    public int Practicals;

    public TYMarks(int t, int p) {

        Theory = t;

        Practicals = p;

    }

    public String toString() {

        return Theory + "\t\t" + Practicals;

    }

}

3] After creating this packages u have to save the main student program as

i]   Student.java

ii]Run the code as

iii] javac Student.java

iv] java Student

v]Then insert the values as per asked in the program.

{Note : Your Student.java program and SY Package & TY Package folders are in Same folder }.

import java.util.Scanner;


import SY.SYMarks;

import TY.TYMarks;


public class Student {

    int rollno;

    String studentname, grade;

    SYMarks sym;

    TYMarks tym;


    Student(int r, String name, SYMarks s, TYMarks t) {

        rollno = r;

        studentname = name;

        sym = s;

        tym = t;


    }


    public String toString() {

        return rollno + "\t" + studentname + "\t" + sym + "\t\t" + tym + "\t";

    }


    void calculategrade() {

        int total = sym.ComputerTotal + tym.Theory + tym.Practicals;

        double per = total / 14;

        if (per >= 70) {

            System.out.println("\tA");

        } else if (per >= 60) {

            System.out.println("\tB");

        } else if (per >= 50) {

            System.out.println("\tC");

        } else if (per >= 40) {

            System.out.println("\tPass");

        } else {

            System.out.println("\tFAIL.!");

        }

    }


    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.println("How Many Students:");

        int n = sc.nextInt();

        Student[] stud = new Student[n];

        for (int i = 0; i < n; i++) {

            System.out.println("Enter " + (i + 1) + " student data");


            System.out.println("Enter Roll no:");

            int roll_no = sc.nextInt();

            sc.nextLine();


            System.out.println("Enter Student Name:");

            String name = sc.nextLine();


            System.out.println("Enter SY Percentage(Comp total,Math total,Elect total):");


            int ct = sc.nextInt();

            int mt = sc.nextInt();

            int et = sc.nextInt();


            SYMarks sym = new SYMarks(ct, mt, et);


            System.out.println("Enter TY Marks (Theory  and Practicals)");

            int th = sc.nextInt();

            int pr = sc.nextInt();

            TYMarks tym = new TYMarks(th, pr);


            stud[i] = new Student(roll_no, name, sym, tym);


        }

        System.out.println("\n*  STUDENT DETAILS *");

        System.out.println("R.No\tName\tCompTotal\tMathTotal\tElectTotal\tTheory\t\tPractical\tGrade");

        for (int i = 0; i < n; i++) {

            System.out.print(stud[i]);

            stud[i].calculategrade();

        }

        sc.close();

    }

}


b) 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.

steps:-

i] save program as CricketPlayer.java

ii]Run the code as

iii] javac CricketPlayer.java

iv] java CricketPlayer

v]Then insert the values as per asked in the program.

import java.util.*;


public class CricketPlayer {

    String name;

    int no_of_innings;

    int no_of_times_notout;

    double totatruns;

    double bat_avg;


    void setdata(String pn, int ni, int no, Double tr) {

        name = pn;

        no_of_innings = ni;

        no_of_times_notout = no;

        totatruns = tr;

    }


    static void avg(CricketPlayer a[], int n) {

        for (int i = 0; i < n; i++) {

            a[i].bat_avg = (a[i].totatruns / (a[i].no_of_innings - a[i].no_of_times_notout));

        }

    }


    void display() {

        System.out.println(name + "\t\t\t" + no_of_innings + "\t\t" + no_of_times_notout + "\t\t"

                + totatruns + "\t\t" + bat_avg);

    }


    static void sort(CricketPlayer a[], int n) {

        CricketPlayer temp = new CricketPlayer();

        for (int i = 0; i < n - 1; i++) {

            for (int j = i + 1; j < n; j++) {

                if (a[i].bat_avg < a[j].bat_avg) {

                    temp = a[i];

                    a[i] = a[j];

                    a[j] = temp;

                }

            }

        }


    }


    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.println("Enter no of Player:");

        int n = sc.nextInt();

        CricketPlayer cp[] = new CricketPlayer[n];


        for (int i = 0; i < n; i++) {

            cp[i] = new CricketPlayer();

            System.out.println("Enter " + (i + 1) + " Player data");

            System.out.println("Enter Player Name : ");

            sc.nextLine();


            String pn = sc.nextLine();

            System.out.println("Enter no of Innings:");

            int ni = sc.nextInt();


            System.out.println("Enter no of times NotOut :");

            int no = sc.nextInt();


            System.out.println("Enter Total Runs :");

            Double tr = sc.nextDouble();


            cp[i].setdata(pn, ni, no, tr);


        }

        System.out.println("\n\t\t\t\t**Player Records**\n");

        System.out.println("Player Name \tNo_Of_Innings \tNo_Of_Times_NotOut \tTotal Runs \tBat Avg");

        

        CricketPlayer.avg(cp, n);

        for (int i = 0; i < n; i++) {

            cp[i].display();

        }

        System.out.println("\n\t\t\t\t**Sorted Player Records**\n");

        CricketPlayer.sort(cp, n);

        System.out.println("Player Name \tNo_Of_Innings \tNo_Of_Times_NotOut \tTotal Runs \tBat Avg");

        for (int i = 0; i < n; i++) {

            cp[i].display();

        }

        sc.close();

    }

}



Set C

a) Write a package for String operation which has two classes Con and Comp. Con class has to concatenates two strings and comp class compares two strings. Also display proper message on execution.

steps:-

i]Create a package as ConComp  (i.e you have to create one folder named as ConComp) in this folder save the program con1.java and then compile this program in same directory as javac con1.java and then java con1 (Use program con1.java).

con1.java

package ConComp;

public class con1 {

    public void displaycon(String s1, String s2) {

        

        System.out.println("Concatenated String : " + s1.concat(s2));

    }

}


a]In the same package you have to save second program as  com1.java and then compile this program in same directory as javac com1.java and then java com1 (Use program com1.java).

comp1.java


package ConComp;

public class comp1 {

    public void displaycomp(String s1, String s2){

        System.out.println("Compared String : " +s1.compareTo(s2));

    }

}


3] After creating this package u have to save the main String program as

i]  Demo.java

ii]Run the code as

iii] javac Demo.java

iv] java Demo

v]Then insert the values as per asked in the program.

{Note : Your Demo.java program and ConComp Package  folder are in Same folder }.

import java.util.Scanner;

import ConComp.*;


public class Demo {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);


        System.out.println("Enter 1St String : ");

        String s1 = sc.nextLine();


        System.out.println("Enter 2nd String : ");

        String s2 = sc.nextLine();


        con1 c = new con1();

        c.displaycon(s1,s2);


        comp1 cm = new comp1();

        cm.displaycomp(s1,s2);


        sc.close();

    }


}


b) Create four member variables for Customer class. Assign public, private, protected and default access modifiers respectively to these variables. Try to access these variables from other classes (Same package and Different package)



No comments:

Post a Comment