Sunday, July 21, 2024

File operation

       ->This Java program offers a user-friendly, menu-driven interface for performing fundamental file operations.

       -> It allows users to create, write, read, update, and delete files through a series of straightforward options.

Program :

import java.io.*;

import java.util.Scanner;


/ FS {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        String fileName = "msc1.txt";

        int choice;


        do {

            System.out.println("\nFile Operations Menu:");

            System.out.println("1. Create a File");

            System.out.println("2. Write to the File");

            System.out.println("3. Read from the File");

            System.out.println("4. Update the File");

            System.out.println("5. Delete the File");

            System.out.print("Enter your choice: ");

            choice = scanner.nextInt();

            scanner.nextLine(); // consume the newline


            switch (choice) {

                case 1:

                    createFile(fileName);

                    break;

                case 2:

                    System.out.print("Enter content to write: ");

                    String content = scanner.nextLine();

                    writeToFile(fileName, content);

                    break;

                case 3:

                    readFromFile(fileName);

                    break;

                case 4:

                    System.out.print("Enter content to append: ");

                    String updateContent = scanner.nextLine();

                    updateFile(fileName, updateContent);

                    break;

                case 5:

                    deleteFile(fileName);

                    break;

                default:

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

            }

        } while (true);  // Continuous loop until the program is manually terminated


        // scanner.close();  // No need to close scanner since program will run indefinitely

    }


    public static void createFile(String fileName) {

        File file = new File(fileName);

        try {

            if (file.createNewFile()) {

                System.out.println("File created successfully: " + file.getName());

            } else {

                System.out.println("File already exists.");

            }

        } catch (IOException e) {

            System.out.println("An error occurred while creating the file.");

            e.printStackTrace();

        }

    }


    public static void writeToFile(String fileName, String content) {

        try (FileWriter writer = new FileWriter(fileName)) {

            writer.write(content);

            System.out.println("Successfully wrote to the file.");

        } catch (IOException e) {

            System.out.println("An error occurred while writing to the file.");

            e.printStackTrace();

        }

    }


    public static void updateFile(String fileName, String content) {

        try (FileWriter writer = new FileWriter(fileName, true)) {

            writer.write(content);

            System.out.println("Successfully updated the file.");

        } catch (IOException e) {

            System.out.println("An error occurred while updating the file.");

            e.printStackTrace();

        }

    }


    public static void readFromFile(String fileName) {

        try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {

            String line;

            System.out.println("Reading from file:");

            while ((line = reader.readLine()) != null) {

                System.out.println(line);

            }

        } catch (IOException e) {

            System.out.println("An error occurred while reading from the file.");

            e.printStackTrace();

        }

    }


    public static void deleteFile(String fileName) {

        File file = new File(fileName);

        if (file.delete()) {

import java.io.*;

import java.util.Scanner;


class FS {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        String fileName = "msc1.txt";

        int choice;


        do {

            System.out.println("\nFile Operations Menu:");

            System.out.println("1. Create a File");

            System.out.println("2. Write to the File");

            System.out.println("3. Read from the File");

            System.out.println("4. Update the File");

            System.out.println("5. Delete the File");

            System.out.print("Enter your choice: ");

            choice = scanner.nextInt();

            scanner.nextLine(); // consume the newline


            switch (choice) {

                case 1:

                    createFile(fileName);

                    break;

                case 2:

                    System.out.print("Enter content to write: ");

                    String content = scanner.nextLine();

                    writeToFile(fileName, content);

                    break;

                case 3:

                    readFromFile(fileName);

                    break;

                case 4:

                    System.out.print("Enter content to append: ");

                    String updateContent = scanner.nextLine();

                    updateFile(fileName, updateContent);

                    break;

                case 5:

                    deleteFile(fileName);

                    break;

                default:

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

            }

        } while (true); // Continuous loop until the program is manually terminated


        // scanner.close(); // No need to close scanner since program will run indefinitely

    }


    public static void createFile(String fileName) {

        File file = new File(fileName);

        try {

            if (file.createNewFile()) {

                System.out.println("File created successfully: " + file.getName());

            } else {

                System.out.println("File already exists.");

            }

        } catch (IOException e) {

            System.out.println("An error occurred while creating the file.");

            e.printStackTrace();

        }

    }


    public static void writeToFile(String fileName, String content) {

        try (FileWriter writer = new FileWriter(fileName)) {

            writer.write(content);

            System.out.println("Successfully wrote to the file.");

        } catch (IOException e) {

            System.out.println("An error occurred while writing to the file.");

            e.printStackTrace();

        }

    }


    public static void updateFile(String fileName, String content) {

        try (FileWriter writer = new FileWriter(fileName, true)) {

            writer.write(content);

            System.out.println("Successfully updated the file.");

        } catch (IOException e) {

            System.out.println("An error occurred while updating the file.");

            e.printStackTrace();

        }

    }


    public static void readFromFile(String fileName) {

        try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {

            String line;

            System.out.println("Reading from file:");

            while ((line = reader.readLine()) != null) {

                System.out.println(line);

            }

        } catch (IOException e) {

            System.out.println("An error occurred while reading from the file.");

            e.printStackTrace();

        }

    }


    public static void deleteFile(String fileName) {

        File file = new File(fileName);

        if (file.delete()) {

            System.out.println("Deleted the file: " + file.getName());

        } else {

            System.out.println("Failed to delete the file.");

        }

    }

}


OUTPUT :-


 





Monday, July 8, 2024

Java command line Quiz program

 import java.lang.*;

import java.io.*;


class Questions {

    public String[][] qpa; 

    public String[][] qca; 


    Questions() {

        qpa = new String[10][5];


        // questions and objectives

        qpa[0][0] = "Which keyword is used to define a class in Java?";

        qpa[0][1] = "1. define";

        qpa[0][2] = "2. class";

        qpa[0][3] = "3. Class";

        qpa[0][4] = "4. def";


        qpa[1][0] = "Which method is the entry point of a Java program?";

        qpa[1][1] = "1. start()";

        qpa[1][2] = "2. main()";

        qpa[1][3] = "3. init()";

        qpa[1][4] = "4. run()";


        qpa[2][0] = "Which package contains the Random class?";

        qpa[2][1] = "1. java.util";

        qpa[2][2] = "2. java.io";

        qpa[2][3] = "3. java.net";

        qpa[2][4] = "4. java.lang";


        qpa[3][0] = "Which keyword is used to create an object in Java?";

        qpa[3][1] = "1. new";

        qpa[3][2] = "2. create";

        qpa[3][3] = "3. object";

        qpa[3][4] = "4. instantiate";


        qpa[4][0] = "What is the size of int in Java?";

        qpa[4][1] = "1. 8 bits";

        qpa[4][2] = "2. 16 bits";

        qpa[4][3] = "3. 32 bits";

        qpa[4][4] = "4. 64 bits";


        qca = new String[10][2];


        // questions and correct answers

        qca[0][0] = "Which keyword is used to define a class in Java?";

        qca[0][1] = "2. class";


        qca[1][0] = "Which method is the entry point of a Java program?";

        qca[1][1] = "2. main()";


        qca[2][0] = "Which package contains the Random class?";

        qca[2][1] = "1. java.util";


        qca[3][0] = "Which keyword is used to create an object in Java?";

        qca[3][1] = "1. new";


        qca[4][0] = "What is the size of int in Java?";

        qca[4][1] = "3. 32 bits";

    }

}


public class qu {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        int x, correct = 0, wrong = 0, i, j; 

        String[] ans = new String[10];

        Questions q = new Questions();


        System.out.println("JAVA QUIZ");

        System.out.println();


        // for loop to display questions and read the answers from the user

        for (i = 0; i < 5; i++) {

            for (j = 0; j < 5; j++) {

                System.out.println(q.qpa[i][j]);

            }

            System.out.println("Your answer:");


            x = scanner.nextInt();

            ans[i] = q.qpa[i][x];

        }


        // calculate correct answers

        for (i = 0; i < 5; i++) {

            if (q.qca[i][1].equals(ans[i])) {

                correct++;

            } else {

                wrong++;

            }

        }


        // printing the correct answers and user-selected answers

        System.out.println("CORRECT ANSWERS");

        for (i = 0; i < 5; i++) {

            System.out.println();

            System.out.println(q.qpa[i][0]);

            System.out.println("Correct answer: " + q.qca[i][1]);

            System.out.println("Your answer: " + ans[i]);

        }

        

        System.out.println("Correct = " + correct + "\tWrong = " + wrong);

        

        scanner.close();

    }

}


OUTPUT:-




























Monday, June 24, 2024

Java program

 // Define the Product class

class Product {

    private String name;

    private double price;

    private int quantity;

    private double taxRate; // Tax rate as a decimal (e.g., 0.08 for 8%)


    // Constructor to initialize the product

    public Product(String name, double price, int quantity, double taxRate) {

        this.name = name;

        this.price = price;

        this.quantity = quantity;

        this.taxRate = taxRate;

    }


    // Method to calculate the total cost including tax

    public double calculateTotalCost() {

        double subtotal = price * quantity;

        double taxAmount = subtotal * taxRate;

        double totalCost = subtotal + taxAmount;

        return totalCost;

    }


    // Getters and setters (optional based on requirements)

    public String getName() {

        return name;

    }


    public void setName(String name) {

        this.name = name;

    }


    public double getPrice() {

        return price;

    }


    public void setPrice(double price) {

        this.price = price;

    }


    public int getQuantity() {

        return quantity;

    }


    public void setQuantity(int quantity) {

        this.quantity = quantity;

    }


    public double getTaxRate() {

        return taxRate;

    }


    public void setTaxRate(double taxRate) {

        this.taxRate = taxRate;

    }

}


// Main class to demonstrate the product calculation

public class ProductCalculation {

    public static void main(String[] args) {

        // Create a product instance

        Product product = new Product("Smartphone", 999.99, 2, 0.08); // Example values: price, quantity, tax rate


        // Calculate the total cost including tax

        double totalCost = product.calculateTotalCost();


        // Display the result

        System.out.println("Product: " + product.getName());

        System.out.println("Price per unit: $" + product.getPrice());

        System.out.println("Quantity: " + product.getQuantity());

        System.out.println("Tax rate: " + (product.getTaxRate() * 100) + "%");

        System.out.println("Total cost (including tax): $" + totalCost);

    }

}


public class BookPriceCalculator {

    public static void main(String[] args) {
        String productName = "Book";
        int quantity = 5;
        double taxRate = 0.1; // Assuming tax rate is 10%

        double originalPrice = 20.0; // Assuming original price of each book is $20

        // Calculate tax amount
        double taxAmount = originalPrice * taxRate;

        // Calculate total price including tax
        double totalPrice = (originalPrice + taxAmount) * quantity;

        // Print out the details
        System.out.println("Product name: " + productName);
        System.out.println("Quantity: " + quantity);
        System.out.println("Original Price per book: $" + originalPrice);
        System.out.println("Tax Rate: " + (taxRate * 100) + "%");
        System.out.println("Tax Amount per book: $" + taxAmount);
        System.out.println("Total Price including tax: $" + totalPrice);
    }
}




File operation

       ->This Java program offers a user-friendly, menu-driven interface for performing fundamental file operations.        -> It allo...