Programming Pandit

c/c++/c#/Javav/Python


Latest Update

Wednesday, February 12, 2025

February 12, 2025

Converter Application in java using package

 Objective :  Develop a java program to implement currency converter (Dollar to INR, EURO to INR, Yen to INR and vice versa), distance converter (meter to KM, miles to KM and vice versa), time converter (hours to minutes, seconds and vice versa) using packages.


Code: 

// Package for currency conversion

package converters.currency;

public class CurrencyConverter {

    public static double dollarToINR(double dollar) { return dollar * 83.0; }

    public static double inrToDollar(double inr) { return inr / 83.0; }

    public static double euroToINR(double euro) { return euro * 90.0; }

    public static double inrToEuro(double inr) { return inr / 90.0; }

    public static double yenToINR(double yen) { return yen * 0.56; }

    public static double inrToYen(double inr) { return inr / 0.56; }

}


// Package for distance conversion

package converters.distance;

public class DistanceConverter {

    public static double metersToKM(double meters) { return meters / 1000.0; }

    public static double kmToMeters(double km) { return km * 1000.0; }

    public static double milesToKM(double miles) { return miles * 1.609; }

    public static double kmToMiles(double km) { return km / 1.609; }

}


// Package for time conversion

package converters.time;

public class TimeConverter {

    public static double hoursToMinutes(double hours) { return hours * 60.0; }

    public static double minutesToHours(double minutes) { return minutes / 60.0; }

    public static double secondsToMinutes(double seconds) { return seconds / 60.0; }

    public static double minutesToSeconds(double minutes) { return minutes * 60.0; }

}


// Main class with user interaction

import java.util.Scanner;

import converters.currency.CurrencyConverter;

import converters.distance.DistanceConverter;

import converters.time.TimeConverter;


public class ConverterApp {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        while (true) {

            System.out.println("Select conversion type:");

            System.out.println("1. Currency Converter");

            System.out.println("2. Distance Converter");

            System.out.println("3. Time Converter");

            System.out.println("4. Exit");

            int choice = scanner.nextInt();


            if (choice == 4) break;

            double value, result;

            switch (choice) {

                case 1:

                    System.out.println("Select conversion: 1. Dollar to INR, 2. INR to Dollar, 3. Euro to INR, 4. INR to Euro, 5. Yen to INR, 6. INR to Yen");

                    int currencyChoice = scanner.nextInt();

                    System.out.println("Enter amount: ");

                    value = scanner.nextDouble();

                    result = switch (currencyChoice) {

                        case 1 -> CurrencyConverter.dollarToINR(value);

                        case 2 -> CurrencyConverter.inrToDollar(value);

                        case 3 -> CurrencyConverter.euroToINR(value);

                        case 4 -> CurrencyConverter.inrToEuro(value);

                        case 5 -> CurrencyConverter.yenToINR(value);

                        case 6 -> CurrencyConverter.inrToYen(value);

                        default -> 0;

                    };

                    System.out.println("Converted value: " + result);

                    break;

                case 2:

                    System.out.println("Select conversion: 1. Meters to KM, 2. KM to Meters, 3. Miles to KM, 4. KM to Miles");

                    int distanceChoice = scanner.nextInt();

                    System.out.println("Enter distance: ");

                    value = scanner.nextDouble();

                    result = switch (distanceChoice) {

                        case 1 -> DistanceConverter.metersToKM(value);

                        case 2 -> DistanceConverter.kmToMeters(value);

                        case 3 -> DistanceConverter.milesToKM(value);

                        case 4 -> DistanceConverter.kmToMiles(value);

                        default -> 0;

                    };

                    System.out.println("Converted value: " + result);

                    break;

                case 3:

                    System.out.println("Select conversion: 1. Hours to Minutes, 2. Minutes to Hours, 3. Seconds to Minutes, 4. Minutes to Seconds");

                    int timeChoice = scanner.nextInt();

                    System.out.println("Enter time value: ");

                    value = scanner.nextDouble();

                    result = switch (timeChoice) {

                        case 1 -> TimeConverter.hoursToMinutes(value);

                        case 2 -> TimeConverter.minutesToHours(value);

                        case 3 -> TimeConverter.secondsToMinutes(value);

                        case 4 -> TimeConverter.minutesToSeconds(value);

                        default -> 0;

                    };

                    System.out.println("Converted value: " + result);

                    break;

                default:

                    System.out.println("Invalid choice, try again.");

            }

        }

        scanner.close();

        System.out.println("Thank you for using the converter!");

    }

}



Package folder Hierarchey: 

│── ConverterApp.java

│── converters\

│   ├── currency\

│   │   ├── CurrencyConverter.java

│   ├── distance\

│   │   ├── DistanceConverter.java

│   ├── time\

│       ├── TimeConverter.java



Output:

Compilation of source codes for class file of packages:



Runing of the Main class :






Wednesday, February 5, 2025

February 05, 2025

User input for addition of two numbers JAVA

Java program that takes user input for two numbers and performs addition: 


import java.util.Scanner;  // Import the Scanner class


public class AdditionProgram 

{

    public static void main(String[] args) {

        // Create a Scanner object for user input

        Scanner scanner = new Scanner(System.in);

        

        // Prompt user for first number

        System.out.print("Enter the first number: ");

        int num1 = scanner.nextInt();

        

        // Prompt user for second number

        System.out.print("Enter the second number: ");

        int num2 = scanner.nextInt();

   

        // Perform addition

        int sum = num1 + num2;

        

        // Display result

        System.out.println("The sum is: " + sum);

        

        // Close scanner

        scanner.close();

    }

}




Output :





February 05, 2025

Object Oriented Programming, objects and classes

Introduction to OOP

Object-Oriented Programming (OOP) is a programming paradigm that organizes software design around objects rather than functions and logic. Java is an object-oriented language that follows the principles of OOP to make the code more modular, reusable, and scalable.

Key Principles of OOP

  1. Encapsulation:

    • Wrapping data (variables) and methods together in a single unit (class).
    • Achieved using access modifiers like private, protected, and public.
    • Example: Using getter and setter methods to access private data.
  2. Abstraction:

    • Hiding implementation details and exposing only essential features.
    • Achieved using abstract classes and interfaces.
  3. Inheritance:

    • Creating a new class based on an existing class to promote code reuse.
    • Achieved using the extends keyword for class inheritance.
  4. Polymorphism:

    • Ability of a function or object to take multiple forms.
    • Achieved using method overloading (same method name but different parameters) and method overriding (subclass redefines a method from its superclass).


Objects and Classes in Java

1. Class in Java

A class is a blueprint for creating objects. It defines properties (fields/variables) and behaviors (methods/functions) that its objects will have.

Syntax of a Class






Monday, February 3, 2025

February 03, 2025

Electricity Bill Calculator Prgram in JAVA

Objective: Develop a Java application to generate Electricity bill. Create a class with the following members: Consumer no., consumer name, previous month reading, current month reading, type of EB connection (i.e domestic or commercial). Compute the bill amount using the following tariff. If the type of the EB connection is domestic, calculate the amount to be paid as follows:


First 100 units - Rs. 1 per unit

101-200 units - Rs. 2.50 per unit
201 -500 units - Rs. 4 per unit
> 501 units - Rs. 6 per unit

If the type of the EB connection is commercial, calculate the amount to be paid as follows:
First 100 units - Rs. 2 per unit
101-200 units - Rs. 4.50 per unit
201 -500 units - Rs. 6 per unit
 > 501 units - Rs. 7 per unit

 


import java.util.Scanner;


class ElectricityBill {

    private int consumerNo;

    private String consumerName;

    private int prevReading;

    private int currReading;

    private String ebType;

    

    public ElectricityBill(int consumerNo, String consumerName, int prevReading, int currReading, String ebType) {

        this.consumerNo = consumerNo;

        this.consumerName = consumerName;

        this.prevReading = prevReading;

        this.currReading = currReading;

        this.ebType = ebType;

    }

    

    public double calculateBill() {

        int unitsConsumed = currReading - prevReading;

        double amount = 0;

        

        if (ebType.equalsIgnoreCase("domestic")) {

            if (unitsConsumed <= 100)

                amount = unitsConsumed * 1.0;

            else if (unitsConsumed <= 200)

                amount = 100 * 1.0 + (unitsConsumed - 100) * 2.50;

            else if (unitsConsumed <= 500)

                amount = 100 * 1.0 + 100 * 2.50 + (unitsConsumed - 200) * 4.0;

            else

                amount = 100 * 1.0 + 100 * 2.50 + 300 * 4.0 + (unitsConsumed - 500) * 6.0;

        } 

        else if (ebType.equalsIgnoreCase("commercial")) {

            if (unitsConsumed <= 100)

                amount = unitsConsumed * 2.0;

            else if (unitsConsumed <= 200)

                amount = 100 * 2.0 + (unitsConsumed - 100) * 4.50;

            else if (unitsConsumed <= 500)

                amount = 100 * 2.0 + 100 * 4.50 + (unitsConsumed - 200) * 6.0;

            else

                amount = 100 * 2.0 + 100 * 4.50 + 300 * 6.0 + (unitsConsumed - 500) * 7.0;

        } else {

            System.out.println("Invalid connection type!");

        }

        return amount;

    }

    

    public void displayBill() {

        System.out.println("\nElectricity Bill");

        System.out.println("Consumer Number: " + consumerNo);

        System.out.println("Consumer Name: " + consumerName);

        System.out.println("Units Consumed: " + (currReading - prevReading));

        System.out.println("Type of Connection: " + ebType);

        System.out.println("Bill Amount: Rs. " + calculateBill());

    }

}


public class ElectricityBillCalculator {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        

        System.out.print("Enter Consumer Number: ");

        int consumerNo = sc.nextInt();

        sc.nextLine(); 

        

        System.out.print("Enter Consumer Name: ");

        String consumerName = sc.nextLine();

        

        System.out.print("Enter Previous Month Reading: ");

        int prevReading = sc.nextInt();

        

        System.out.print("Enter Current Month Reading: ");

        int currReading = sc.nextInt();

        sc.nextLine();

        

        System.out.print("Enter Type of EB Connection (Domestic/Commercial): ");

        String ebType = sc.nextLine();

        

        ElectricityBill bill = new ElectricityBill(consumerNo, consumerName, prevReading, currReading, ebType);

        bill.displayBill();

      

        sc.close();

    }

}



Output : 




Tuesday, November 26, 2024

November 26, 2024

Updating a File

Updating a file


Updating a file in C++ involves reading the file, making the necessary modifications, and then writing the updated data back to the file. Below is a structured explanation and example of how to do this:


Steps to Update a File:

Step 1: Write Initial Content to the File

  1. Open the file in write mode (std::ofstream).
  2. Write the initial data into the file line by line.
  3. Close the file to ensure data is saved properly.

Step 2: Read the File into a Data Structure

  1. Open the file in read mode (std::ifstream).
  2. Use a loop to read each line from the file and store it in a suitable data structure, such as a std::vector<std::string>.
  3. Close the file after reading all its content.

Step 3: Modify the Required Content

  1. Identify the specific line or lines that need to be updated using the index in the vector.
  2. Modify the content by replacing or appending as needed.

Step 4: Write the Updated Content Back to the File

  1. Open the file in truncate mode (std::ofstream with std::ios::trunc), which clears the file before writing.
  2. Write each line from the updated data structure back to the file.
  3. Close the file to ensure the changes are saved.

Summary of the Workflow

  1. File Creation: Initially create a file with default content.
  2. Content Reading: Read the current content for processing.
  3. Content Modification: Perform updates on specific parts of the data.
  4. Content Overwriting: Write the updated data back to the file.

These steps provide a structured approach to handling file operations in C++.

Program:

#include <iostream>

#include <fstream>

#include <vector>

#include <string>

int main() 

{

    std::string filename = "data.txt";

    // Step 1: Write initial content to the file

    {

        std::ofstream outputFile(filename);

        if (!outputFile.is_open()) 

{

            std::cerr << "Error: Unable to open file for writing initial content.\n";

            return 1;

}

        // Writing initial content

        outputFile << "Line 1: Hello World\n";

        outputFile << "Line 2: Welcome to C++\n";

        outputFile << "Line 3: File Operations\n";

        outputFile.close();

        std::cout << "Initial content written to the file.\n";

    }

    // Step 2: Read the file into a vector

    std::vector<std::string> lines;

    std::string line;

    std::ifstream inputFile(filename);

    if (!inputFile.is_open()) {

        std::cerr << "Error: Unable to open file for reading.\n";

        return 1;

    }

    while (std::getline(inputFile, line)) 

{

        lines.push_back(line);

    }

    inputFile.close();

    // Step 3: Modify the specific line

    if (lines.size() >= 2) {

        lines[1] = "Line 2: Updated Content"; // Update the second line

    }

else 

{

        std::cerr << "Error: File does not have enough lines to update.\n";

        return 1;

    }

    // Step 4: Write the updated content back to the file

    std::ofstream outputFile(filename, std::ios::trunc);

    if (!outputFile.is_open()) 

{

        std::cerr << "Error: Unable to open file for writing updated content.\n";

        return 1;

 }

    for (const auto& updatedLine : lines) 

{

        outputFile << updatedLine << "\n";

  }

    outputFile.close();

    std::cout << "File updated successfully.\n";

    return 0;

}


Output:



Sunday, November 17, 2024

November 17, 2024

Sequential Input and Output Operations in C++

 Sequential Input and Output Operations in C++

Sequential input and output operations in C++ involve processing data in a file in the order in which it is stored. These operations are straightforward and suited for applications where the data is read or written linearly.

C++ provides classes and functions for sequential I/O through the <fstream> library. The most commonly used classes are:

  • ifstream: For input (reading data from files).
  • ofstream: For output (writing data to files).
  • fstream: For both input and output operations.

Basic Workflow of Sequential I/O

  1. Input Operations:

    • Open a file for reading using ifstream.
    • Read data sequentially until the end of the file.
    • Close the file after reading.
  2. Output Operations:

    • Open a file for writing using ofstream.
    • Write data sequentially to the file.
    • Close the file after writing.

Example: Sequential Output Operation

Writing data sequentially to a file.




Example: Sequential Input Operation

Reading data sequentially from a file.


Program:


#include <iostream>

#include <fstream>

#include <string>

using namespace std;


int main() {

    ifstream infile("example.txt");

    if (!infile) {

        cout << "Error opening file for reading!" << endl;

        return 1;

    }

    string line;

    // Sequentially reading data from the file

    while (getline(infile, line)) {

        cout << line << endl; // Print each line

    }

    infile.close();

    return 0;

}