0% found this document useful (0 votes)
15 views

Latest Oops Practical

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Latest Oops Practical

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Random number generator

package RandomNumberGenerator;

//public class RandomNumberGenerator.RandomNumberGenerator {


//}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class RandomNumberGenerator extends JFrame implements


ActionListener {

private JTextField textField;


private JButton button;
private JButton resetButton;

public RandomNumberGenerator() {

setTitle("Random Number Generator");


setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(350, 200);
setLayout(new FlowLayout());

JPanel panel = new JPanel();


panel.setLayout(new BoxLayout(panel,
BoxLayout.Y_AXIS));

JLabel titleLabel = new JLabel("Click the button below


to generate a random number.");
titleLabel.setHorizontalAlignment(JLabel.CENTER);
add(titleLabel);

button = new JButton("Click here");


button.setBackground(Color.YELLOW);
button.setForeground(Color.CYAN);
button.addActionListener(this);
add(button);

textField = new JTextField(20);


textField.setEditable(false);
textField.setHorizontalAlignment(JTextField.RIGHT);
textField.setBackground(Color.CYAN);
textField.setForeground(Color.BLUE);
add(textField);

resetButton = new JButton("Reset");


resetButton.addActionListener(this);
add(resetButton);
}

public void actionPerformed(ActionEvent e) {

if (e.getSource() == button) {
textField.setText(String.valueOf((int)
(Math.random() * 1000000)));
} else if (e.getSource() == resetButton) {
textField.setText("");
}
}

public static void main(String[] args) {

RandomNumberGenerator randomNumberGenerator = new


RandomNumberGenerator();
randomNumberGenerator.setVisible(true);
}
}

Table
package Table;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;

public class CSVTable {


public static void main(String[] args) {
String fileName = "Data.txt";

List<String> headings = new ArrayList<>();


List<List<String>> data = new ArrayList<>();

try {
BufferedReader br = new BufferedReader(new
FileReader(fileName));
String line;
while ((line = br.readLine()) != null) {
String[] values = line.split("\\|");
if (headings.isEmpty()) {
for (String value : values) {
headings.add(value.trim());
}
} else {
List<String> row = new ArrayList<>();
for (String value : values) {
row.add(value.trim());
}
data.add(row);
}
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}

SwingUtilities.invokeLater(() -> {
try {

UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassNa
me());
} catch (Exception e) {
e.printStackTrace();
}

String[] columnNames = headings.toArray(new


String[0]);
Object[][] rowData = new Object[data.size()][];
for (int i = 0; i < data.size(); i++) {
rowData[i] = data.get(i).toArray();
}

DefaultTableModel model = new


DefaultTableModel(rowData, columnNames);
JTable table = new JTable(model);
JScrollPane scrollPane = new JScrollPane(table);

JFrame frame = new JFrame("CSV Table");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(scrollPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}

Data.txt
Name|Gender|Age|Preference
mrit Kumar|M|20|Veg
Arit Kumari|F|21|Non-Veg
Amit Kum|M|20|Veg
Amrt Kuma|M|10|Non-Veg

Sum of numbers in line


package PresentTheSum;

import java.util.Scanner;

public class SumOfNumbers {


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

System.out.println("Enter a line containing


numbers:");
String inputLine = scanner.nextLine();

try {
int sum = calculateSumOfNumbers(inputLine);
System.out.println("Sum of numbers in the input
line: " + sum);
} catch (NumberFormatException e) {
System.out.println("Error: Non-numeric characters
encountered. Ignoring them.");
}
}

private static int calculateSumOfNumbers(String inputLine)


throws NumberFormatException {
Scanner lineScanner = new Scanner(inputLine);
int sum = 0;

while (lineScanner.hasNext()) {
if (lineScanner.hasNextInt()) {
sum += lineScanner.nextInt();
} else {
// If the next token is not an integer, ignore
it
lineScanner.next();
}
}

return sum;
}
}

Name Validator
package NameValidator;

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

class InvalidNameFormatException extends Exception {


public InvalidNameFormatException(String message) {
super(message);
}
}

public class NameValidator extends Frame implements


ActionListener {
TextField tf;
Button btn;
Label label;

public NameValidator() {
tf = new TextField(20);
btn = new Button("Validate");
label = new Label("");

setLayout(new FlowLayout());
add(tf);
add(btn);
add(label);

btn.addActionListener(this);
}

public void actionPerformed(ActionEvent e) {


String name = tf.getText();

try {
validateName(name);
label.setText("OK");
} catch (InvalidNameFormatException ex) {
label.setText("Invalid name");
}
}

public void validateName(String name) throws


InvalidNameFormatException {
if (name.matches(".*\\d.*")) {
throw new InvalidNameFormatException("Invalid
name. It should not contain numbers.");
}
}

public static void main(String[] args) {


NameValidator frame = new NameValidator();
frame.setTitle("Name Validator");
frame.setSize(300, 100);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}

Coffeemaker

AbstractCoffeeMaker
package CoffeeMaker;

import java.util.Map;
import java.util.HashMap;
public abstract class AbstractCoffeeMaker implements
CoffeeMaker {
private Map<String, Integer> ingredients;

public AbstractCoffeeMaker() {
ingredients = new HashMap<>();
}

protected void addIngredient(String name, int quantity) {


ingredients.put(name, quantity);
}

protected boolean checkIngredients(String name, int


quantity) {
return ingredients.getOrDefault(name, 0) >= quantity;
}

public void brew() {


// default brewing process
}

public void serve() {


// default serving process
}
}
BlackCoffee
package CoffeeMaker;

public class BlackCoffee extends AbstractCoffeeMaker {


public BlackCoffee() {
addIngredient("coffee", 10);
}

@Override
public void brew() {
// brew black coffee recipe
}

@Override
public void serve() {
// serve black coffee
}
}

Cappuccino
package CoffeeMaker;

public class Cappuccino extends AbstractCoffeeMaker {


public Cappuccino() {
addIngredient("coffee", 10);
addIngredient("milk", 150);
addIngredient("foamed milk", 10);
}

@Override
public void brew() {
// brew cappuccino recipe
}

@Override
public void serve() {
// serve cappuccino
}
}

Interface Coffeemaker
package CoffeeMaker;

public interface CoffeeMaker {


void brew();
void serve();
}

Lattee
package CoffeeMaker;

public class Latte extends AbstractCoffeeMaker {


public Latte() {
addIngredient("coffee", 10);
addIngredient("milk", 150);
}

@Override
public void brew() {
// brew latte recipe
}

@Override
public void serve() {
// serve latte
}
}

Scientific calculator

AbstractScientificCalculator
package ScientificCalculator;

import java.util.HashMap;
import java.util.Map;

public abstract class AbstractScientificCalculator implements


ScientificCalculator {

protected Map<Integer, Double> factorialMap = new


HashMap<>();

@Override
public double logarithm(double number, double base) {
return Math.log(number) / Math.log(base);
}

@Override
public double exponential(double number, double power) {
return Math.pow(number, power);
}
@Override
public double root(double number, double degree) {
return Math.pow(number, 1.0 / degree);
}

@Override
public double factorial(int number) {
if (number == 0 || number == 1) {
return 1;
}

if (factorialMap.containsKey(number)) {
return factorialMap.get(number);
}

double factorial = number * factorial(number - 1);


factorialMap.put(number, factorial);

return factorial;
}
}

BasicScientificCalculator
package ScientificCalculator;

public class BasicScientificCalculator extends


AbstractScientificCalculator {

public static void main(String[] args) {


BasicScientificCalculator calculator = new
BasicScientificCalculator();

double logarithm = calculator.logarithm(100, 10);


double exponential = calculator.exponential(2, 3);
double root = calculator.root(8, 2);
double factorial = calculator.factorial(5);

System.out.println("Logarithm: " + logarithm);


System.out.println("Exponential: " + exponential);
System.out.println("Root: " + root);
System.out.println("Factorial: " + factorial);
}
}

Interface ScientificCalculator
package ScientificCalculator;

public interface ScientificCalculator {


double logarithm(double number, double base);
double exponential(double number, double power);
double root(double number, double degree);
double factorial(int number);
}

Shape

Circle
package Shape;

public class Circle extends Shape {


private double radius;

public Circle(double radius) {


this.radius = radius;
}

@Override
void draw() {
System.out.println("Drawing a circle with radius " +
radius);
}

@Override
double calculateArea() {
return Math.PI * radius * radius;
}
}

Main
package Shape;

public class Main {


public static void main(String[] args) {
Shape circle = new Circle(5);
Shape square = new Square(4);
Shape triangle = new Triangle(3, 2);

circle.draw();
square.draw();
triangle.draw();
System.out.println("Area of circle: " +
circle.calculateArea());
System.out.println("Area of square: " +
square.calculateArea());
System.out.println("Area of triangle: " +
triangle.calculateArea());
}
}

Abstract class Shape


package Shape;

public abstract class Shape {


abstract void draw();
abstract double calculateArea();
}

Square
package Shape;

public class Square extends Shape {


private double side;

public Square(double side) {


this.side = side;
}

@Override
void draw() {
System.out.println("Drawing a square with side length
" + side);
}

@Override
double calculateArea() {
return side * side;
}
}

Triangle
package Shape;

public class Triangle extends Shape {


private double base;
private double height;

public Triangle(double base, double height) {


this.base = base;
this.height = height;
}

@Override
void draw() {
System.out.println("Drawing a triangle with base " +
base + " and height " + height);
}

@Override
double calculateArea() {
return 0.5 * base * height;
}
}

String manipulation
package StringManipulation;

import java.util.Scanner;

import java.util.Scanner;

public class StringManipulationProgram {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input;

do {
System.out.println("Select an option:");
System.out.println("a. String compare");
System.out.println("b. String compare ignoring
case");
System.out.println("c. String reverse");
System.out.println("d. Change to uppercase");
System.out.println("e. Change to lowercase");
System.out.println("f. END");

char choice = scanner.next().charAt(0);


scanner.nextLine(); // Consume the newline
character

switch (choice) {
case 'a':
System.out.println("Enter the first
string:");
String str1 = scanner.nextLine();
System.out.println("Enter the second
string:");
String str2 = scanner.nextLine();
compareStrings(str1, str2);
break;

case 'b':
System.out.println("Enter the first
string:");
String str3 = scanner.nextLine();
System.out.println("Enter the second
string:");
String str4 = scanner.nextLine();
compareStringsIgnoreCase(str3, str4);
break;

case 'c':
System.out.println("Enter the string to
reverse:");
input = scanner.nextLine();
reverseString(input);
break;

case 'd':
System.out.println("Enter the string to
convert to uppercase:");
input = scanner.nextLine();
toUpperCase(input);
break;

case 'e':
System.out.println("Enter the string to
convert to lowercase:");
input = scanner.nextLine();
toLowerCase(input);
break;

case 'f':
System.out.println("Program ended.
Goodbye!");
break;

default:
System.out.println("Invalid option. Please
try again.");
}

} while (scanner.hasNext() && scanner.next().charAt(0)


!= 'f');
scanner.close();
}

private static void compareStrings(String str1, String


str2) {
if (str1.equals(str2)) {
System.out.println("The strings are equal.");
} else {
System.out.println("The strings are not equal.");
}
}

private static void compareStringsIgnoreCase(String str1,


String str2) {
if (str1.equalsIgnoreCase(str2)) {
System.out.println("The strings are equal
(ignoring case).");
} else {
System.out.println("The strings are not equal
(ignoring case).");
}
}

private static void reverseString(String str) {


StringBuilder reversed = new
StringBuilder(str).reverse();
System.out.println("Reversed string: " + reversed);
}

private static void toUpperCase(String str) {


System.out.println("Uppercase: " + str.toUpperCase());
}

private static void toLowerCase(String str) {


System.out.println("Lowercase: " + str.toLowerCase());
}
}

Employee Salary

PayrollProcessor
package salary.accounts;

import salary.emp.*;

public class PayrollProcessor {


public static void printEmployeeDetails(Employee employee)
{
System.out.println("Employee Details:");
System.out.println("Name: " + employee.getName());
System.out.println("Employee ID: " +
employee.getEmployeeId());
System.out.println("Category: " +
employee.getCategory());
System.out.println("Basic Pay: " +
employee.getBasicPay());
System.out.println("HRA: " + employee.calculateHRA());
System.out.println("DA: " + employee.calculateDA());
System.out.println("Gross Pay: " +
employee.calculateGrossPay());
System.out.println("Income Tax: " +
employee.calculateIncomeTax());
System.out.println("Allowance: " +
employee.calculateAllowance());
}

public static void main(String[] args) {


// Example usage
Employee employee = new Employee("John Doe", 101,
"Permanent", 50000.0);
printEmployeeDetails(employee);
}
}

Employee

package salary.emp;

public class Employee {


private String name;
private int employeeId;
private String category;
private double basicPay;

public Employee(String name, int employeeId, String


category, double basicPay) {
this.name = name;
this.employeeId = employeeId;
this.category = category;
this.basicPay = basicPay;
}

public double calculateHRA() {


return 0.1 * basicPay;
}

public double calculateDA() {


return 0.05 * basicPay;
}

public double calculateGrossPay() {


return basicPay + calculateHRA() + calculateDA();
}

public double calculateIncomeTax() {


return 0.4 * calculateGrossPay();
}

public double calculateAllowance() {


return 0.02 * basicPay;
}

public String getName() {


return name;
}

public int getEmployeeId() {


return employeeId;
}

public String getCategory() {


return category;
}

public double getBasicPay() {


return basicPay;
}
}

Inner Class
package Innerclass;

// Outer class
class OuterClass {

// Member Inner class


class MemberInner {
void display() {
System.out.println("Member Inner class");
}
}

// Anonymous Inner class


void anonymousInnerMethod() {
// Anonymous Inner class inside a method
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("Anonymous Inner class");
}
};
new Thread(runnable).start();
}

// Local Inner class


void localInnerMethod() {
class LocalInner {
void display() {
System.out.println("Local Inner class");
}
}
LocalInner localInner = new LocalInner();
localInner.display();
}

// Static Nested class


static class StaticNested {
void display() {
System.out.println("Static Nested class");
}
}

// Nested Interface
interface NestedInterface {
void show();
}
}

public class InnerClassExample {


public static void main(String[] args) {
// Creating an instance of the outer class
OuterClass outer = new OuterClass();

// Member Inner class


OuterClass.MemberInner memberInner = outer.new
MemberInner();
memberInner.display();

// Anonymous Inner class


outer.anonymousInnerMethod();

// Local Inner class


outer.localInnerMethod();

// Static Nested class


OuterClass.StaticNested staticNested = new
OuterClass.StaticNested();
staticNested.display();

// Nested Interface
OuterClass.NestedInterface nestedInterface = new
OuterClass.NestedInterface() {
@Override
public void show() {
System.out.println("Nested Interface");
}
};
nestedInterface.show();
}
}

Relative Date of Birth


package RelativeLatest;

import java.util.*;

public class SortDates {


static Map<String, Integer> monthsMap = new HashMap<>();

// Function which initializes the monthsMap


static void sortMonths() {
monthsMap.put("Jan", 1);
monthsMap.put("Feb", 2);
monthsMap.put("Mar", 3);
monthsMap.put("Apr", 4);
monthsMap.put("May", 5);
monthsMap.put("Jun", 6);
monthsMap.put("Jul", 7);
monthsMap.put("Aug", 8);
monthsMap.put("Sep", 9);
monthsMap.put("Oct", 10);
monthsMap.put("Nov", 11);
monthsMap.put("Dec", 12);
}

static int cmp(String date) {


String[] dateParts = date.split(" ");
int day = Integer.parseInt(dateParts[0]);
int month = monthsMap.get(dateParts[1]);
int year = Integer.parseInt(dateParts[2]);

return year * 10000 + month * 100 + day;


}

// Utility function to print the contents


// of the array
static void printDates(String[] dates, int n) {
for (int i = 0; i < n; i++) {
System.out.println(dates[i]);
}
}

public static void main(String[] args) {


String[] dates = { "24 Jul 2017", "25 Jul 2017", "11
Jun 1996",
"01 Jan 2019", "12 Aug 2005", "01 Jan 1997" };
int n = dates.length;

// Order the months


sortMonths();

// Sort the dates


Arrays.sort(dates, (a, b) -> cmp(a) - cmp(b));

// Print the sorted dates


printDates(dates, n);
}
}

// This code is contributed by Prince Kumar

You might also like