TYBSc (CS) Sem V : Object Oriented Programming Using Java I Practical Slips Solutions

SAVITRIBAI PHULE PUNE UNIVERSITY, PUNE

T. Y. B.Sc. (Computer Science) Semester V

Practical Examination

      SUBJECT: CS-359 Practical course based on 

CS-355 (Object Oriented Programming Using Java I)


Slip No. 1

/* Q1) Write a Program to print all Prime numbers in an array of ‘n’ elements. (use command line arguments) */

class Slip1

{
public static void main(String args[])
{
System.out.println("The prime numbers are: ");
for(int i = 0; i < args.length; i++)
{
boolean isPrime= true;
int num = Integer.parseInt(args[i]);
for(int j = 2; j < num; j++)
{
if(num%j == 0)
{
isPrime= false;
break;
}
}
if(isPrime== true)
{
System.out.println(num);
}
}
}
}

How run it:










/* Q. 2 - Define an abstract class Staff with protected memebers id and name.  Define a parameterized constructor. Define one subclass OfficeStaff with member department. Create n object of OfficeStaff and display all details.*/

import java.util.*;

abstract class Staff{
protected int id;
protected String name;

Staff(int id, String name)
{
this.id = id;
this.name = name;
}
}

class OfficeStaff extends Staff{
String department;

OfficeStaff(int id, String name, String department)
{
super(id, name);

this.department = department;
}

void display()
{
System.out.println("[id = " + id + " Name = " + name + " Department = " + department + " ]");
}
}

class Slip1_2
{
public static void main(String[] args) {

int id;
String name, department;

Scanner sc = new Scanner(System.in);

System.out.println("How many staff memebers you have to enter: ");
int n = sc.nextInt();

OfficeStaff []os = new OfficeStaff[n];

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

System.out.println("Enter the staff member id number: ");
id = sc.nextInt();

System.out.println("Enter the staff member name: ");
name = sc.next();

System.out.println("Enter the staff member department: ");
department = sc.next();

os[i] = new OfficeStaff(id, name, department);
}
for (int i = 0; i < n; i++)
os[i].display();
}
}

How to run it:



Slip No. 2

/* Q. 1 Write a program to read the First Name and Last Name of a person, his weight and height using
command line arguments. Calculate the BMI Index which is defined as the individual's body mass
divided by the square of their height.
(Hint : BMI = Wts. In kgs / (ht)2)*/

class Slip2_1
{
    public static void main(String args[])
    {
        String FirstName = args[0];
        String LastName = args[1];
        float weight = Float.parseFloat(args[2]);
        float height = Float.parseFloat(args[3]);

        // To convert height centimeter to meter
        height = height / 100;

        float BMI = weight / (height * height);
        
        System.out.println("First Name : " + FirstName);
        System.out.println("Last Name : " + LastName);
        System.out.println("Weight : " + weight);
        System.out.println("Height : " + height);
        System.out.println("The Body Mass Index (BMI) : " + BMI + " kg / m2");
    }
}

How to run it:



/* Q. 2) 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.*/

class CricketPlayer
{
    String name;
    int no_of_innings, no_of_times_notout, totatruns;
    double bat_avg;

    CricketPlayer(String name, int no_of_innings, int no_of_times_notout, int totatruns)
    {
        this.name = name;
        this.no_of_innings = no_of_innings;
        this.no_of_times_notout = no_of_times_notout;
        this.totatruns = totatruns;
    }

    public static double avg(CricketPlayer player)
    {
        if((player.no_of_innings - player.no_of_times_notout) == 0)
        {
            return 0.0;
        }
        
        return (double) player.totatruns / (player.no_of_innings - player.no_of_times_notout);
    }

    public static void sortPlayerByAvg(CricketPlayer players[])
    {
        for (int i = 0; i < players.length - 1; i++)
        {
            for (int j = 0; j < players.length - i - 1; j++)
            {
                if (players[j].bat_avg < players[j + 1].bat_avg)
                {
                    CricketPlayer temp = players[j];
                    players[j] = players[j+1];
                    players[j+1] = temp;
                }
            }
        }
    }

    public void displayPlayerDetails()
    {
        System.out.println("Name : " + name + ", Innings : " + no_of_innings + ", Not Outs : " + no_of_times_notout + ", Total Runs : " + totatruns + ", Batting Average : " + String.format("%.2f", bat_avg));
    }
}
class Slip2_2
{
    public static void main(String args[])
    {
        CricketPlayer players[] = new CricketPlayer[3];

        players[0] = new CricketPlayer("Virat Kohli", 250, 30, 12000);
        players[1] = new CricketPlayer("Rohit Sharma", 220, 20, 9500);
        players[2] = new CricketPlayer("MS Dhoni", 350, 80, 10700);

        for (CricketPlayer player: players)
        {
            player.bat_avg = CricketPlayer.avg(player);
        }

        CricketPlayer.sortPlayerByAvg(players);

        System.out.println("Player details sorted by batting average: ");
        for (CricketPlayer player: players)
        {
            player.displayPlayerDetails();
        }
    }   
}

How to run it:




Slip No. 3

/** Q. 1) Write a program to accept 'n' name of cities from the user and sort them in ascending order. */

import java.util.*;

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

System.out.print("Enter how many city you want to enter : ");
int n = sc.nextInt();

String city[] = new String[n];

        for(int i = 0; i < n; i++)
{
System.out.print("\n\nEnter city name: ");
city[i]= sc.next();
}

String temp;

for(int i = 0; i < n; i++)
{
for(int j=i+1; j < n; j++)
{
if(city[i].compareTo(city[j])>0)
{
temp = city[i];
city[i] = city[j];
city[j] = temp;
}
}
}

System.out.print("\n\nSorted Cities are : ");
for(int i = 0; i < n; i++)
{
System.out.print(city[i]+" ");
}
}
}

How to run it:




/** Q. 2) Define a class patient (patient_name, patient_age, patient_oxy_level, patient_HRCT_report). Create an object of patient. Handle appropriate exception while patient oxygen level less than 95% and HRCT scan report greater than 10, then throw user defined Exception "Patient is Covid Positive(+) and Need to Hospitalized" otherwise display its information.
*/

import java.util.*;

class patient{
String patient_name;
int patient_age;
int patient_oxy_level;
int patient_HRCT_report;

patient(String patient_name, int patient_age, int patient_oxy_level, int patient_HRCT_report)
{
this.patient_name = patient_name;
this.patient_age = patient_age;
this.patient_oxy_level = patient_oxy_level;
this.patient_HRCT_report = patient_HRCT_report;
}
}

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

System.out.println("How many patient you want to insert: ");
int number = sc.nextInt();

patient[] obj = new patient[number];

for(int i = 0; i < number; i++)
{
System.out.println("Enter patient name: ");
String name = sc.next();

System.out.println("Enter patient age: ");
int age = sc.nextInt();

System.out.println("Enter patient oxygen level: ");
int oxylevel = sc.nextInt();

System.out.println("Enter patient HRCT report: ");
int HRCTreport = sc.nextInt();

obj[i] = new patient(name, age, oxylevel, HRCTreport);
}

for(int i = 0; i < number; i++)
{
if(obj[i].patient_oxy_level < 95 && obj[i].patient_HRCT_report > 10)
{
try{
throw new NullPointerException("\n");
}
catch(Exception e)
{
System.out.println("Patient is Covid Positive(+) and Need to Hospitalized");
}
}
else
{
System.out.println("Patient name: "+ obj[i].patient_name);
System.out.println("Patient age " + obj[i].patient_age);
System.out.println("Patient oxygen level " +obj[i].patient_oxy_level);
System.out.println("Patient HRCT report " + obj[i].patient_HRCT_report);
System.out.println();
}
}
}
}

How to run it:




Slip No. 4

/* Q1) Write a program to print an array after changing the rows and columns of a given
two-dimensional array.*/

import java.util.*;

class Slip4_1{
    public static void main(String args[])
    {
        System.out.println("Enter the number of rows and columns: ");
        Scanner sc = new Scanner(System.in);
        int r = sc.nextInt();
        int c = sc.nextInt();

        int matrix[][] = new int[r][c];

        System.out.println("Enter the element of matrix: ");

        for(int i = 0; i < r; i++)
        {
            for(int j = 0; j < c; j++)
            {
                matrix[i][j] = sc.nextInt();
            }
        }

        System.out.println("The Original matrix: ");

        for(int i = 0; i < r; i++)
        {
            for(int j = 0; j < c; j++)
            {
                System.out.print(matrix[i][j] + "  ");
            }
            System.out.println();
        }

        System.out.println("After changing rows and columns of matrix: ");

        for(int i = 0; i < c; i++)
        {
            for(int j = 0; j < r; j++)
            {
                System.out.print(matrix[j][i] + "  ");
            }
            System.out.println();
        }
    }
}

How to run it:




/* Write a 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("Invalid User name and Password.");
}
}

class LoginForm extends Frame implements ActionListener
{
Label name, password;
TextField uname, upassword, msg;
Button login, clear;
Panel p;
int attempt = 0;
char c = '*';

LoginForm(String title)
{
super(title);

setLayout(new FlowLayout());
name = new Label("User name : ");
uname = new TextField(20);

password = new Label("Password : ");
upassword = new TextField(20);
upassword.setEchoChar(c);

msg = new TextField(10);
msg.setEditable(false);

p = new Panel();

p.setLayout(new GridLayout(2, 2, 5, 5));

p.add(name);
p.add(uname);

p.add(password);
p.add(upassword);

login = new Button("Login");
clear = new Button("Clear");
login.addActionListener(this);
clear.addActionListener(this);

p.add(login);
p.add(clear);
p.add(msg);

add(p);

setSize(500, 500);

setVisible(true);

addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e)
{
dispose();
}
});
}
public void actionPerformed(ActionEvent ae)
{
Button btn = (Button)(ae.getSource());

if(attempt < 3)
{
if((btn.getLabel()) == "Clear")
{
uname.setText("");
upassword.setText("");
}

if((btn.getLabel()) == "Login")
{
try{
String user = uname.getText();
String passwd = upassword.getText();

if(user.compareTo(passwd) == 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);
}
}
}

class Slip4_2
{
public static void main(String[] args) {
new LoginForm("Login Form");
}
}

How to run it:




Slip No. 5

/* Q1) Write a program for multilevel inheritance such that Country is inherited from Continent.
State is inherited from Country. Display the place, State, Country and Continent.*/

import java.io.*;

class Continent
{
    String continent;

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    void continentInput() throws IOException
    {
        System.out.println("Enter the continent name: ");
        continent = br.readLine();
    }
}

class Country extends Continent
{
    String country;

    void countryInput() throws IOException
    {
        System.out.println("Enter the country name: ");
        country = br.readLine();
    }
}

class State extends Country
{
    String state;

    void stateInput() throws IOException
    {
        System.out.println("Enter the state name: ");
        state = br.readLine();
    }
}

class Place extends State
{
    String place;

    void placeInput() throws IOException
    {
        System.out.println("Enter the place name: ");
        place = br.readLine();
    }
}

class Slip5_1
{
    public static void main(String args[]) throws IOException
    {
        Place p = new Place();

        p.continentInput();
        p.countryInput();
        p.stateInput();
        p.placeInput();

        System.out.println("Place is : " + p.place);
        System.out.println("State is : " + p.state);
        System.out.println("Country is : " + p.country);
        System.out.println("Continent is : " + p.continent);
    }
}

How to run it:



/* Q2) Write a menu driven program to perform the following operations on multidimensional array
ie matrices :
    1. Addition
    2. Multiplication
    3. Exit
*/

import java.util.*;

class MatrixOperations
{
    public int[][] getMatrixInput(String name)
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter number of rows for "+ name + ": ");
        int rows = sc.nextInt();

        System.out.println("Enter number of columns for "+ name + ": ");
        int columns = sc.nextInt();

        int matrix[][] = new int[rows][columns];

        System.out.println("Enter elements for " + name + ": ");
        for(int i = 0; i < rows; i++)
        {
            for(int j = 0; j < columns; j++)
            {
                System.out.print("Enter element [" + i + "][" + j + "]:");
                matrix[i][j] = sc.nextInt();
            }
        }

        return matrix;
    }

    public void printMatrix(int matrix[][])
    {
        System.out.println("The given matrix is:");
        
        for(int i = 0; i < matrix.length; i++)
        {
            for(int j = 0; j < matrix[0].length; j++)
            {
                System.out.print(matrix[i][j] + "\t");
            }
            System.out.println();
        }
    }

    public int[][] addMatrices(int matrix1[][], int matrix2[][])
    {
        if(matrix1.length != matrix2.length || matrix1[0].length != matrix2[0].length)
        {
            System.out.println("Matrices must have the same dimensions for addition.");
            return null;
        }

        int rows = matrix1.length;
        int columns = matrix1[0].length;

        int sumMatrix[][] = new int[rows][columns];

        for(int i = 0; i < rows; i++)
        {
            for(int j = 0; j < columns; j++)
            {
                sumMatrix[i][j] = matrix1[i][j] + matrix2[i][j];
            }
        }

        return sumMatrix;
    }

    
    public int[][] multiplyMatrices(int matrix1[][], int matrix2[][])
    {
        if(matrix1[0].length != matrix2.length)
        {
            System.out.println("Number of columns in Matrix 1 must be equal to number of rows in Matrix 2 for multiplication. ");
            return null;
        }

        int rows = matrix1.length;
        int columns1 = matrix1[0].length;
        int columns2 = matrix2[0].length;

        int productMatrix[][] = new int[rows][columns2];

        for(int i = 0; i < rows; i++)
        {
            for(int j = 0; j < columns2; j++)
            {
                for(int k = 0; k < columns1; k++)
                {
                        productMatrix[i][j] += matrix1[i][k] * matrix2[k][j];
                }
            }
        }

        return productMatrix;
    }
}

class Slip5_2
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        int choice;
        MatrixOperations m = new MatrixOperations();

        int matrix1[][] = m.getMatrixInput("Matrix 1");
        int matrix2[][] = m.getMatrixInput("Matrix 2");
   
        do{
            System.out.println("\n Matrix Operations Menu: ");
            System.out.println("1. Addition");
            System.out.println("2. Multiplication");
            System.out.println("3. Exit");
            System.out.println("Enter your choice: ");
            choice = sc.nextInt();

            switch (choice) {
                case 1:
                    int addMatrix[][] = m.addMatrices(matrix1, matrix2);
                    m.printMatrix(addMatrix);
                    break;
                case 2:
                    int productMatrix[][] = m.multiplyMatrices(matrix1, matrix2);
                    m.printMatrix(productMatrix);
                    break;
                case 3:
                    System.out.println("Exiting program. Good Bye!!!");
                    break;
                default:
                    System.out.println("Invalid choice. Please try again.");
            }
        }while(choice != 3);

        sc.close();
    }
}

How to run it:




Slip No. 6

/** Q1) Write a program to display the Employee(Empid, Empname, Empdesignation, Empsal) information using toString(). */

class Employee
{    
int Empid, Empsal;
    
String Empname, Empdesignation;
    
    Employee(int id, String name, String designation, int salary)
    {
        Empid = id;
        Empname = name;
        Empdesignation = designation;
        Empsal = salary;
    }

    public String toString()
    {
        return "Employee[Employee id = "+Empid+", Employee Name = "+Empname+", Employee Designation = "+Empdesignation+", Employee Salary = "+Empsal+"]";
    }
}

class Slip6_1
{
    public static void main(String args[])
    {
        Employee e = new Employee(1, "Sunil", "Manager", 450000);
        System.out.println(e.toString());
    }
}

How to run it:









/** Q2) 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.*;

abstract class Order 
{
    int id;
    String 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 = Integer.parseInt(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);
    }
}

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 = Integer.parseInt(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);
    }
}

class Slip6_2 
{
    public static void main(String [] args) throws IOException
    {
        int i;
        System.out.println("Enter your Choice: ");

        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 []p = new PurchaseOrder[n];
                for(i = 0; i < n; i++)
                {
                    p[i] = new PurchaseOrder();
                    p[i].accept();
                }
         
                for(i=0;i<n;i++)
                {
                    p[i].display();
                }
                break;
        
            case 2:
                System.out.println("Enter the number of sales orders: ");
                int m = Integer.parseInt(br.readLine());
                SalesOrder []s = new SalesOrder[m];
        
                for(i = 0; i < m; i++)
                {
                    s[i] = new SalesOrder();
                    s[i].accept();
                }
        
                for(i = 0; i < m; i++)
                {
                    s[i].display();
                }
                break;
        }
    }
}


How to run it:






















Slip No. 7

/* Q. 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.
*/

import java.util.*;

class Bank
{
private String accno;
private String name;
private String acc_type;
private long balance;

Scanner sc = new Scanner(System.in);

    //method to open new account  
    public void openAccount() {  
        System.out.print("Enter Account No: ");  
        accno = sc.next();  
        System.out.print("Enter Account type: ");  
        acc_type = sc.next();  
        System.out.print("Enter Name: ");  
        name = sc.next();  
        System.out.print("Enter Balance: ");  
        balance = sc.nextLong();  
    }

    //method to display account details  
    public void showAccount() {  
        System.out.println("Name of account holder: " + name);  
        System.out.println("Account no.: " + accno);  
        System.out.println("Account type: " + acc_type);  
        System.out.println("Balance: " + balance);  
    }

    //method to deposit money  
    public void deposit() {  
        long amt;  
        System.out.println("Enter the amount you want to deposit: ");  
        amt = sc.nextLong();  
        balance = balance + amt;  
    }

    //method to withdraw money  
    public void withdrawal() {  
        long amt;  
        System.out.println("Enter the amount you want to withdraw: ");  
        amt = sc.nextLong();  
        if (balance >= amt) {  
            balance = balance - amt;  
            System.out.println("Balance after withdrawal: " + balance);  
        } else {  
            System.out.println("Your balance is less than " + amt + "\tTransaction failed...!!" );  
        }  
    }

    //method to search an account number  
    public boolean search(String ac_no) {  
        if (accno.equals(ac_no)) {  
            showAccount();  
            return (true);  
        }  
        return (false);  
    }
}

public class Slip7_1 { 

    public static void main(String arg[]) {  
        
        Scanner sc = new Scanner(System.in);  
        
        //create initial accounts          
        System.out.print("How many number of customers do you want to input? ");  
        int n = sc.nextInt(); 

        Bank C[] = new Bank[n];  
        
        for (int i = 0; i < C.length; i++) {  
            C[i] = new Bank();  
            C[i].openAccount();  
        }  
        
        // loop runs until number 5 is not pressed to exit  
        int ch;  
        do {  
            System.out.println("\n ***Banking System Application***");  
            System.out.println("\n1. Display all account details \n2. Search by Account number\n3. Deposit the amount \n4. Withdraw the amount \n5. Exit ");  
            System.out.println("Enter your choice: ");  
            
            ch = sc.nextInt();

                switch (ch) {  
                    case 1:  
                        for (int i = 0; i < C.length; i++) {  
                            C[i].showAccount();  
                        }  
                        break;  
                    case 2:  
                        System.out.print("Enter account no. you want to search: ");  
                        String ac_no = sc.next();  
                        boolean found = false;  
                        for (int i = 0; i < C.length; i++) {  
                            found = C[i].search(ac_no);  
                            if (found) {  
                                break;  
                            }  
                        }  
                        if (!found) {  
                            System.out.println("Search failed! Account doesn't exist..!!");  
                        }  
                        break;  
                    case 3:  
                        System.out.print("Enter Account no. : ");  
                        ac_no = sc.next();  
                        found = false;  
                        for (int i = 0; i < C.length; i++) {  
                            found = C[i].search(ac_no);  
                            if (found) {  
                                C[i].deposit();  
                                break;  
                            }  
                        }  
                        if (!found) {  
                            System.out.println("Search failed! Account doesn't exist..!!");  
                        }  
                        break;  
                    case 4:  
                        System.out.print("Enter Account No : ");  
                        ac_no = sc.next();  
                        found = false;  
                        for (int i = 0; i < C.length; i++) {  
                            found = C[i].search(ac_no);  
                            if (found) {  
                                C[i].withdrawal();  
                                break;  
                            }  
                        }  
                        if (!found) {  
                            System.out.println("Search failed! Account doesn't exist..!!");  
                        }  
                        break;  
                    case 5:  
                        System.out.println("See you soon...");  
                        break;  
                }  
            }  
            while (ch != 5);  
    }  
}

How to run it:






















/** 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.*;

class Slip7_2
{
    public static void main(String args[]) throws IOException
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        System.out.println("Enter file name: ");
        String fname = br.readLine();

        File f = new File(fname);

        if(f.isFile())
        {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fname));

            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");
    }
}

How to run it:

First create a text file in current folder. e.g. input.txt












Slip No. 8

/** Q1) Create a class Sphere, to calculate the volume and surface area of sphere. (Hint : Surface area=4*3.14(r*r), Volume=(4/3)3.14(r*r*r))*/

class Sphere
{
    int radius;
    Sphere(int radius)
    {
        this.radius = radius;
    }

    double calculateVolume()
    {
        return (4/3) * 3.14 * (radius * radius * radius);
    }

    double calculateSurfaceArea()
    {
        return (4 * 3.14 * (radius * radius));
    }
}
class Slip8_1
{
    public static void main(String args[])
    {
        Sphere s = new Sphere(3);
        System.out.println("The volume of Sphere : " + s.calculateVolume());
        System.out.println("The surface area of Sphere : " + s.calculateSurfaceArea());
    }
}

How to run it:
















/** Q2) Design a screen to handle the Mouse Events such as MOUSE_MOVED and MOUSE_CLICKED and display the position of the Mouse_Click in a TextField. */

import java.awt.*;
import java.awt.event.*;

class MyFrame extends Frame
{
Label l, l1;
    TextField t, t1;
int x, y;

Panel p;

MyFrame(String title)
{
super(title);

setLayout(new FlowLayout()); // Frame

p = new Panel();

p.setLayout(new GridLayout(2, 2, 5, 5));
l = new Label("Co-ordinates of clicking");
t = new TextField(20);

l1 = new Label("Co-ordinates of movement");
t1 = new TextField(20);

p.add(l);
p.add(t);

p.add(l1);
p.add(t1);

add(p);

addMouseListener(new MyClick());
addMouseMotionListener(new MyMove());

setSize(500, 500);
setVisible(true);

addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e)
{
dispose();
}
});
}
class MyClick extends MouseAdapter
{
public void mouseClicked(MouseEvent me)
{
x = me.getX();
y = me.getY();

t.setText("X = "+ x + " Y = " + y);
}
}

class MyMove extends MouseMotionAdapter
{
public void mouseMoved(MouseEvent me)
{
x = me.getX();
y = me.getY();

t1.setText("X = "+ x + " Y = " + y);
}
}
}

class Slip8_2
{
public static void main(String[] args) {
new MyFrame("Slip Number 8");
}
}

How to run it:

















Slip No. 11

/** Q1) Define an interface “Operation” which has method 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 volume. (V = PI * r * r * h) */

interface Operation
{
    double PI = 3.142;
    public double volume();
}

class Cylinder implements Operation
{
    int radius, height;

    Cylinder(int r, int h)
    {
        radius = r; 
        height = h;
    }

    public double volume()
    {
        return (PI * radius * radius * height);
    }
}

class Slip11_1
{
    public static void main(String args[])
    {
        Cylinder c = new Cylinder(2, 5);
        System.out.println("The volume of Cylender is : " + c.volume());
    }
}

How to run it:











/** Q2) Write a program to accept the username and password from user if username and password are not same then raise "Invalid Password" with appropriate msg. */

import java.util.*;

class InvalidPasswordException extends Exception
{
InvalidPasswordException()
{
System.out.println("Invalid Password");
}
}

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

try
{
System.out.println("Enter the username: ");
username = sc.next();

System.out.println("Enter the password: ");
password = sc.next();

if (username.compareTo(password) != 0)
{
throw new InvalidPasswordException();
}
else
{
System.out.println("Username and Password are matched...");
}
}
catch(InvalidPasswordException ip)
{
}
finally{
sc.close();
}

}
}

How to run it:























Slip No. 13

/** Q1) Write a program to accept a file name from command prompt, if the file exits then display number of words and lines in that file.*/

import java.io.*;

class Slip13_1
{
   public static void main(String args[]) throws IOException
   {
        File f = new File(args[0]);

        if(f.exists())
        {
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
            String line;
            int wordCount = 0, lineCount = 0;

            while((line = br.readLine()) != null)
            {
                lineCount++;
                String words[] = line.split("\\s+");
                wordCount += words.length;
            }

            System.out.println("Total number of words : " + wordCount);
            System.out.println("Total number of lines : " + lineCount);
        }
        else
        {
            System.out.println(args[0] + " does not exists.");
        }
   } 
}

How to run it:

Create input.txt file and write some data into it.













/** Write a java program to display the system date and time in various
formats shown below:
Current date is : 31/08/2021
Current date is : 08-31-2021
Current date is : Tuesday August 31 2021
Current date and time is : Fri August 31 15:25:59 IST 2021
Current date and time is : 31/08/21 15:25:59 PM +0530
Note: Use java.util.Date and java.text.SimpleDateFormat class
*/

import java.util.Date;
import java.text.SimpleDateFormat;

class Slip13_2{

public static void main(String args[])
{
Date date = new Date();
/* Current date is : 31/08/2021 */

SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");  
String strDate= formatter.format(date);  
System.out.println("Current date is : " + strDate);
/* Current date is : 08-31-2021 */
formatter = new SimpleDateFormat("MM-dd-yyyy");  
strDate= formatter.format(date);  
System.out.println("Current date is : " + strDate);
/* Current date is : Tuesday August 31 2021 */
formatter = new SimpleDateFormat("EEEEE, MMMMM dd yyyy");  
strDate= formatter.format(date);  
System.out.println("Current date is : " + strDate);

/* Current date and time is : Fri August 31 15:25:59 IST 2021 */
formatter = new SimpleDateFormat("E, MMMMM dd HH:mm:ss z yyyy");
strDate = formatter.format(date);

System.out.println("Current date and time is : " + strDate);

/* Current date and time is : 31/08/21 15:25:59 PM +0530 */

formatter = new SimpleDateFormat("dd/MM/yy HH:mm:ss a Z");
strDate = formatter.format(date);

System.out.println("Current date and time is : " + strDate);

}
}

How to run it:













Slip No. 14

/** Q1) Write a 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 (Use static keyword). */

import java.io.*;

class ZeroNumExc extends Exception{}

public class Slip14_2 {
    static int n;
    public static void main(String args[]){
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

            System.out.print("Enter Number : ");
            n = Integer.parseInt(br.readLine());
            
            if(n == 0)
            {
                throw new ZeroNumExc();
            }
            else
            {
                if(n == 1)
                {
                    System.out.println(n + " is not a prime nor a composite.");
                }
                else{
                    boolean flag = true;

                    for (int i = 2; i < n; i++)
                    {
                        if(n%i == 0)
                        {
                            flag = false;
                            break;
                        }
                    }

                    if(flag)
                        System.out.println("Given number is prime.");
                    else
                        System.out.println("Given number is not prime.");
                }
            }           
        } catch (ZeroNumExc nz) {
            System.out.println("Number is 0");
        }
        catch(Exception e){}        
    }   
}

How to run it:






















/** Q2) 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 to create SY folder and save the SYMarks.java file into it.

package SY;

import java.io.*;

public class SYMarks
{
public int ComputerTotal, MathsTotal, ElectronicTotal;

public void set() throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Computer Total Marks out of 200");
ComputerTotal = Integer.parseInt(br.readLine());

System.out.println("Enter the Maths Total Marks out of 200");
MathsTotal = Integer.parseInt(br.readLine());

System.out.println("Enter the Electronic Total Marks out of 200");
ElectronicTotal = Integer.parseInt(br.readLine());
}
}


2) After that to create TY folder and save the TYMarks.java file into it.

package TY;

import java.io.*;

public class TYMarks
{
public int Theory, Practicals;

public void set() throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Theory Marks out of 400");
Theory = Integer.parseInt(br.readLine());

System.out.println("Enter the Practicals Marks out of 200");
Practicals = Integer.parseInt(br.readLine());
}
}

3) In current folder (Outside of SY and TY) and save the Student.java file into it.

import SY.SYMarks;
import TY.TYMarks;
import java.io.*;

class Student
{
int rollNumber;
String name, grade;
public float grandTotal, syTotal, tyTotal;
public float per;

public void set() throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter roll number of the student");
rollNumber = Integer.parseInt(br.readLine());

System.out.println("Enter name of the student");
name = br.readLine();
}

public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter number of the students");
int n = Integer.parseInt(br.readLine());

SYMarks sy[] = new SYMarks[n];

TYMarks ty[] = new TYMarks[n];

Student s[] = new Student[n];

for (int i = 0; i < n; i++)
{
s[i] = new Student();
sy[i] = new SYMarks();
ty[i] = new TYMarks();

s[i].set();
sy[i].set();
ty[i].set();

s[i].syTotal = sy[i].ComputerTotal + sy[i].MathsTotal + sy[i].ElectronicTotal;
s[i].tyTotal = ty[i].Theory + ty[i].Practicals;

s[i].grandTotal = s[i].syTotal + s[i].tyTotal;

s[i].per = (s[i].grandTotal/1200)*100;

if(s[i].per>=70) 
s[i].grade="A";
  else if(s[i].per>=60) 
  s[i].grade="B";
  else if(s[i].per>=50) 
  s[i].grade="C";
  else if(s[i].per>=40) 
  s[i].grade="Pass";
  else 
  s[i].grade="Fail";
}

System.out.println("Roll No\tName\tSyTotal\tTyTotal\tGrandTotal\tPercentage\tGrade");
for(int i=0;i<n;i++)
{
System.out.println(s[i].rollNumber+"\t"+s[i].name+"\t"+s[i].syTotal+"\t"+s[i].tyTotal+"\t"+s[i].grandTotal+"\t\t"+s[i].per+"\t\t"+s[i].grade);
}
}
}

How to run it:



















Slip No. 15


/** Q1) 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.*/

import java.io.*;

class Slip15_1
{
public static void main(String args[]) throws IOException
{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter first file name: ");
        String iFile = br.readLine();
        System.out.println("Enter second file name: ");
        String oFile = br.readLine();

File ifile = new File(iFile);
File ofile = new File(oFile);

try{
FileReader in = new FileReader(ifile);
FileWriter out = new FileWriter(ofile, true);

int ch;

while((ch = in.read()) != -1)
{
out.write(ch);
}

            System.out.println("Copy the contents of the first to the second file successfully.");

in.close();
out.close();
}
catch(IOException e)
{
System.out.println(e);
System.exit(-1);
}
}
}

How to run it:

Create two text file named as first.txt and second.txt. First file contains the data Name Book and Author name:













/** Q2) Write a program to define a class Account having members custname, accno. Define default and parameterized constructor. Create a subclass called SavingAccount with member savingbal, minbal. Create a derived class AccountDetail that extends the class SavingAccount with members, depositamt and withdrawalamt. Write a appropriate method to display customer details. */


class Account
{
String custname;
double accno;

Account()
{
custname = "";
accno = 0.0;
}

Account(String custname, double accno)
{
this.custname = custname;
this.accno = accno;
}
}

class SavingAccount extends Account
{
double savingbal;
double minbal;

SavingAccount(String custname, double accno, double savingbal, double minbal)
{
super(custname, accno);
this.savingbal = savingbal;
this.minbal = minbal;
}
}

class AccountDetails extends SavingAccount
{
double depositeamt;
double withdrawalamt;

AccountDetails(String custname, double accno, double savingbal, double minbal, double depositeamt, double withdrawalamt)
{
super(custname, accno, savingbal, minbal);
this.depositeamt = depositeamt;
this.withdrawalamt = withdrawalamt;
}

void DispayDetails()
{
System.out.println("The Customer Details :");
System.out.println("The Customer Name :" + custname);
System.out.println("The Customer Account Number :" + accno);
System.out.println("The Customer Saving Balance :" + savingbal);
System.out.println("The Customer Minimum Balance :" + minbal);
System.out.println("The Deposte Amount :" + depositeamt);
System.out.println("The withdrawal Amount :" + withdrawalamt);
}

}

class Slip15_2
{
public static void main(String[] args) {
AccountDetails ad = new AccountDetails("ABC", 123, 12500, 500, 250, 1000);

ad.DispayDetails();
}
}

How to run it:




Comments

Popular posts from this blog

First Year Web Technology Practical Slips Solution

TY B.B.A. (C.A.) Sem V : Core Java Practical Slips Solutions