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 CS355 (Core Java)


/* 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:




/* 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:





/** 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:




/* 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:



/* 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:



Comments

Popular posts from this blog

First Year Web Technology Practical Slips Solution

SYBSc (CS) Sem III : Data Structure Slip 14 Que - 2

SYBSc (CS) Sem III : Data Structure Slip 20 Que - 2