Sol Prac Assignment 1 Java
Sol Prac Assignment 1 Java
import java.util.Scanner;
// Calculate area
double area = length * breadth;
System.out.println("Area of rectangle: " + area);
// Calculate perimeter
double perimeter = 2 * (length + breadth);
System.out.println("Perimeter of rectangle: " + perimeter);
scanner.close();
}
}
B: Write a menu driven program to perform the following
operations
IV. Exit
import java.util.Scanner;
do {
System.out.println("Menu:");
System.out.println("1. Calculate the volume of cylinder");
System.out.println("2. Find the factorial of a given number");
System.out.println("3. Check if a number is Armstrong or not");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.print("Enter radius of cylinder: ");
double radius = scanner.nextDouble();
System.out.print("Enter height of cylinder: ");
double height = scanner.nextDouble();
double volume = Math.PI * Math.pow(radius, 2) * height;
System.out.println("Volume of cylinder: " + volume);
break;
case 2:
System.out.print("Enter a number to find factorial: ");
int num = scanner.nextInt();
long factorial = 1;
for (int i = 1; i <= num; i++) {
factorial *= i;
}
System.out.println("Factorial of " + num + " is: " + factorial);
break;
case 3:
System.out.print("Enter a number to check
Armstrong: ");
int number = scanner.nextInt();
int originalNumber = number;
int sum = 0;
while (number != 0) {
int remainder = number % 10;
sum += Math.pow(remainder, 3);
number /= 10;
}
if (sum == originalNumber) {
System.out.println(originalNumber + " is an Armstrong number.");
} else {
System.out.println(originalNumber + " is not an Armstrong number.");
}
break;
case 4:
System.out.println("Exiting... Thank you!");
break;
default:
System.out.println("Invalid choice. Please enter a
valid option.");
}
scanner.close();
}
}
import java.util.Scanner;
scanner.close();
}
}
Set B
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Calendar;
public MyNumber() {
this.data = 0;
}
/**
* Parameterized constructor that initializes the data member to the specified value.
* @param value The value to initialize the data member with.
*/
public MyNumber(int value) {
this.data = value;
}
/**
* Checks if the number is negative.
* @return true if the number is negative, false otherwise.
*/
/**
* Checks if the number is positive.
* @return true if the number is positive, false otherwise.
*/
public boolean isPositive() {
return this.data > 0;
}
/**
* Checks if the number is zero.
* @return true if the number is zero, false otherwise.
*/
public boolean isZero() {
return this.data == 0;
}
/**
* Checks if the number is odd.
* @return true if the number is odd, false otherwise.
*/
public boolean isOdd() {
return this.data % 2 != 0;
}
/**
* Checks if the number is even.
* @return true if the number is even, false otherwise.
*/
public boolean isEven() {
return this.data % 2 == 0;
}
try {
// Convert command line argument to integer
int number = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
System.out.println("Invalid number format. Please provide
an integer.");
}
}
}
I Addition
II Multiplication
IV. Exit
import java.util.Scanner;
switch (choice) {
case 1:
addMatrices();
break;
case 2:
multiplyMatrices();
break;
case 3:
transposeMatrix();
break;
case 4:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice. Please try
again.");
}
} while (choice != 4);
}
System.out.println("Sum of matrices:");
printMatrix(result);
}
if (cols1 != rows2) {
System.out.println("Matrix multiplication is not
possible.");
return;
}
System.out.println("Transposed matrix:");
printMatrix(transposed);
}
Set C
import java.util.Arrays;
import java.util.Scanner;
scanner.close();
}
}
Practical Slip_1 …
// Parameterized constructor
public Staff(int id, String name) {
this.id = id;
this.name = name;
}
// Parameterized constructor
public OfficeStaff(int id, String name, String department) {
super(id, name);
this.department = department;
}
Q1) 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)
try {
weight = Double.parseDouble(args[2]);
height = Double.parseDouble(args[3]);
} catch (NumberFormatException e) {
System.out.println("Invalid number format. Weight and height
should be numeric.");
return;
}
// Calculate BMI
double bmi = weight / (height * height);
Compile and Run the program from the command line, passing the
required arguments: Name Weight and Height
import java.util.Arrays;
import java.util.Comparator;
class CricketPlayer {
String name;
int noOfInnings;
int noOfTimesNotOut;
int totalRuns;
double batAvg;
// Constructor
public CricketPlayer(String name, int noOfInnings, int
noOfTimesNotOut, int totalRuns) {
this.name = name;
this.noOfInnings = noOfInnings;
this.noOfTimesNotOut = noOfTimesNotOut;
this.totalRuns = totalRuns;
this.batAvg = avg(noOfInnings, noOfTimesNotOut, totalRuns);
}
Run
Practical Slip_3 …
Q1)write a programm in java to accept 'n' names of cities from the user and
sort them in ascending order
import java.util.Scanner;
import java.util.Arrays;
// Constructor
public Patient(String name, int age, double oxy_level, double
HRCT_report) {
this.patient_name = name;
this.patient_age = age;
this.patient_oxy_level = oxy_level;
this.patient_HRCT_report = HRCT_report;
}
try {
patient1.checkPatientStatus();
} catch (CovidPositiveException e) {
System.out.println(e.getMessage());
}
}
}
Practical Slip_4 …
Q2) 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.*;
// Create components
Label usernameLabel = new Label("Username:");
usernameField = new TextField(20);
setVisible(true);
}
// Event handling
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == loginButton) {
try {
checkLogin();
} catch (Exception e) {
messageLabel.setText(e.getMessage());
}
} else if (ae.getSource() == clearButton) {
usernameField.setText("");
passwordField.setText("");
messageLabel.setText("");
}
}
if (username.equals(password)) {
messageLabel.setText("Login successful!");
} else {
loginAttempts--;
if (loginAttempts > 0) {
throw new Exception("Username and password do not
match. Attempts left: " + loginAttempts);
} else {
throw new Exception("Login failed. No attempts left.");
}
}
}
// Main method
public static void main(String[] args) {
new LoginScreen();
}
}
Practical Slip_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.
Continent(String continentName) {
this.continentName = continentName;
}
void displayContinent() {
System.out.println("Continent: " + continentName);
}
}
void displayCountry() {
displayContinent();
System.out.println("Country: " + countryName);
}
}
void displayState() {
displayCountry();
System.out.println("State: " + stateName);
System.out.println("Place: " + place);
}
}
javac MultilevelInheritance.java
java MultilevelInheritance
while (true) {
System.out.println("\nMatrix Operations Menu:\n1.
Addition\n2. Multiplication\n3. Exit\nEnter your choice: ");
choice = scanner.nextInt();
if (choice == 3) break;
if (choice == 1) { // Addition
int[][] matrix2 = new int[rows1][cols1];
System.out.println("Enter elements of matrix 2:");
for (int i = 0; i < rows1; i++)
for (int j = 0; j < cols1; j++)
matrix2[i][j] = scanner.nextInt();
class Employee {
private int empId;
private String empName;
private String empDesignation;
private double empSalary;
// Constructor
public Employee(int empId, String empName, String
empDesignation, double empSalary) {
this.empId = empId;
this.empName = empName;
this.empDesignation = empDesignation;
this.empSalary = empSalary;
}
import java.util.Scanner;
@Override
void accept(Scanner scanner) {
System.out.print("Enter Purchase Order ID: ");
id = scanner.nextInt();
scanner.nextLine(); // Consume newline left-over
System.out.print("Enter Purchase Order Description: ");
description = scanner.nextLine();
System.out.print("Enter Vendor Name: ");
vendorName = scanner.nextLine();
}
@Override
void display() {
System.out.println("\nPurchase Order Details:");
System.out.println("ID: " + id);
System.out.println("Description: " + description);
System.out.println("Vendor Name: " + vendorName);
}
}
@Override
void accept(Scanner scanner) {
System.out.print("Enter Sales Order ID: ");
id = scanner.nextInt();
scanner.nextLine(); // Consume newline left-over
System.out.print("Enter Sales Order Description: ");
description = scanner.nextLine();
System.out.print("Enter Customer Name: ");
customerName = scanner.nextLine();
}
@Override
void display() {
System.out.println("\nSales Order Details:");
System.out.println("ID: " + id);
System.out.println("Description: " + description);
System.out.println("Customer Name: " + customerName);
}
}
scanner.close();
}
}
The program will prompt you to enter the details for three
PurchaseOrder and three SalesOrder objects and then display
the entered details for each order.
Sample
Sale
OUTPUT
Practical Slip_7 …
Q1) 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.HashMap;
import java.util.Map;
// Create accounts
bank.createAccount("12345", 1000.00);
bank.createAccount("67890", 500.00);
// Deposit money
bank.deposit("12345", 200.00);
bank.deposit("67890", 50.00);
// Withdraw money
bank.withdraw("12345", 150.00);
bank.withdraw("67890", 100.00); // Should fail due to
insufficient funds
// Get balance
bank.getBalance("12345");
bank.getBalance("67890");
}
}
Expected Output
Q2) Write a program to accept a text file from user and display
the contents of a file in reverse order and change its case.
Before writing the code create a .txt file and save the file in red
hat root directory and provide the path of file at the time of
compilation.
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
try {
// Read the contents of the file into a String
String content = new
String(Files.readAllBytes(Paths.get(filePath)));
scanner.close();
}
changedCaseContent.append(Character.toLowerCase(ch));
} else if (Character.isLowerCase(ch)) {
changedCaseContent.append(Character.toUpperCase(ch));
} else {
changedCaseContent.append(ch); // keep
non-alphabetic characters unchanged
}
}
return changedCaseContent.toString();
}
}
The program will prompt you to enter the path of the text file.
After entering the path, it will display the transformed content.
Practical Slip_8 …
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
@Override
public void mousePressed(MouseEvent e) {
// Not used
}
@Override
public void mouseReleased(MouseEvent e) {
// Not used
}
@Override
public void mouseEntered(MouseEvent e) {
// Not used
}
@Override
public void mouseExited(MouseEvent e) {
// Not used
}
});
@Override
public void mouseMoved(MouseEvent e) {
// Optional: Handle mouse movement if needed
// e.g., update status bar with current mouse position
}
});
}
// Marker interface
public interface ProductMarker {
// This interface does not declare any methods or fields
}
// Default constructor
public Product() {
this.product_id = 0;
this.product_name = "Unknown";
this.product_cost = 0.0;
this.product_quantity = 0;
objectCount++;
}
// Parameterized constructor
public Product(int product_id, String product_name,
double product_cost, int product_quantity) {
this.product_id = product_id;
this.product_name = product_name;
this.product_cost = product_cost;
this.product_quantity = product_quantity;
objectCount++;
}
interface CubeCalculator {
// Abstract method to calculate the cube of a number
double calculateCube(double number);
}
package student;
File: StudentPer.java
package student;
File: Main.java
import student.StudentInfo;
import student.StudentPer;
import java.util.Scanner;
marks[i] = scanner.nextDouble();
studentInfo.displayInfo();
scanner.close();