[go: up one dir, main page]

0% found this document useful (0 votes)
73 views43 pages

Aditya Termwork

This document contains code snippets and output related to generating a Wi-Fi password based on user input of name, city, age, and gender. The password generation logic follows different rules depending on the gender and age: if female and under 18, it combines parts of the name and city with the age sum; if female and over 18, it combines parts of the name and city differently with the age difference; otherwise, it alternates characters from the name and city and appends the age. The code takes input, applies the logic, and prints the generated password.

Uploaded by

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

Aditya Termwork

This document contains code snippets and output related to generating a Wi-Fi password based on user input of name, city, age, and gender. The password generation logic follows different rules depending on the gender and age: if female and under 18, it combines parts of the name and city with the age sum; if female and over 18, it combines parts of the name and city differently with the age difference; otherwise, it alternates characters from the name and city and appends the age. The code takes input, applies the logic, and prints the generated password.

Uploaded by

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

NAME: ADITYA SURI UNIVERSITY ROLL NO: 2102586 COURSE: BCA

1. WAP in Java to print the sum of following


series: x1/y2 + x3/y4 + x5/y6 + …. Up to n terms.

CODE:

import

java.util.Scanner; public

class SeriesSum{

public static void main(String[] args){

Scanner scanner = new

Scanner(System.in);

System.out.print("Enter the value of x: ");

double x = scanner.nextDouble();

System.out.print("Enter the value of y: ");

double y = scanner.nextDouble();

System.out.print("Enter the value of n: ");

int n = scanner.nextInt();

double sum = calculateSeriesSum(x, y, n);

System.out.println("Sum of the series is: " + sum);

public static double calculateSeriesSum(double x, double y, int n)

{ double sum = 0;

for (int i = 0; i < n; i++){

int exponentX = 2 * i + 1;

int exponentY = 2 * (i +

1);

double term = Math.pow(x, exponentX) / Math.pow(y,

exponentY) sum += term;


NAME: ADITYA SURI UNIVERSITY ROLL NO: 2102586 COURSE: BCA

return sum;

}
NAME: ADITYA SURI UNIVERSITY ROLL NO: 2102586 COURSE: BCA

OUTPUT:
NAME: ADITYA SURI UNIVERSITY ROLL NO: 2102586 COURSE: BCA

2. WAP in Java to initialize 2D integer array of type uneven in order to print average
of each row. Array should be initialized by the user.

CODE:

import java.util.Scanner;

public class AverageOfEachRow {

public static void main(String[] args)

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of rows:

"); int numRows = scanner.nextInt();

int[][] unevenArray = new int[numRows]

[]; for (int i = 0; i < numRows; i++) {

System.out.print("Enter the number of columns for row " + (i + 1) + ":

"); int numCols = scanner.nextInt();

unevenArray[i] = new int[numCols];

System.out.println("Enter " + numCols + " elements for row " + (i + 1) + ":

"); for (int j = 0; j < numCols; j++) {

unevenArray[i][j] = scanner.nextInt();

System.out.println("Input array:");

printArray(unevenArray)

System.out.println("Average of each

row:");

calculateAndPrintAverage(unevenArray);

public static void printArray(int[][] arr)

{ for (int i = 0; i < arr.length; i++) {


NAME: ADITYA SURI UNIVERSITY ROLL NO: 2102586 COURSE: BCA

for (int j = 0; j < arr[i].length; j++)

{ System.out.print(arr[i][j] + " ");

System.out.println();

public static void calculateAndPrintAverage(int[][] arr)

{ for (int i = 0; i < arr.length; i++) {

int sum = 0;

for (int j = 0; j < arr[i].length; j++)

{ sum += arr[i][j];

double average = (double) sum / arr[i].length;

System.out.println("Row " + (i + 1) + ": " + average);

}
NAME: ADITYA SURI UNIVERSITY ROLL NO: 2102586 COURSE: BCA

OUTPUT:
NAME: ADITYA SURI UNIVERSITY ROLL NO: 2102586 COURSE: BCA

3. WAP to calculate Area of Circle and Rectangle by Overloading constructor, radius


and side should be initialized through constructor.

CODE:

import

java.text.DecimalFormat; class

Circle {

private double radius;

public Circle(double radius)

{ this.radius = radius;

public double calculateArea() {

return Math.PI * Math.pow(radius, 2);

class Rectangle {

private double

length; private

double width;

public Rectangle(double length, double width)

{ this.length = length;

this.width = width;

public double calculateArea()

{ return length * width;

public class AreaCalculator {


NAME: ADITYA SURI UNIVERSITY ROLL NO: 2102586 COURSE: BCA

public static void main(String[] args) {


NAME: ADITYA SURI UNIVERSITY ROLL NO: 2102586 COURSE: BCA

Circle circle = new Circle(5);

double circleArea = circle.calculateArea();

System.out.println("Area of the circle: " +

formatArea(circleArea)); Rectangle rectangle = new Rectangle(10,

7);

double rectangleArea = rectangle.calculateArea();

System.out.println("Area of the rectangle: " +

formatArea(rectangleArea));

private static String formatArea(double area) {

DecimalFormat df = new

DecimalFormat("#.###"); return df.format(area);

}
NAME: ADITYA SURI UNIVERSITY ROLL NO: 2102586 COURSE: BCA

OUTPUT:
NAME: ADITYA SURI UNIVERSITY ROLL NO: 2102586 COURSE: BCA

4. WAP to use of super keyword to access variable, method and constructor calling.

CODE:

class Superclass

{ int number;

Superclass(int number)

{ this.number =

number;

void display() {

System.out.println("Number from Superclass: " + number);

class Subclass extends Superclass {

int number; // Shadowing the 'number' variable from the

superclass Subclass(int number1, int number2) {

super(number1); // Call superclass

constructor this.number = number2;

void display() {

super.display(); // Call superclass method

System.out.println("Number from Subclass: " +

number);

void accessSuperclassVariable() {

System.out.println("Superclass 'number' variable: " + super.number);

}
NAME: ADITYA SURI UNIVERSITY ROLL NO: 2102586 COURSE: BCA

}
NAME: ADITYA SURI UNIVERSITY ROLL NO: 2102586 COURSE: BCA

public class SuperKeywordExample {

public static void main(String[] args)

Subclass subclassObj = new Subclass(10,

20); subclassObj.display();

subclassObj.accessSuperclassVariable();

}
NAME: ADITYA SURI UNIVERSITY ROLL NO: 2102586 COURSE: BCA

OUTPUT:
NAME: ADITYA SURI UNIVERSITY ROLL NO: 2102586 COURSE: BCA

5. WAP to implement the upcasting and down-casting between parent and child class.

CODE:

class Parent {
void parentMethod() {
System.out.println("This is a method of Parent class.");
}
}

class Child extends Parent


{ void childMethod() {
System.out.println("This is a method of Child class.");
}
}

public class Demo {


public static void main(String[] args)
{ Parent parent = new Parent();
parent.parentMethod();

Parent parent1 = new


Child();
parent1.parentMethod();

Child child = (Child)


parent1; child.childMethod();
}
}
NAME: ADITYA SURI UNIVERSITY ROLL NO: 2102586 COURSE: BCA

OUTPUT:
NAME: ADITYA SURI UNIVERSITY ROLL NO: 2102586 COURSE: BCA

6. WAP to exception handling for checked and unchecked exception.

CODE:

import
java.io.FileNotFoundException;
import java.io.IOException;

public class Main {


public static void main(String[] args)
{ try {
divideNumbers(10, 0);
// System.out.println(sum);
} catch (ArithmeticException e) {
System.out.println("ArithmeticException: " +
e.getMessage());
}

try {
openFile("nonExistentFile.txt");
} catch (FileNotFoundException e) {
System.out.println("FileNotFoundException: " +
e.getMessage());
} catch (IOException e) {
System.out.println("IOException: " + e.getMessage());
}
}

private static void divideNumbers(int a, int b) throws ArithmeticException


{ if (b == 0) {
throw new ArithmeticException("Division by zero is not allowed");
}
int sum = a / b;
System.out.println("Result: " + sum);
}

private static void openFile(String fileName) throws FileNotFoundException, IOException


{ throw new FileNotFoundException("File not found");
}
}
NAME: ADITYA SURI UNIVERSITY ROLL NO: 2102586 COURSE: BCA

OUTPUT:
NAME: ADITYA SURI UNIVERSITY ROLL NO: 2102586 COURSE: BCA

7. WAP in java to simulate condition to generate Wi-Fi password. Take input as


Name, City, Age and Gender.
Constraints:
a. Length of name and city should be greater or equal to 3.
b. Age can`t be 18.
Output Constraints:
a. If Gender=F and Age<18
Password: 1st 3 char of name + sum of digit of age + last 3 char of
city
b. Else If gender=F and Age>18
Password: last 3 char of Name + Diff of digit of age(Positive) + 1st 3 char of City.
c. Else
Password: 1st char of name + 1st char of city + 2nd char of name + 2nd char of city

Append this to length of max string (name or city) and then concatenate with Age to
get password.

CODE:

import
java.util.Scanner; public
class WAP {
public static void main(String[] args) {

Scanner scanner = new

Scanner(System.in);

System.out.println("Enter
Name:"); String name =
scanner.nextLine();

System.out.println("Enter
City:"); String city =
scanner.nextLine();

System.out.println("Enter
Age:"); int age =
scanner.nextInt();

System.out.println("Enter Gender
(M/F):"); char gender =
scanner.next().charAt(0);
NAME: ADITYA SURI UNIVERSITY ROLL NO: 2102586 COURSE: BCA

System.out.println("Wi-Fi Password: " + generateWiFiPassword(name, city, age, gender));

}
public static String generateWiFiPassword(String name, String city, int age, char gender)
{ String password = "";
NAME: ADITYA SURI UNIVERSITY ROLL NO: 2102586 COURSE: BCA

password += name.substring(0,
3).toUpperCase(); password += city.substring(0,
3).toUpperCase(); password +=
String.valueOf(age).substring(0, 2); password +=
gender;

return password;
}
}
NAME: ADITYA SURI UNIVERSITY ROLL NO: 2102586 COURSE: BCA

OUTPUT:
NAME: ADITYA SURI UNIVERSITY ROLL NO: 2102586 COURSE: BCA

8. WAP in Java to take input (more than one) using command line and compare it with
input taken using Scanner. If there is any match, print “Character Found” else throw
a NoMatchException (also message).

CODE:

import

java.util.Scanner; public

class WAP {

public static void main(String[] args)

{ String userInput = "";

if (args.length > 0) {
for (String arg : args)
{ userInput += arg + "
";
}
} else {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter multiple inputs (separated by space):
"); userInput = scanner.nextLine();
}

String inputFromCommandLine = "A B C D

E"; try {
compareInputs(userInput, inputFromCommandLine);
} catch (NoMatchException e) {
System.out.println(e.getMessage())
;
}
}

public static void compareInputs(String userInput, String inputFromCommandLine)


throws NoMatchException {

String[] userInputArray = userInput.split(" ");


String[] commandLineInputArray = inputFromCommandLine.split("

"); boolean matchFound = false;

for (String commandLineInput : commandLineInputArray)


{ for (String userInputValue : userInputArray) {
if (commandLineInput.equalsIgnoreCase(userInputValue))
{ matchFound = true;
NAME: ADITYA SURI UNIVERSITY ROLL NO: 2102586 COURSE: BCA

System.out.println("Character Found: " +


userInputValue); break;
}
}
if (matchFound) break;
}

if (!matchFound) {
throw new NoMatchException("No matching characters found in command line input.");
}
}
}

class NoMatchException extends Exception


{ public NoMatchException(String message)
{ super(message);
}
}
NAME: ADITYA SURI UNIVERSITY ROLL NO: 2102586 COURSE: BCA

OUTPUT:
NAME: ADITYA SURI UNIVERSITY ROLL NO: 2102586 COURSE: BCA

9. WAP in Java to initialize two string and find common characters and different
Characters of these string.

CODE:

import

java.util.Scanner; public

class WAP {
public static void main(String[] args) {
Scanner scanner = new
Scanner(System.in);
System.out.println("Enter first string: ");
String str1 = scanner.nextLine();
System.out.println("Enter second string: ");
String str2 = scanner.nextLine();

compareStrings(str1, str2);
}

public static void compareStrings(String str1, String str2)


{ StringBuilder commonCharacters = new StringBuilder();
StringBuilder differentCharacters = new StringBuilder();

for (int i = 0; i < str1.length(); i++) {


for (int j = 0; j < str2.length(); j++) {
if (str1.charAt(i) == str2.charAt(j))
{
commonCharacters.append(str1.charAt(i))
; break;
}
}
}

for (int i = 0; i < str1.length(); i++)


{ boolean found = false;
for (int j = 0; j < str2.length(); j++) {
if (str1.charAt(i) == str2.charAt(j))
{ found = true;
break;
}
}
if (!found) {
differentCharacters.append(str1.charAt(i))
;
}
}
NAME: ADITYA SURI UNIVERSITY ROLL NO: 2102586 COURSE: BCA

System.out.println("Common Characters: " +


commonCharacters.toString()); System.out.println("Different Characters: " +
differentCharacters.toString());
}
NAME: ADITYA SURI UNIVERSITY ROLL NO: 2102586 COURSE: BCA

OUTPUT:
NAME: ADITYA SURI UNIVERSITY ROLL NO: 2102586 COURSE: BCA

10. WAP in Java to initialize a string in order to find that character which frequency is
2nd most in that string.

CODE:

import java.util.*;

public class WAP {


public static void main(String[] args) {
Scanner scanner = new
Scanner(System.in);
System.out.println("Enter a string: ");
String str = scanner.nextLine();
find2ndMostFrequentChar(str);
}

public static void find2ndMostFrequentChar(String str)


{ if (str == null || str.length() < 2) {
System.out.println("Invalid input. String should be at least 2 characters
long."); return;
}

Map<Character, Integer> charCountMap = new

HashMap<>(); for (char c : str.toCharArray()) {


charCountMap.put(c, charCountMap.getOrDefault(c, 0) + 1);
}

List<Character> maxCountCharList = new


ArrayList<>(); int maxCount = 0;

for (Map.Entry<Character, Integer> entry : charCountMap.entrySet())


{ if (entry.getValue() > maxCount) {
maxCount = entry.getValue();
maxCountCharList.clear();
maxCountCharList.add(entry.getKey())
;
} else if (entry.getValue() == maxCount)
{ maxCountCharList.add(entry.getKey())
;
}
}

if (maxCountCharList.size() < 2) {
System.out.println("2nd most frequent character not
found."); return;
}
NAME: ADITYA SURI UNIVERSITY ROLL NO: 2102586 COURSE: BCA

char secondMostFrequentChar = maxCountCharList.get(1);


System.out.println("2nd most frequent character: " + secondMostFrequentChar);
}
}
NAME: ADITYA SURI UNIVERSITY ROLL NO: 2102586 COURSE: BCA

OUTPUT:
NAME: ADITYA SURI UNIVERSITY ROLL NO: 2102586 COURSE: BCA

11. WAP to find the average of second minimum and second highest number from the
array?

CODE:

import

java.util.Arrays;

public class Main {


public static void main(String[] args)
{ int[] array = {4, 2, 5, 2, 3, 4};
System.out.println("The average of the second minimum and second highest number is: "
+ averageOfSecondMinMax(array));
}

public static double averageOfSecondMinMax(int[] array)


{ if (array == null || array.length < 2) {
throw new IllegalArgumentException("Array should have at least 2 elements");
}

int min1 = Integer.MAX_VALUE, min2 =


Integer.MAX_VALUE; int max1 = Integer.MIN_VALUE, max2
= Integer.MIN_VALUE;

for (int num : array)


{ if (num < min1) {
min2 = min1;
min1 = num;
} else if (num < min2)
{ min2 = num;
}

if (num > max1)


{ max2 =
max1; max1 =
num;
} else if (num > max2)
{ max2 = num;
}
}

if (min1 == Integer.MAX_VALUE || min2 == Integer.MAX_VALUE || max1 ==


Integer.MIN_VALUE || max2 == Integer.MIN_VALUE) {
throw new IllegalArgumentException("Array should have at least 2 different numbers");
}

return (min2 + max2) / 2.0;


}
}
NAME: ADITYA SURI UNIVERSITY ROLL NO: 2102586 COURSE: BCA

OUTPUT:
NAME: ADITYA SURI UNIVERSITY ROLL NO: 2102586 COURSE: BCA

12. WAP to check longest sub sequence of a same character in an initialized


string? Sample I/P: [aaaabppppp]O/P: p=5
Sample I/P: [aabbcc] O/P:

a=2 CODE:

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

public class Main {

public static void main(String[] args) {


System.out.println(checkLongestSubSequence("aaaabppppp"))
; System.out.println(checkLongestSubSequence("aabbcc"));
}

public static Map<Character, Integer> checkLongestSubSequence(String s)


{ Map<Character, Integer> map = new HashMap<>();
int maxLength = 0;
char maxChar = '\0';

for (int i = 0; i < s.length(); i++)


{ char c = s.charAt(i);

if (map.containsKey(c)) {
map.put(c, map.get(c) + 1);
} else {
map.put(c, 1);
}

if (map.get(c) > maxLength)


{ maxLength = map.get(c);
maxChar = c;
}
}

map.clear();
map.put(maxChar, maxLength);

return map;
}
}
NAME: ADITYA SURI UNIVERSITY ROLL NO: 2102586 COURSE: BCA

OUTPUT;
NAME: ADITYA SURI UNIVERSITY ROLL NO: 2102586 COURSE: BCA

13. WAP to create heterogeneous ArrayList and to retrieve using iterator().

CODE:

import java.util.*;

public class Main {


public static void main(String[] args) {
ArrayList<Object> arrayList = new
ArrayList<>(); arrayList.add("Java");
arrayList.add(123)
;
arrayList.add(3.14)
; arrayList.add('C');

Iterator<Object> iterator = arrayList.iterator();

while (iterator.hasNext()) {
System.out.println(iterator.next())
;
}
}
}
NAME: ADITYA SURI UNIVERSITY ROLL NO: 2102586 COURSE: BCA

OUTPUT:
NAME: ADITYA SURI UNIVERSITY ROLL NO: 2102586 COURSE: BCA

14. WAP to enter string through command line argument that may contain numeric or
alphanumeric. You have to sum out all numeric digit as well as create a string from
remaining characters in order to find your name can be created from that string or
not.

CODE:

public class Main {

public static void main(String[] args)

{ if (args.length != 1) {
System.out.println("Please enter a string through command line argument.");
return;
}

String inputString =
args[0]; String
remainingChars = ""; int
sumOfDigits = 0;

for (int i = 0; i < inputString.length(); i++)


{ char currentChar =
inputString.charAt(i);

if (Character.isDigit(currentChar)) {
sumOfDigits += Character.getNumericValue(currentChar);
} else {
remainingChars += currentChar;
}
}

System.out.println("Sum of digits: " + sumOfDigits);


System.out.println("Remaining characters: " + remainingChars);

}
}
NAME: ADITYA SURI UNIVERSITY ROLL NO: 2102586 COURSE: BCA

OUTPUT:
NAME: ADITYA SURI UNIVERSITY ROLL NO: 2102586 COURSE: BCA

15. WAP to find number of ‘a’ in a string s=” alialiali” without using charAt() method.

CODE:

public class Main {

public static void main(String[] args)

{ String s = "alialiali";
int count = 0;

char[] chars =

s.toCharArray(); for (char c :

chars) {
if (c == 'a')
{ count+
+;
}
}

System.out.println("Number of 'a' in the string: " + count);


}
}
NAME: ADITYA SURI UNIVERSITY ROLL NO: 2102586 COURSE: BCA

OUTPUT:
NAME: ADITYA SURI UNIVERSITY ROLL NO: 2102586 COURSE: BCA

16. WAP in Java to print the sum of following


series: xn = x1 + x2 + x3 + x4 + …… +
xn.

CODE:

import

java.util.Scanner; public

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

System.out.println("Enter the number of terms (n):


"); int n = scanner.nextInt();

System.out.println("Enter the value of x (x):


"); int x = scanner.nextInt();

int sum = (x * (x + 1)) / 2;

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


}
}
NAME: ADITYA SURI UNIVERSITY ROLL NO: 2102586 COURSE: BCA

OUTPUT:

You might also like