Question:1
⁠PAN is a ten -digit unique alphanumeric number issued by the Income Tax Department of India. The structure of the first five characters of PAN, the first three characters represent the alphabetic series running from AAA to ZZZ and the fourth character of PAN represents the status of the PAN holder it will contain only “A”, ”B”, ”C”, ”E”, ”G”, ”H”, ”I”, ”K”, ”N” & “Q”. Fifth character of PAN represents the first character of the PAN holder's Father’s first name/surname in case of an individual. In case of non individual PAN holder’s fifth character represents the last character of PAN holder's name. Get the input from the user, if all the cases are valid for PAN number’s first five values then print “This might be valid PAN number” otherwise throw appropriate user defined exceptions(alphabetic series, forth and fifth character input.)

Solution:


import java.util.Scanner;
import java.util.regex.*;

class InvalidPANException extends Exception {
    public InvalidPANException(String str) {
        // calling the constructor of the parent Exception
        super(str);
    }
}
// class that uses custom exception InvalidAgeException
public class PAN_Exception {
    public static int whitespace(String str) {
        int i = 0;
        for (i = 0; i < str.length(); i++) {
            if (str.charAt(i) == ' ') {
                return i;
            }
        }
        return i;
    }
    // method to check the PAN
    static void validate_PAN(String PAN, String a, String b, String c, String d) throws InvalidPANException {
        String fifth_word = PAN.substring(4, 5);
        if (PAN.length() != 10) {
            // throw an object of user-defined exception
            throw new InvalidPANException("Entered PAN number should have exactly ten-digit unique alphanumeric characters.");
        } else if (!Pattern.matches("[A-Z]{3}", PAN.substring(0, 3))) {
            throw new InvalidPANException("The first three characters should represent the alphabetic series running from AAA to ZZZ");
        } else if (!Pattern.matches("[ABCEGHIKNQ]{1}", PAN.charAt(3) + "")) {
            throw new InvalidPANException("The fourth character should represent the status of the PAN Holder and it should be one of the characters A, B, C, E, G, H, I, K, N, Q.");
        } else if (!(fifth_word.equals(a.toUpperCase()) || fifth_word.equals(b.toUpperCase()) || fifth_word.equals(c.toUpperCase()) || fifth_word.equals(d.toUpperCase()))) {
            throw new InvalidPANException("The fifth character should represent either father's first name/last name's first character (Individual) or person's first name/last name's last character (Non-Individual).");
        } else {
            System.out.println("This might be a valid PAN number.");
        }
    }
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.println("\n");
        System.out.println("Enter the person's PAN Number to Validate: ");
        String PAN = sc.nextLine();
        System.out.println("Enter the person Name: ");
        String person = sc.nextLine();
        System.out.println("Enter the Father Name: ");
        String father = sc.nextLine();
        try {
            // calling the method
            String father_firstname_firstchar = "" + father.charAt(0);
            String father_lastname_firstchar = "" + father.charAt(whitespace(father) + 1);
            String person_firstname_lastchar = "" + person.charAt(whitespace(person) - 1);
            String person_lastname_lastchar = "" + person.charAt(person.length() - 1);
            validate_PAN(PAN, father_firstname_firstchar, father_lastname_firstchar, person_firstname_lastchar, person_lastname_lastchar);
        } catch (InvalidPANException e) {
            System.out.println("\nCaught the exception.");
            // printing the message from InvalidAgeException object
            System.out.println("Exception occurred: " + e);
            System.out.println("");
        } finally {
            sc.close();
        }
    }
}
      

Question:2
Develop a Node.js application for a customizable event-driven calculator. The calculator should support the following advanced arithmetic operations: exponentiation (^), modulus (%), and square root (√).

Solution:


Server.js

const express = require("express"); const app = express(); // Function to perform arithmetic operations function calculate(num1, operator, num2) { switch (operator) { case "+": return num1 + num2; case "-": return num1 - num2; case "*": return num1 * num2; case "/": return num1 / num2; case "^": return Math.pow(num1, num2); case "%": return num1 % num2; case "√": return Math.sqrt(num1); default: return NaN; } } // Serve HTML file app.get("/", (req, res) => { res.sendFile(__dirname + "/index.html"); }); // Route for calculator app.get("/calculate", (req, res) => { const num1 = parseFloat(req.query.num1); const operator = req.query.operator; const num2 = parseFloat(req.query.num2); if (isNaN(num1) || isNaN(num2)) { return res.send("Invalid input. Please enter valid numbers."); } let result = calculate(num1, operator, num2); if (isNaN(result)) { return res.send("Invalid operator. Please choose a valid operator."); } res.send(`Result: ${result}`); }); // Start the server const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });

Question:3
Write Java program that checks if two arrays contain the same elements or not.

Solution:


import java.util.Arrays;
public class ArrayEqualityCheck {
    public static void main(String[] args) {
        int[] array1 = {1, 2, 3, 4, 5};
        int[] array2 = {1, 2, 3, 4, 5};

        boolean result = arraysEqual(array1, array2);
        
        if (result) {
            System.out.println("Arrays are equal.");
        } else {
            System.out.println("Arrays are not equal.");
        }
    }

    // Function to check if two arrays contain the same elements
    public static boolean arraysEqual(int[] array1, int[] array2) {
        // If arrays have different lengths, they can't be equal
        if (array1.length != array2.length) {
            return false;
        }

        // Sort both arrays
        Arrays.sort(array1);
        Arrays.sort(array2);

        // Check if sorted arrays are equal
        return Arrays.equals(array1, array2);
    }
} 

Question:4
Develop Node JS Application to perform basic arithmetic application (+,-,*,/) using events. Make sure that your Node JS application must demonstrate how to create an event, emit and remove the events

Solution:


const EventEmitter = require("events");
const readline = require("readline");
class ArithmeticOperation extends EventEmitter {
  add(num1, num2) {
    const result = num1 + num2;
    this.emit("add", result);
  }
  subtract(num1, num2) {
    const result = num1 - num2;
    this.emit("subtract", result);
  }
  multiply(num1, num2) {
    const result = num1 * num2;
    this.emit("multiply", result);
  }
  divide(num1, num2) {
    if (num2 === 0) {
      this.emit("error", "Division by zero is not allowed!");
    } else {
      const result = num1 / num2;
      this.emit("divide", result);
    }
  }
}
const arithmetic = new ArithmeticOperation();
arithmetic.on("add", (result) => {
  console.log("Addition Result:", result);
});
arithmetic.on("subtract", (result) => {
  console.log("Subtraction Result:", result);
});
arithmetic.on("multiply", (result) => {
  console.log("Multiplication Result:", result);
});
arithmetic.on("divide", (result) => {
  console.log("Division Result:", result);
});
arithmetic.on("error", (error) => {
  console.error("Error:", error);
});
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});
function performOperation(operation, num1, num2) {
  switch (operation) {
    case "+":
      arithmetic.add(num1, num2);
      break;
    case "-":
      arithmetic.subtract(num1, num2);
      break;
    case "*":
      arithmetic.multiply(num1, num2);
      break;
    case "/":
      arithmetic.divide(num1, num2);
      break;
    default:
      console.log("Invalid operation!");
  }
}
rl.question("Enter operation (+, -, *, /): ", (operation) => {
  rl.question("Enter first number: ", (num1) => {
    rl.question("Enter second number: ", (num2) => {
      performOperation(operation, parseFloat(num1), parseFloat(num2));
      rl.close();
    });
  });
});
rl.on("close", () => {
  console.log("Exiting the application.");
});
  

Question:5
You are developing a registration system for an online event. Each participant must provide their age, email address, and a password. The password must be at least 8 characters long and contain at least one uppercase letter, one lowercase letter, and one special character (!@#$%^&*). If any of these criteria are not met, throw a user-defined exception with an appropriate message like "Invalid password format."

Solution:


import java.util.Scanner;

class InvalidPasswordException extends Exception {
    public InvalidPasswordException(String message) {
        super(message);
    }
}

public class RegistrationSystem {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        System.out.print("Enter your name: ");
        String name = scanner.nextLine();
        
        System.out.print("Enter your age: ");
        int age = scanner.nextInt();
        scanner.nextLine(); // Consume newline left-over
        
        System.out.print("Enter your email address: ");
        String email = scanner.nextLine();
        
        System.out.print("Enter your password: ");
        String password = scanner.nextLine();
        
        try {
            register(name, age, email, password);
        } catch (InvalidPasswordException e) {
            System.out.println("Registration failed: " + e.getMessage());
        } finally {
            scanner.close();
        }
    }

    public static void register(String name, int age, String email, String password) throws InvalidPasswordException {
        if (!isValidPassword(password)) {
            throw new InvalidPasswordException("Invalid password format.");
        }
        
        // Register the user
        System.out.println("Registration successful!");
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("Email: " + email);
    }

    public static boolean isValidPassword(String password) {
        // Password must be at least 8 characters long
        if (password.length() < 8) {
            return false;
        }
        
        // Password must contain at least one uppercase letter, one lowercase letter, and one special character
        boolean hasUpperCase = false;
        boolean hasLowerCase = false;
        boolean hasSpecialCharacter = false;
        
        for (char ch : password.toCharArray()) {
            if (Character.isUpperCase(ch)) {
                hasUpperCase = true;
            } else if (Character.isLowerCase(ch)) {
                hasLowerCase = true;
            } else if ("!@#$%^&*".indexOf(ch) != -1) {
                hasSpecialCharacter = true;
            }
        }
        
        return hasUpperCase && hasLowerCase && hasSpecialCharacter;
    }
}
    

Question:6
You are developing a banking application that processes withdrawals. Each withdrawal transaction requires the user to provide their account number, withdrawal amount, and a PIN for authentication. If the provided PIN does not match the PIN associated with the account, or if the withdrawal amount exceeds the available balance, throw a user-defined exception with an appropriate message.

Solution:


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

class IncorrectPINException extends Exception {
    public IncorrectPINException(String message) {
        super(message);
    }
}

class InsufficientBalanceException extends Exception {
    public InsufficientBalanceException(String message) {
        super(message);
    }
}

class Account {
    private String accountNumber;
    private int pin;
    private double balance;

    public Account(String accountNumber, int pin, double balance) {
        this.accountNumber = accountNumber;
        this.pin = pin;
        this.balance = balance;
    }

    public String getAccountNumber() {
        return accountNumber;
    }

    public boolean validatePIN(int enteredPIN) {
        return this.pin == enteredPIN;
    }

    public double getBalance() {
        return balance;
    }

    public void withdraw(double amount) throws InsufficientBalanceException {
        if (amount > balance) {
            throw new InsufficientBalanceException("Insufficient balance.");
        }
        balance -= amount;
        System.out.println("Withdrawal successful! Remaining balance: " + balance);
    }
}

public class BankingApplication {
    private static Map accounts = new HashMap<>();

    public static void main(String[] args) {
        // Create some sample accounts
        accounts.put("1234567890", new Account("1234567890", 1234, 1000.0));
        accounts.put("0987654321", new Account("0987654321", 4321, 2000.0));
        
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter account number: ");
        String accountNumber = scanner.nextLine();
        System.out.print("Enter PIN: ");
        int pin = scanner.nextInt();
        System.out.print("Enter withdrawal amount: ");
        double amount = scanner.nextDouble();
        
        try {
            processWithdrawal(accountNumber, pin, amount);
        } catch (IncorrectPINException | InsufficientBalanceException e) {
            System.out.println("Withdrawal failed: " + e.getMessage());
        } finally {
            scanner.close();
        }
    }

    public static void processWithdrawal(String accountNumber, int pin, double amount) throws IncorrectPINException, InsufficientBalanceException {
        Account account = accounts.get(accountNumber);
        if (account == null || !account.validatePIN(pin)) {
            throw new IncorrectPINException("Incorrect PIN.");
        }
        account.withdraw(amount);
    }
}
  

Question:7
You are tasked with creating a Node.js script that generates a random number within a specified range and outputs it to the console.
Write a Node.js script that does the following:
1. Accepts two command-line arguments representing the minimum and maximum values of the range.
2. Generates a random integer between the provided minimum and maximum values (inclusive).
3. Outputs the generated random number to the console.
Ensure that your script handles cases where invalid input is provided (e.g., non-numeric arguments, minimum value greater than maximum value) and provides appropriate error messages.

Solution:


const readline = require('readline');

// Function to generate a random integer between min and max (inclusive)
function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

// Create readline interface for input/output
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

// Function to handle user input and generate random number
function generateRandomNumber() {
  // Ask the user for the minimum value
  rl.question('Enter the minimum value: ', (minInput) => {
    // Parse the input as an integer
    const min = parseInt(minInput);

    // Ask the user for the maximum value
    rl.question('Enter the maximum value: ', (maxInput) => {
      // Parse the input as an integer
      const max = parseInt(maxInput);

      // Check if inputs are valid numbers
      if (isNaN(min) || isNaN(max)) {
        console.error('Error: Both minimum and maximum values must be numeric');
        rl.close();
        return;
      }

      // Check if min is greater than max
      if (min > max) {
        console.error('Error: Minimum value cannot be greater than maximum value');
        rl.close();
        return;
      }

      // Generate and output the random number
      const randomNumber = getRandomInt(min, max);
      console.log('Random number between', min, 'and', max + ':', randomNumber);

      // Close the readline interface
      rl.close();
    });
  });
}

// Call the main function
generateRandomNumber();

Question:8
A social media platform requires users to create a username using the first letter of their first name, followed by their entire last name, and ending with the last two digits of their phone number. If the criteria are not met (for example, if the last name is missing or the phone number is not provided), throw a user-defined exception with an appropriate message like "Invalid username creation criteria not met." Example: First name: John Last name: Doe Phone number: 9859807527 The username should be: JDoe27

Solution:


const readline = require('readline');

class InvalidUsernameError extends Error {
  constructor(message) {
    super(message);
    this.name = 'InvalidUsernameError';
  }
}

function createUsername(firstName, lastName, phoneNumber) {
  // Check if last name and phone number are provided
  if (!lastName || !phoneNumber) {
    throw new InvalidUsernameError('Invalid username creation criteria not met. Last name or phone number missing.');
  }

  // Extract the first letter of the first name
  const firstInitial = firstName.charAt(0).toUpperCase();

  // Extract the last name
  const lastNamePart = lastName.toLowerCase();

  // Extract the last two digits of the phone number
  const phoneNumberPart = phoneNumber.slice(-2);

  // Construct the username
  const username = `${firstInitial}${lastNamePart}${phoneNumberPart}`;

  return username;
}

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.question('Enter your first name: ', (firstName) => {
  rl.question('Enter your last name: ', (lastName) => {
    rl.question('Enter your phone number: ', (phoneNumber) => {
      try {
        const username = createUsername(firstName, lastName, phoneNumber);
        console.log('The username should be:', username);
      } catch (error) {
        if (error instanceof InvalidUsernameError) {
          console.error(error.message);
        } else {
          console.error('An unexpected error occurred:', error.message);
        }
      } finally {
        rl.close();
      }
    });
  });
});

Question:9
Write a Node.js function that takes a string as input and returns the reversed version of the string.

Solution 1


const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

function reverseString(inputString) {
  // Convert the string to an array of characters, reverse the array, then join the characters back into a string
  return inputString.split('').reverse().join('');
}

rl.question('Enter a string: ', (input) => {
  const reversed = reverseString(input);
  console.log('Reversed string:', reversed);
  rl.close();
});

Solution 2


const readline = require('readline');

function reverseString(input) {
    let reversed = '';
    for (let i = input.length - 1; i >= 0; i--) {
        reversed += input[i];
    }
    return reversed;
}

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

rl.question('Enter a string: ', (input) => {
    const reversedString = reverseString(input);
    console.log('Reversed string:', reversedString);
    rl.close();
});