BCSL-043 Solved Free Assignment 2024-25 Sem 4
Â
Q1: (a) Write java program to find the simple interest on a savings account. Define appropriate class, constructor and methods in your program. Make necessary assumptions.Â
(b) Write a java program to print first 50 fibonacci numbers . Define appropriate class, constructor and methods in your program.Â
Ans:-Â Â (a): Java Program to Find Simple Interest on a Savings Account
In this task, we will create a class called `SavingsAccount` with a constructor to initialize the principal amount, interest rate, and time. We will define a method `calculateSimpleInterest()` to compute the simple interest using the formula:
\[
\text{Simple Interest} = \frac{P \times R \times T}{100}
\]
Where:
- \(P\) is the principal amount,
- \(R\) is the rate of interest per annum,
- \(T\) is the time in years.
#### Java Program for Simple Interest:
```java
class SavingsAccount {
  // Instance variables
  private double principal;
  private double rateOfInterest;
  private double timePeriod;
  // Constructor to initialize account details
  public SavingsAccount(double principal, double rateOfInterest, double timePeriod) {
    this.principal = principal;
    this.rateOfInterest = rateOfInterest;
    this.timePeriod = timePeriod;
  }
  // Method to calculate simple interest
  public double calculateSimpleInterest() {
    return (principal * rateOfInterest * timePeriod) / 100;
  }
  // Main method to demonstrate functionality
  public static void main(String[] args) {
    // Assumptions
    double principal = 10000; // Principal amount in currency
    double rate = 5.5;     // Interest rate (in percentage)
    double time = 2;      // Time period (in years)
    // Create an instance of SavingsAccount
    SavingsAccount account = new SavingsAccount(principal, rate, time);
    // Calculate and display simple interest
    double interest = account.calculateSimpleInterest();
    System.out.println("Simple Interest on the savings account: " + interest);
  }
}
```
 Explanation:
- The `SavingsAccount` class has three instance variables: `principal`, `rateOfInterest`, and `timePeriod`.
- The constructor initializes these variables, and the method `calculateSimpleInterest()` computes the simple interest.
- In the `main()` method, an instance of `SavingsAccount` is created, and the simple interest is calculated and displayed.
---
 (b): Java Program to Print First 50 Fibonacci Numbers
The Fibonacci sequence is a series of numbers where the next number is found by adding up the two numbers before it. The sequence starts with 0 and 1, and the following formula applies:
\[
F(n) = F(n-1) + F(n-2)
\]
Java Program to Print First 50 Fibonacci Numbers:
```java
class FibonacciSeries {
  // Method to print the first n Fibonacci numbers
  public void printFibonacci(int n) {
    long first = 0, second = 1; // Starting values of the Fibonacci series
    // Print the first n Fibonacci numbers
    System.out.println("First " + n + " Fibonacci numbers:");
    System.out.print(first + " " + second + " ");
    for (int i = 3; i <= n; i++) {
      long next = first + second;
      System.out.print(next + " ");
      first = second;
      second = next;
    }
    System.out.println(); // Move to the next line after printing the series
  }
  // Main method
  public static void main(String[] args) {
    // Create an instance of the FibonacciSeries class
    FibonacciSeries fibonacci = new FibonacciSeries();
    // Print the first 50 Fibonacci numbers
    fibonacci.printFibonacci(50);
  }
}
```
 Explanation:
- The `FibonacciSeries` class contains a method `printFibonacci()` that prints the first `n` Fibonacci numbers.
- The method starts by initializing the first two numbers of the sequence (`first` and `second`).
- A loop is used to generate the remaining Fibonacci numbers, and the sum of the two previous numbers is calculated to determine the next number.
- The `main()` method creates an instance of `FibonacciSeries` and calls the `printFibonacci()` method to display the first 50 Fibonacci numbers.
These programs demonstrate the use of classes, constructors, and methods in Java to solve basic mathematical problems such as calculating simple interest and generating Fibonacci numbers.
Q2: (a) Write a program to demonstrate multilevel inheritance implementation. Make suitable provisions of exceptions handling in your program.Â
(b) Create an applet which take a number as input and display whether the given number is even or odd. If the input number is less than 1 then ask user to re-enter the input. Use appropriate components, layout and formatting in your program.Â
Ans:-Â Â (a): Java Program to Demonstrate Multilevel Inheritance with Exception Handling
In multilevel inheritance, a class is derived from a class that is already derived from another class. We will create three classes: `Person`, `Employee`, and `Manager` to demonstrate multilevel inheritance. Additionally, we'll implement exception handling to manage invalid inputs, such as when an employee's salary is negative.
 Java Program for Multilevel Inheritance:
```java
// Base class
class Person {
  protected String name;
  protected int age;
  public Person(String name, int age) {
    this.name = name;
    this.age = age;
  }
  public void displayPersonInfo() {
    System.out.println("Name: " + name);
    System.out.println("Age: " + age);
  }
}
// Derived class (inherits from Person)
class Employee extends Person {
  protected String employeeId;
  protected double salary;
  public Employee(String name, int age, String employeeId, double salary) throws Exception {
    super(name, age);
    this.employeeId = employeeId;
    // Handling salary exception
    if (salary < 0) {
      throw new Exception("Salary cannot be negative");
    }
    this.salary = salary;
  }
  public void displayEmployeeInfo() {
    displayPersonInfo();
    System.out.println("Employee ID: " + employeeId);
    System.out.println("Salary: $" + salary);
  }
}
// Further derived class (inherits from Employee)
class Manager extends Employee {
  private String department;
  public Manager(String name, int age, String employeeId, double salary, String department) throws Exception {
    super(name, age, employeeId, salary);
    this.department = department;
  }
  public void displayManagerInfo() {
    displayEmployeeInfo();
    System.out.println("Department: " + department);
  }
  public static void main(String[] args) {
    try {
      // Creating a Manager object (multilevel inheritance)
      Manager manager = new Manager("Alice", 35, "E123", 75000, "IT");
      // Displaying manager's information
      manager.displayManagerInfo();
    } catch (Exception e) {
      System.out.println("Error: " + e.getMessage());
    }
  }
}
```
 Explanation:
- **Class Hierarchy**:
 - `Person`: Base class with common attributes `name` and `age`.
 - `Employee`: Derived from `Person`, adds `employeeId` and `salary`.
 - `Manager`: Derived from `Employee`, adds `department`.
- Exception Handling: We use `throws Exception` in the constructors to handle cases where salary is negative.
- The `main()` method creates a `Manager` object and displays all the relevant information by calling methods from the hierarchy.
---
 (b): Applet to Check if a Number is Even or Odd
In this program, we will create an applet that takes a number as input and determines if it is even or odd. If the input number is less than 1, the applet prompts the user to re-enter the number. We will use components such as `TextField`, `Label`, and `Button` for interaction.
 Java Applet Program for Even or Odd Check:
```java
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class EvenOddApplet extends Applet implements ActionListener {
  Label inputLabel, resultLabel;
  TextField numberInput;
  Button checkButton;
  public void init() {
    // Set layout of the applet
    setLayout(new FlowLayout());
    // Input components
    inputLabel = new Label("Enter a number:");
    add(inputLabel);
    numberInput = new TextField(10);
    add(numberInput);
    // Button to check even or odd
    checkButton = new Button("Check Even/Odd");
    checkButton.addActionListener(this);
    add(checkButton);
    // Result label to display output
    resultLabel = new Label();
    add(resultLabel);
  }
  public void actionPerformed(ActionEvent e) {
    try {
      // Get input from text field and parse it to an integer
      int number = Integer.parseInt(numberInput.getText());
      // Check if the number is less than 1
      if (number < 1) {
        resultLabel.setText("Please enter a number greater than 0.");
      } else {
        // Determine if the number is even or odd
        if (number % 2 == 0) {
          resultLabel.setText("The number " + number + " is even.");
        } else {
          resultLabel.setText("The number " + number + " is odd.");
        }
      }
    } catch (NumberFormatException ex) {
      resultLabel.setText("Invalid input. Please enter a valid number.");
    }
  }
}
```
 Explanation:
- **Components Used**:
 - `Label`: For displaying text such as "Enter a number" and results.
 - `TextField`: For taking user input.
 - `Button`: A button to trigger the check for even/odd.
- **Event Handling**: The `ActionListener` interface is implemented, and the `actionPerformed()` method handles the button click event. It retrieves the input, checks for its validity, and displays whether the number is even or odd.
- **Error Handling**: If the input is not a valid number, a `NumberFormatException` is caught, and a message is displayed to the user.
How to Run the Applet:
To run this applet, you would need to compile the code and run it in an applet viewer or embed it into an HTML page using the following HTML code:
```html
<applet code="EvenOddApplet.class" width="400" height="150"></applet>
```
The applet will display a text field for number input, a button to check whether the number is even or odd, and a label to display the result.
No comments: