0% found this document useful (0 votes)
69 views129 pages

Milestone 1

The document contains multiple Java programming tasks, including creating classes, methods for string manipulation, array operations, and validation of passwords. Each task specifies input and output formats, constraints, and sample test cases. The tasks cover various programming concepts such as string handling, array manipulation, and object-oriented programming principles.

Uploaded by

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

Milestone 1

The document contains multiple Java programming tasks, including creating classes, methods for string manipulation, array operations, and validation of passwords. Each task specifies input and output formats, constraints, and sample test cases. The tasks cover various programming concepts such as string handling, array manipulation, and object-oriented programming principles.

Uploaded by

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

\Create a class named Main and create two variables named, venueName and city of

type string.

Write a main method to get the venue details in the string separated by a comma.
Use String.split() function to display the details.

Input format :
The first line consists of a String that represents the venueName and city.

Output format :
The output should display the venue details.

Refer sample output for formatting specifications.

// You are using Java


import java.util.*;
class Main{
public static void main(String[] args){
Scanner sc= new Scanner(System.in);
String st= sc.nextLine();
String sarr[]= st.split(",");
System.out.println("Venue Details:");
System.out.println("Venue Name: "+sarr[0]);
System.out.println("City Name: "+sarr[1]);

___________________________________________________________________________________
________

Single File Programming Question


Number of unique character

Problem statement

You are required to implement the following function:

int countUniqueCharacters(char[] str);

The function accepts a string ‘str’ as its argument. You are required to calculate
the number of unique characters in string ‘str’ and return the same.

Note

If ‘str’ = NULL, return -1

Example

Input
abcdabc

Output

Explanation

The string ‘str’ is “abcdabc” and unique characters in string ‘str’ are { ‘a’ , ‘b’
, ‘c’ , ‘d’ }, Count of them is 4, hence 4 is returned.

Input format :
Input is a string

Output format :
Integer represents number of unique characters.

Code constraints :
Length of ‘str’ <= 100000 characters

‘str’ contains only lower case alphabets

Sample test cases :


Input 1 :
efeefhjg
Output 1 :
5
Input 2 :
abcabcd
Output 2 :
4
Note :
The program will be evaluated only after the “Submit Code” is clicked.
Extra spaces and new line characters in the program output will result in the
failure of the test case.

// You are using Java


import java.util.*;
class Main{
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
String st = sc.nextLine();
HashSet<Character> set = new HashSet<>();
for (int i =0;i<st.length();i++){
set.add(st.charAt(i));
}
System.out.println(set.size());

}
}
___________________________________________________________________________________
____________________

Valid Password or Not


The HR committee of Sunrise Basket Company decided to enforce the following rules
when an employee creates/changes his/her password.

Password should be less than 15 and more than 8 characters in length.


Password should contain at least one upper case and one lower case alphabet.
Password should contain at least one number.
Password should contain at least one special character.
Password should not contain a space.

The program must accept a given password string "password" as input.

Input format :
The input consists of String that represents password.

Output format :
The output should print "<password> is a valid password" or "<password> is a
invalid password".

Refer sample output for formatting specifications.

Sample test cases :


Input 1 :
Ex@1234ab
Output 1 :
Ex@1234ab is a valid password
Input 2 :
Ex!!
Output 2 :
Ex!! is a invalid password
Input 3 :
Abcd @1234
Output 3 :
Abcd @1234 is a invalid password
Note :
The program will be evaluated only after the “Submit Code” is clicked.
Extra spaces and new line characters in the program output will result in the
failure of the test case.

// You are using Java


import java.util.*;
class Main{

public static void main(String[]args){


Scanner sc = new Scanner(System.in);
String password = sc.nextLine();
boolean uppercase, lowercase, digits,space , specialChar;
int size= password.length();
boolean valid = true;
char ch;
if(size<8 || size>15){
valid= false;
}
else{
uppercase=lowercase=specialChar=digits=space =false;
for(int i=0;i<password.length();i++){
ch = password.charAt(i);

if(Character.isUpperCase(ch)) uppercase=true;
else if(Character.isLowerCase(ch)) lowercase= true;
else if(Character.isDigit(ch)) digits= true;
else if(Character.isSpace(ch)) space= true;
else
specialChar= true;
}
if(uppercase && lowercase&& !space&& digits&&specialChar){
valid= true;
}
else{
valid = false;
}

}
if(valid)
System.out.println(password+" is a valid password");
else
System.out.println(password+" is a invalid password");
}
}

___________________________________________________________________________________
_____________
Single File Programming Question
Write a Java program to reverse a given array. Define a method reverseArray that
takes an integer array as an argument and returns a new array with the elements in
reverse order.

Code constraints :
The input array can be of any length

Sample test cases :


Input 1 :
5
80
70
60
50
40
Output 1 :
40 50 60 70 80

code // You are using Java


import java.util.*;
class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n= sc.nextInt();
int[]arr= new int[n];
for(int i=0;i<n;i++){
arr[i]=sc.nextInt();
}
for(int i=0,j=n-1;i<j;i++,j--){
int temp = arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
for(int i=0;i<n;i++){
System.out.println(arr[i]);
}
}
}
-_________________________________________________________
Write a Java program to find the maximum value in a given array. Define a method
findMax that takes an integer array as an argument and returns the maximum value.

Code constraints :
The input array should have at least one element.

Sample test cases :


Input 1 :
5
10
20
30
40
50
Output 1 :
The maximum value in the array is: 50
code
// You are using Java
import java.util.*;
class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int arr[]= new int [n];
for(int i =0;i<arr.length;i++){
arr[i]= sc.nextInt();

}
int max= arr[0];
for(int j =1;j<arr.length;j++){
if(arr[j]>max){
max= arr[j];
}

}
System.out.print("The Maximum value in the array is:"+max);

}
}
________________________________________________________________
Write a Java program to concatenate two given arrays. Define a method
concatenateArrays that takes two integer arrays as arguments and returns a new
array containing all elements of the first array followed by all elements of the
second array.

Input format :
The first line of input contains the size of the first array.
The second line contains the elements of the first array.

The third line contains the size of the second array.

The fourth line contains the elements of the second array.

Output format :
Output consist of the concatenation of the array

Code constraints :
The input arrays can be of any length, including empty.

Sample test cases :


Input 1 :
3
1 2 3
3
4 5 6
Output 1 :
1 2 3 4 5 6

// You are using Java


import java.util.*;
class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int arr1[]= new int[n];
for(int i=0;i<n;i++){
arr1[i]=sc.nextInt();
}
int m = sc.nextInt();
int arr2[]= new int[m];
for(int i=0;i<m;i++){
arr2[i]=sc.nextInt();
}
int z=n+m;
int arr3[]=new int[z];
for(int i=0;i<n;i++){
arr3[i]=arr1[i];

}
for(int i=0;i<m;i++){
arr3[n]=arr2[i];
n++;
}

for(int i=0;i<n;i++){
System.out.println(arr3[i]);
}
}

}
_________________________________________
Ravi is working on a system that processes text messages sent by users. He wants to
write a program that analyzes a message, removes extra spaces, and reverses each
word in the sentence. Additionally, the program should count how many words are
present in the message.

You need to help Ravi by writing a program that processes the message using basic
string methods.

Input format :
The input is a single string (message) that contains words separated by spaces.

The input can have leading, trailing, and multiple spaces between words.

Output format :
The program should print the message after removing extra spaces.
The program should print the message with each word reversed.
The program should print the number of words in the message.

Code constraints :
The length of the message string is ≤ 200 characters.

Words consist of only alphabetic characters and numbers


code
// You are using Java
import java.util.*;
class Main{

public static void main(String[]args){


Scanner sc = new Scanner(System.in);
String st= sc.nextLine();
String[] str=st.split(" ");
String result1="",result2= "";
int count=0;
StringBuffer sb;
for(int i=0;i<str.length;i++){
if(str[i].trim().length()>0){
result1= result1+ str[i]+" ";
sb= new StringBuffer(str[i]);
result2= result2+sb.reverse().toString();

count++;
}
}
result1= result1.trim();
result2= result2.trim();
System.out.println("Message after removing extra spaces: "+"\""+result1+"\"");
System.out.println("Message with each word reversed: "+"\""+result2+"\"");
System.out.println("Word count: "+count);
}

}
________________________________________________________________________________

You are working on a small utility for a word processing program. The utility
should process a list of words and identify:
Words that start with a specific letter.
Words that have more than a specified number of characters.
Words that contain a specific substring.
Write a program that takes a list of words and performs the following tasks:

Check if each word starts with the specified letter.


Check if the word length is greater than a given number.
Check if the word contains a specific substring.
Input format :
Input Format:
The first line contains an integer n, the number of words.
The next n lines contain one word each.
The next line contains a character representing the letter to check for.
The next line contains an integer representing the minimum word length to check
for.
The last line contains a substring to search for in the words
Output format :
Output Format:
For each word, print whether it:

Starts with the given letter.


Has a length greater than the specified number.
Contains the given substring.

Code constraints :
The number of words (n) ≤ 20.

Each word's length ≤ 30.

The letter and substring to search for are non-empty.

Sample test cases :


Input 1 :
3
hello
world
java
h
4
java
Output 1 :
Word: hello
Starts with 'h': true
Length greater than 4: true
Contains 'java': false

Word: world
Starts with 'h': false
Length greater than 4: true
Contains 'java': false

Word: java
Starts with 'h': false
Length greater than 4: false
Contains 'java': true
code:
// You are using Java
import java.util.*;
class Main{
public static void main(String []args){
Scanner sc= new Scanner(System.in);
int n= sc.nextInt();
sc.nextLine();
String[]words = new String[n];

for(int i=0;i<n;i++){
words[i]=sc.nextLine();

String startStr = sc.nextLine();

int minLen= sc.nextInt();


sc.nextLine();
String searchStr= sc.nextLine();

for(String data: words){


System.out.println("Word: "+data);
System.out.println("Starts with \'"+startStr+"\' :
"+data.startsWith(startStr));
System.out.println("Length greater than "+minLen+": "+
(data.length()>minLen));
System.out.println("contains'"+searchStr+"':"+
(data.indexOf(searchStr)>-1)+"\n");

}
}
________________________________________________________________________________

// You are using Java


import java.util.*;
class Main{
public static String check(String sen){

if(Character.isLowerCase(sen.charAt(0))) return "invalid";


int vowel=0;
for(int i=0;i<sen.length();i++){
char ch= sen.charAt(i);
if(Character.isDigit(ch)) return "invalid";
if(ch=='a' ||ch=='e' ||ch=='i' ||ch=='o'||ch=='u'){
vowel++;
}
}

if(vowel==0){
return "invalid";}
char ch= sen.charAt(sen.length()-1);
if(ch!='.'&& ch!='?'&& ch!= '!') return "invalid";
return "valid";

public static void main(String[]args){


Scanner sc= new Scanner(System.in);
int n= sc.nextInt();

sc.nextLine();
String[] str = new String[n];
for(int i=0;i<n;i++){
str[i]=sc.nextLine();
}
for(int i=0;i<n;i++){
if(Character.isDigit(str[i].charAt(0))) continue;
System.out.println("Sentence: "+ str[i]+" - "+check(str[i]));

}
}
}
____________
// You are using Java
import java.util.*;
class Main{

public static void main(String[]args){


Scanner sc = new Scanner(System.in);
String st= sc.nextLine();
String[] str=st.split(" ");
String result1="",result2= "";
int count=0;
StringBuffer sb;
for(int i=0;i<str.length;i++){
if(str[i].trim().length()>0){
result1= result1+ str[i]+" ";
sb= new StringBuffer(str[i]);
result2= result2+sb.reverse().toString();

count++;
}
}
result1= result1.trim();
result2= result2.trim();
System.out.println("Message after removing extra spaces: "+"\""+result1+"\"");
System.out.println("Message with each word reversed: "+"\""+result2+"\"");
System.out.println("Word count: "+count);
}

}
______
// You are using Java
import java.util.*;
class Main{
public static void main(String []args){
Scanner sc= new Scanner(System.in);
int n= sc.nextInt();
sc.nextLine();
String[]words = new String[n];
for(int i=0;i<n;i++){
words[i]=sc.nextLine();

String startStr = sc.nextLine();

int minLen= sc.nextInt();


sc.nextLine();
String searchStr= sc.nextLine();

for(String data: words){


System.out.println("Word: "+data);
System.out.println("Starts with \'"+startStr+"\' :
"+data.startsWith(startStr));
System.out.println("Length greater than "+minLen+": "+
(data.length()>minLen));
System.out.println("contains'"+searchStr+"':"+
(data.indexOf(searchStr)>-1)+"\n");

}
}
___________________________________________________________________________________
________________________
DAY 4

Session 1

VENUE HALL DETAILS

Create a class named Venue with the following attributes.

name - String
city - String
address - String
pincode - int
Create another class called Main and write a main method to test the above class.

Retrieve input from the user for the name, city, address and pincode. Then, display
the details according to the specified output format.

Input format :
The first line consists of a name in String.

The next line consists of a city in String.

Output format :
The output should display the venue details.

Refer to the sample output for reference.

Sample test cases :


Input 1 :
demo venue name
demo city
demo address
12344
Output 1 :
Venue Details
Venue Name: demo venue name
City Name : demo city
City Address : demo address
City Pincode : 12344
Input 2 :
demo venue name 2
demo city 2
demo address 2
11111
Output 2 :
Venue Details
Venue Name: demo venue name 2
City Name : demo city 2
City Address : demo address 2
City Pincode : 11111

CODE::
// You are using Java
import java.util.*;
class Venue{
private String name;
private String city;
private String address;
private int pincode;

public void setName(String name){


this.name=name;
}
public String getName(){
return name;
}
public void setCity(String city){
this.city=city;
}

public String getCity(){


return city;
}
public void setAddress(String address){
this.address=address;
}
public String getAddress(){
return address;
}

public void SetPincode(int pincode){


this.pincode=pincode;
}

public int getPincode(){


return pincode;
}
}

class Main{

public static void main(String[]args){


Scanner sc= new Scanner(System.in);
Venue venue = new Venue();
venue.setName(sc.nextLine());
venue.setCity(sc.nextLine());
venue.setAddress(sc.nextLine());
venue.SetPincode(sc.nextInt());

System.out.println("Venue Details");
System.out.println("Venue Name: "+ venue.getName());
System.out.println("City Name : "+ venue.getCity());
System.out.println("City address : "+ venue.getAddress());
System.out.println("City Pincode : "+ venue.getPincode());

}
}
___________________________________________________________________________________
______________

Create a class named Delivery with the following private attributes

over - long
ball - long
runs - long
batsman - String
bowler - String
nonStriker - String
Implement getters, setters, parameterized constructors and default constructors for
the above attributes.

Create another class named Main and include a main method to test the above class.

Input format :
The first line consists of a long that represents over.

The second line consists of a long that represents the ball.

The third line consists of a long that represents the runs.

The fourth line consists of a String that represents a batsman.

The next line consists of a String that represents a bowler.

The next line consists of a String that represents a nonStriker.

Output format :
The output should display delivery details.

Refer to the sample output for reference.


Sample test cases :
Input 1 :
1
1
4
Dhoni
Dale Steyn
Suresh Raina
Output 1 :
Over: 1
Ball: 1
Runs: 4
Batsman: Dhoni
Bowler: Dale Steyn
Non Striker: Suresh Rai

CODE:
// You are using Java
import java.util.*;

class Delivery{
private long over;
private long ball;
private long runs;
private String batsman;
private String bowler;
private String nonStriker;

Delivery(long over , long ball,long runs, String batsman, String bowler, String
nonStriker){
this.over= over;
this.ball= ball;
this.runs= runs;
this.batsman= batsman;
this.bowler= bowler;
this.nonStriker= nonStriker;
}

public long getOver(){


return over;
}
public long getBall(){
return ball;
}
public long getRuns(){
return runs;
}
public String getBatsman(){
return batsman;
}
public String getBowler(){
return bowler;
}
public String getNonStriker(){
return nonStriker;
}
}

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

long o= (sc.nextLong());
long b= (sc.nextLong());
long r=(sc.nextLong());
sc.nextLine();
String bt=(sc.nextLine());
String bw=(sc.nextLine());
String ns=(sc.nextLine());

Delivery dd = new Delivery(o,b,r,bt,bw,ns);


System.out.println("Over: "+dd.getOver());
System.out.println("Ball: "+dd.getBall());
System.out.println("Runs: "+dd.getRuns());
System.out.println("Batsman: "+dd.getBatsman());
System.out.println("Bowler: "+dd.getBowler());
System.out.println("Non Striker: "+dd.getNonStriker());
}

___________________________________________________

Determining Neon Numbers

Your task is to write a program to determine whether a given number is a neon


number or not. A neon number is a number where the sum of the digits of the square
of the number is equal to the number itself.

For example: 9

9^2=81 =>8+1=9

Create a class named 'Main' with an attribute named 'num' of type int.

Constructor: Create a constructor with a parameter to initialize the attribute


'num'. Pass the value to the constructor from the main method and perform the task
of checking for a neon number within the constructor.

Input format :
The first line of input consists of an integer representing the number.
Output format :
If the number is a neon number, the output should be in the format: <number> is a
Neon Number
If the number is not a neon number, the output should be in the format: <number> is
not a Neon Number
If the input number is greater than 20, the output should be: Invalid
Code constraints :
N < 20

Sample test cases :


Input 1 :
2
Output 1 :
2 is not a Neon Number
Input 2 :
1
Output 2 :
1 is a Neon Number
Input 3 :
21
Output 3 :
Invalid

CODE:::
import java.util.*;
class Main{
private int num;
Main(int num){
this.num=num;
if(num>20)
System.out.println("Invalid");
else{
if(isNeon())
System.out.println(num+" is a Neon Number");
else
System.out.println(num+" is not a Neon Number");
}
}
public boolean isNeon(){
int daraSingh=num*num;
int sum=0;
while(daraSingh>0){
sum+=daraSingh%10;
daraSingh=daraSingh/10;
}
return sum==num;
}
public static void main(String a[]){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
Main ob=new Main(n);
}
}
_______________________________________________________

Session 2:

Bob has been tasked with creating a program to calculate and display the
circumference and area of the circle.

The program should allow Bob to input the radius of a circle as both an integer and
a double and compute both the circumference and area of the circle using separate
overloaded methods:

calculateCircumference- To calculate the circumference using the formula 2 * 3.14 *


radius
calculateArea- To calculate the area 3.14 * radius * radius

Write a program to help Bob.

Input format :
The first line of input consists of an integer m, representing the radius of the
circle as a whole number.

The second line consists of a double value n, representing the radius of the circle
as a decimal number.

Output format :
The first line of output displays two space-separated double values, rounded to two
decimal places, representing the circumference of the circle with the integer
radius and the double radius, respectively.

The second line displays two space-separated double values, rounded to two decimal
places, representing the area of the circle with the integer radius and the double
radius, respectively.

Refer to the sample output for formatting specifications.

Code constraints :
In this scenario, the test cases fall under the following constraints:

1 ≤ m ≤ 100

1.00 ≤ n ≤ 100.00

Sample test cases :


Input 1 :
5
3.5
Output 1 :
31.40 21.98
78.50 38.47
Input 2 :
1
1.00
Output 2 :
6.28 6.28
3.14 3.14
Input 3 :
100
100.00
Output 3 :
628.00 628.00
31400.00 31400.00

CODE::
// You are using Java
import java.util.*;
class Circle{

public double calculateArea(int radius){


return 3.14* radius*radius;
}
public double calculateArea(double radius){
return 3.14* radius*radius;
}
public double calculateCircumference(int radius){
return 3.14*radius*2;
}
public double calculateCircumference(double radius){
return 3.14* radius*2;
}
}

class Main{

public static void main(String args[]){


Scanner sc = new Scanner(System.in);
Circle obj = new Circle();

int intradius = sc.nextInt();


double doubleradius = sc.nextDouble();

System.out.printf("%.2f %.2f",obj.calculateCircumference(intradius),
obj.calculateCircumference(doubleradius));
System.out.printf("%.2f %.2f",obj.calculateArea(intradius),
obj.calculateArea(doubleradius));

}
}

____________________________________________________________________

You are tasked with designing a Travel class featuring overloaded calculateTime
methods, enabling users to calculate travel time based on either the distance and
speed they plan to travel or the number of stops they intend to make and the
average duration of each stop.

Calculate the time taken for both approaches and display the results.

For distance and speed input, time = distance/speed.

For number of stops and average duration, time = stops * (avg duration / 60.0)

Input format :
The first line of input consists of a double value representing the distance.

The second line consists of a double value representing the speed.

The third line consists of an integer representing the number of stops.

The fourth line consists of a double value representing the average stop duration.

Output format :
The first line of output displays a double value, representing the travel time by
distance and speed, rounded to one decimal place.

The second line displays a double value, representing the travel time by number of
stops and average stop duration, rounded to one decimal place.

Refer to the sample output for formatting specifications.

Code constraints :
In this scenario, the test cases fall under the following constraints:

1.0 ≤ distance ≤ 1000.0

0.0 ≤ speed ≤ 1000.0

1 ≤ number of stops ≤ 100

1.0 ≤ average stop duration ≤ 3600.0

Sample test cases :


Input 1 :
50.0
10.0
1
30.0
Output 1 :
5.0
0.5
Input 2 :
100.0
100.0
100
100.0
Output 2 :
1.0
166.7

code::
// You are using Java
import java.util.*;
class Travel{
public double calculateTime(double distance, double speed){
return (distance/speed);
}
public double calculateTime(int stops, double avgStop){
return stops*(avgStop/60.0);
}
}
class Main{
public static void main(String[]args)

{
Scanner sc = new Scanner(System.in);
double distance = sc.nextDouble();
double speed = sc.nextDouble();
int stops = sc.nextInt();
double avgStop = sc.nextDouble();

Travel obj = new Travel();


System.out.printf("%.1f\n",obj.calculateTime(distance,speed));
System.out.printf("%.1f",obj.calculateTime(stops,avgStop));

}
___________________________________________________________________________________
________

Problem Statement

Hagrid needs a program capable of performing two calculations: square roots and
cube roots.

When he inputs an integer value, the program calculates the square root and
displays the result.
Likewise, if he enters a double, he anticipates the program to compute the cube
root and display the outcome.

Create a program that enables Hagrid to input a number and then see the result of
the respective root calculation. Use method overloading with the name
calculateRoot() for this and also sqrt() and cbrt() functions from the Java
library.

Input format :
The input consists of either an integer n or a double value d, representing the
numerical value entered by Hagrid.

Output format :
If the input is an integer, the output displays the square root of n rounded to one
decimal place.

If the input is a double value, the output displays the cube root of d rounded to
one decimal place.

Refer to the sample output for the formatting specifications.

Sample test cases :


Input 1 :
4
Output 1 :
2.0
Input 2 :
27.0
Output 2 :
3.0
Input 3 :
1000
Output 3 :
31.6
Input 4 :
1000.00
Output 4 :
10.0
Note :
The program will be evaluated only after the “Submit Code” is clicked.
Extra spaces and new line characters in the program output will result in the
failure of the test case.

CODE:
// You are using Java
import java.util.*;
class calculate{
public double calculateRoot(int value){
return Math.sqrt(value);
}
public double calculateRoot(double value){
return Math.cbrt(value);
}
}
class Main{
public static void main(String[]args){

Scanner sc = new Scanner(System.in);


calculate obj = new calculate();
String num = sc.nextLine();
if(!num.contains(".")){
System.out.printf("%.1f",obj.calculateRoot(Integer.parseInt(num)));
}
else{
System.out.printf("%.1f",obj.calculateRoot(Double.parseDouble(num)));

}
}
________________________________________________________________________________

1st // You are using Java

import java.util.*;
class Person{
private String firstName;
private String lastName;

Person(){
firstName="";
lastName="";
}
Person(String firstName, String lastName){
this.firstName=firstName;
this.lastName= lastName;
}
public void setFirstName(String firstName){
this.firstName= firstName;
}
public void setLastName(String lastName){
this.lastName= lastName;
}
public String getFirstName(){
return firstName;
}
public String getLastName(){
return lastName;
}
}

class Employee extends Person{


private int employeeId;
private String jobTitle;

Employee(){
employeeId=0;
jobTitle="";
}
Employee(String firstName, String lastName,int employeeId,String jobTitle)
{ super(firstName,lastName);
this.employeeId=employeeId;
this.jobTitle=jobTitle;
}
public void setEmployeeId(int employeeId){
this.employeeId=employeeId;
}
public void setJobTitle(String jobTitle){
this.jobTitle=jobTitle;
}

public int getEmployeeId(){


return employeeId;
}
public String getJobTitle(){
return jobTitle;
}

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

String firstName= sc.nextLine();


String lastName= sc.nextLine();
int employeeId= sc.nextInt();
sc.nextLine();
String jobtitle=sc.nextLine();
Employee emp = new Employee(firstName,lastName,employeeId,jobtitle);
System.out.println("Employee details:");
System.out.println("Name: "+emp.getFirstName()+" "+emp.getLastName()+",
"+emp.getJobTitle());
System.out.println("Employee ID: "+emp.getEmployeeId());
}
}

_______________________________________

// You are using Java


import java.util.*;
class Transaction{
private int transactionId;
private double amount;

Transaction(int transactionId,double amount){


this.transactionId=transactionId;
this.amount=amount;
}
public String getTransactionInfo(){
return "Transaction ID: "+transactionId+"\nAmount: $"+amount;
}

class PeerToPeerTransaction extends Transaction{


private String recipient;
PeerToPeerTransaction(int transactionId,double amount, String recipient){
super(transactionId,amount);
this.recipient=recipient;
}

public String getTransactionInfo(){


return super.getTransactionInfo()+"\nRecipient: "+recipient;
}

}
class OnlinePurchaseTransaction extends Transaction{
private String merchant;
OnlinePurchaseTransaction(int transactionId,double amount, String merchant){
super(transactionId,amount);
this.merchant=merchant;
}

public String getTransactionInfo(){


return super.getTransactionInfo()+"\nMerchant: "+merchant;
}
}

class BillPaymentTransaction extends Transaction{


private String billType;
BillPaymentTransaction(int transactionId,double amount, String billType){
super(transactionId,amount);
this.billType=billType;
}

public String getTransactionInfo(){


return super.getTransactionInfo()+"\nBill Type: "+billType;
}
}

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

int tid = sc.nextInt();


double amount = sc.nextDouble();
sc.nextLine();
String recipient= sc.nextLine();
String mer = sc.nextLine();
String btype = sc.nextLine();
Transaction ob = new PeerToPeerTransaction(tid,amount,recipient);
System.out.println("Peer-To-Peer Transaction:");
System.out.println(ob.getTransactionInfo());
System.out.println();
ob = new OnlinePurchaseTransaction(tid,amount,mer);
System.out.println("Online Purchase Transaction:");
System.out.println(ob.getTransactionInfo());
System.out.println();
System.out.println("Bill Payment Transaction:");
ob= new BillPaymentTransaction(tid,amount,btype);
System.out.println(ob.getTransactionInfo());

}
}

____________________________________________________________________________

// You are using Java


import java.util.*;
class Employee{
protected int empId;
protected float salary;
Employee(int empId, float salary){
this.empId=empId;
this.salary=salary;
}

}
class EmployeeLevel extends Employee{
EmployeeLevel(int empId,float salary){
super(empId,salary);
}
public int getEmpId(){
return empId;
}
public float getSalary(){
return salary;
}
}

class Main{
public static void main(String[] args){
Scanner sc= new Scanner(System.in);
int empId=sc.nextInt();
float salary= sc.nextFloat();
Employee ob = new Employee(empId,salary);
System.out.println(empId);
System.out.println(salary);
if(salary>100){
System.out.println("1");
}
if(salary<=100){
System.out.println("2");
}
}
}

_______________________________________________________________________________

DAY 5 METHOD OVERIDING

Teena's retail store has implemented a Loyalty Points System to reward customers
based on their spending. The program includes two classes: Customer and
PremiumCustomer.

For regular customers: Loyalty points = amount spent / 10

For premium customers: Loyalty points = 2 * (amount spent / 10)

Calculate and display the loyal points received by the customers using an
overridden method calculateLoyaltyPoints.

Input format :
The first line of input consists of an integer representing the amount spent by the
customer.

The second line consists of premium customer status (a string) - "yes" if the
customer is a premium customer, "no" if they are not.

Output format :
The output displays the loyalty points earned based on the amount spent.

Refer to the sample output for formatting specifications.

Code constraints :
1 ≤ amount ≤ 10,000

Sample test cases :


Input 1 :
50
yes
Output 1 :
10
Input 2 :
40
no
Output 2 :
4
code:
// You are using Java
import java.util.*;
class Customer{
public int calculateLoyaltyPoints(int amount){
return (amount/10);

}
}
class PremiumCustomer extends Customer{
public int calculateLoyaltyPoints(int amount){
return 2*(amount/10);

class Main{
public static void main(String []args){
Scanner sc = new Scanner(System.in);
int amount = sc.nextInt();
sc.nextLine();
String st = sc.nextLine();
Customer c;
if(st.equals("no")){
c=new Customer();
}
else {
c= new PremiumCustomer();
}
System.out.println(c.calculateLoyaltyPoints(amount));

}
}

___________________________________________________________________________________
code 2 :

Problem Statement

Rithish is developing a straightforward pizza ordering system. To achieve this, he


needs a Pizza class with a constructor for the base price and topping cost, along
with a calculatePrice method overriding. He also wants a DiscountedPizza class that
inherits from Pizza, applying a 10% discount for more than three toppings.

The program prompts the user for inputs, creates instances of both classes,
calculates regular and discounted prices, and displays them formatted
appropriately.
Example 1

Input:

9.5

1.25

Output:

Price without discount: Rs.13.25

Price with discount: Rs.13.25

Explanation:

Rithish orders a pizza with a base price of Rs. 9.5, a topping cost of Rs. 1.25,
and selects 3 toppings. The price is calculated as 9.5 + (1.25 * 3) = 13.25. The
regular and discounted prices are both Rs. 13.25, as no discount has been applied.

Example 2

Input:

11.0

2.0

Output:

Price without discount: Rs.25.00

Price with discount: Rs.22.50

Explanation:

Rithish orders another pizza with a higher base price of Rs. 11.0, a topping cost
of Rs. 2.0, and chooses 7 toppings.

Regular Price: 11.0 + (2.0 * 7) = Rs. 25.00.

Discounted Price: The discounted price is calculated as 90% of the regular price,
i.e., 0.9 * 25.00 = Rs.22.50.

Input format :
The first line of input consists of a double value, representing the base price of
the pizza.
The second line consists of a double value, representing the cost per topping.

The third line consists of an integer, representing the number of toppings chosen
for the pizza.

Output format :
The first line of output prints the price without discount, rounded off to two
decimal places.

The second line prints the price with the discount, rounded off to two decimal
places.

Hint: Use printf with %.2f

Refer to the sample output for formatting specifications.

Code constraints :
The base price and the cost per topping should be greater than zero.

1 ≤ number of toppings ≤ 10

Sample test cases :


Input 1 :
9.5
1.25
3
Output 1 :
Price without discount: Rs.13.25
Price with discount: Rs.13.25
Input 2 :
11.0
2.0
7
Output 2 :
Price without discount: Rs.25.00
Price with discount: Rs.2

// You are using Java


import java.util.*;
class Pizza{
protected double basePrice;
protected double toppingCost;
protected int numberOfTopping;
Pizza(){

}
Pizza(double basePrice, double toppingCost, int numberOfTopping){
this.basePrice= basePrice;
this.toppingCost= toppingCost;
this.numberOfTopping=numberOfTopping;

}
public double calculatePrice(){
return basePrice +(toppingCost*numberOfTopping);
}
}

class DiscountedPizza extends Pizza{

DiscountedPizza(){

DiscountedPizza(double basePrice, double toppingCost, int numberOfTopping){


super(basePrice,toppingCost,numberOfTopping);

public double calculatePrice(){


if(numberOfTopping<=3){
return super.calculatePrice();
}
else{
return (basePrice+(numberOfTopping*toppingCost))*0.9;
}

}
}

class Main{
public static void main(String []args){
Scanner sc = new Scanner(System.in);
double basePrice = sc.nextDouble();
double toppingCost = sc.nextDouble();
int not = sc.nextInt();
Pizza p= new Pizza(basePrice,toppingCost,not);
System.out.printf("price without discount: Rs. %.2f\n",p.calculatePrice());
p= new DiscountedPizza(basePrice,toppingCost,not);
System.out.printf("price with discount: Rs. %.2f\n",p.calculatePrice());

}
}

______________________________________________________________________

code 3:

____________________

code1
Problem Statement

Jessica is tasked with designing a fantasy game character system. The system
includes an abstract class named GameCharacter with two abstract methods: attack()
and defend().

Two subclasses, Warrior and Wizard, extend the GameCharacter class.


The program prompts the player to choose a character class (1. Warrior, 2. Wizard)
and input their character's strength or magic power. The dynamic calculations
involve tripling the strength (strength * 3) for the Warrior's attack and doubling
the magic power(power * 2) for the Wizard's attack.

Jessica needs your help in completing the program. Help her finish it.

Input format :
The first line of input consists of an integer, representing the choice of the
character - 1 for Warrior and 2 for Wizard.

If the choice is 1, the second line consists of an integer N, representing the


strength.

If the choice is 2, the second line consists of an integer M, representing the


magic power.

Output format :
If the choice is 1, the output displays the actions of a warrior in the following
format:

"Warrior Actions:

Attack: Powerful sword slash for [result] damage!

Defend: Raises shield, defence boosted by [N]!"

If the choice is 2, the output displays the actions of a wizard in the following
format:

"Wizard Actions:

Attack: Casts spell, deals [result] magical damage!

Defend: Creates magical barrier, defence boosted by [M]!"

If any other choice is given, print "Invalid choice".

Refer to the sample output for formatting specifications.

Code constraints :
1 ≤ M, N ≤ 106

Sample test cases :


Input 1 :
1
68
Output 1 :
Warrior Actions:
Attack: Powerful sword slash for 204 damage!
Defend: Raises shield, defence boosted by 68!
Input 2 :
2
998
Output 2 :
Wizard Actions:
Attack: Casts spell, deals 1996 magical damage!
Defend: Creates magical barrier, defence boosted by 998!
Input 3 :
3
76
Output 3 :
Invalid choice
Note :
The program will be evaluated only after the “Submit Code” is clicked.
Extra spaces and new line characters in the program output will result in the
failure of the test case.

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
// You are using Java
import java.util.*;
abstract class GameCharacter{
public abstract void attack();
public abstract void defend();

class Warrior extends GameCharacter{


private int strength;
Warrior (int strength){
this.strength= strength;
}
public void attack(){
System.out.println("Attack: Powerful sword slash for "+(strength*3)+"
damage!");

}
public void defend(){
System.out.println("Defend: raises shield , defence boosted by
"+strength+"!");

}
}

class Wizard extends GameCharacter{


private int strength;

Wizard (int strength){


this.strength= strength;
}
public void attack(){
System.out.println("Attack: Casts spell, deals "+(2*strength)+" magical
damage!");
}
public void defend(){
System.out.println("Defend: Creates magical barrier, defence boosted by
"+strength+"!");
}

class Main{
public static void main(String []args){
Scanner sc = new Scanner(System.in);
int choice = sc.nextInt();
int strength= sc.nextInt();
GameCharacter g;
if(choice==1){
g= new Warrior(strength);
System.out.println("Warrior Actions:");
g.attack();
g.defend();

else if(choice==2){
g= new Wizard(strength);
System.out.println("Wizard Actions:");
g.attack();
g.defend();
}
else{

System.out.println("Invalid choice");
}
}
}

--------------------------------------
// You are using Java

Imagine Maria is developing a game, where it involves collecting resources on each


planet, and the availability of resources is modelled using a geometric
progression.

Create an abstract class Series with an abstract method nextTerm(). Implement a


subclass called GeometricSeries that calculates the next term in a geometric
progression for the resource collection on planets. Allow players to input the
initial resource level, resource growth ratio, and the number of planets they plan
to explore.

Display the predicted resource levels on each planet.

Input format :
The first line of input consists of an integer, representing the initial resource
level.

The second line consists of an integer, representing the growth ratio.


The third line consists of an integer, representing the number of planets.

Output format :
The output displays the predicted resource levels of each planet, separated by
space.

Refer to the sample output for formatting specifications.

Code constraints :
In this scenario, the test cases fall under the following constraints:

1 ≤ resource ≤ 10

1 ≤ growth ratio ≤ 10

1 ≤ number of planets ≤ 8

Sample test cases :


Input 1 :
2
3
5
Output 1 :
2 6 18 54 162
Input 2 :
5
2
3
Output 2 :
5 10 20

code________________________________________
import java.util.*;
abstract class Series{
abstract public void nextTerm(int resource, int growth, int num);
}
class GeometricSeries extends Series{
public void nextTerm(int resource,int growth,int num){
for(int i=0;i<num;i++){
System.out.print(resource+" ");
resource=resource*growth;
}
}
}

class Main{
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
GeometricSeries g = new GeometricSeries();
Series s = new GeometricSeries();
s.nextTerm(sc.nextInt(),sc.nextInt(),sc.nextInt());
}
}
_________________________________________________

Wick is developing a real-time strategy game where the players command armies
represented by square matrices. The game requires matrix operations to calculate
army strength and overall battle outcomes.

Write a program to assist Wich that includes an abstract class MatrixOperation with
an abstract method performOperation() and a class MatrixAddition. Calculate the
army strength by adding all the elements in the given matrices. Display the matrix
that represents the army's strength.

Input format :
The first line of input consists of an integer N, representing the number of rows
and columns of a square matrix.

The next N lines consist of N space-separated integers, representing the elements


of the first matrix.

The following N lines consist of N space-separated integers representing the


elements of another matrix.

Output format :
The output prints the army strength, which is the addition of the given matrices.

Refer to the sample output for formatting specifications.

Code constraints :
The given test cases fall under the following constraints:

1 ≤ N ≤ 5

Sample test cases :


Input 1 :
2
1 2
3 4
5 6
7 8
Output 1 :
6 8
10 12
Input 2 :
3
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
16 17 18
Output 2 :
11 13 15
17 19 21
23 25 27

code::::

// You are using Java

abstract public int[][]performOperation(int[][] arr1, int [][]arr2);


}
class MatrixAddition extends MatrixOperation{
public int [][] performOperation(int [][] A, int[][] B){
int [][] C = new int[A.length][A.length];

for(int i=0;i<A.length;i++){
for(int j=0;j<A.length;j++){
C[i][j]= A[i][j]+B[i][j];
}
}
return C;
}
}
class Main{
public static void inputMatrix(int[][]arr, Scanner scan){
for(int i=0;i<arr.length;i++){
for(int j=0;j<arr[0].length;j++ ){
arr[i][j]=scan.nextInt();
}
}
}

public static void displayMatrix(int[][]arr){


for(int i=0;i<arr.length;i++){
for(int j=0;j<arr[0].length;j++ ){
System.out.print(arr[i][j]+" ");
}
System.out.println("");
}

The subclass, WordPalindromeChecker, is derived from the base class. This subclass
overrides the isPalindrome() method to accommodate word inputs, treating them case-
insensitively. The overridden displayResult() method ensures that the outcome of
the word palindrome check is appropriately printed.

Create instances of both classes in the main class and display the results.

Input format :
The first line of input consists of an integer.

The second line consists of a string, it contains lowercase and uppercase letters
with spaces.

Output format :
If the given integer is a palindrome, the first line of output prints "The number
is a palindrome."

Else, print "The number is not a palindrome."

If the given string is a palindrome, the second line of output prints "The word is
a palindrome."

Else, print "The word is not a palindrome."


Refer to the sample output for formatting specifications.

Code constraints :
1 ≤ input integer ≤ 109

length of string < 50

The strings are case-insensitive.

Sample test cases :


Input 1 :
121
madam
Output 1 :
The number is a palindrome.
The word is a palindrome.
Input 2 :
15651
raar world
Output 2 :
The number is a palindrome.
The word is not a palindrome.
Input 3 :
1563
Malayalam
Output 3 :
The number is not a palindrome.
The word is a palindrome.
Input 4 :
45789
java
Output 4 :
The number is not a palindrome.
The word is not a palindrome.
code:

// You are using Java


import java.util.*;
class PalindromeChecker{
private int n;
PalindromeChecker(){

}
PalindromeChecker(int n){
this.n=n;
}
public void setN(int n){
this.n=n;
}
public int getN(){
return n;
}
public boolean isPalindrome(){
int m=n;
int rev=0;
while(m>0){
int r=m%10;
rev= rev*10+r;
m=m/10;
}
if(rev==n){
return true;
}
else{
return false;
}
}
public String displayResult(){
if(isPalindrome()){
return "The number is a palindrome.";
}
else{
return "The number is not a palindrome.";
}
}
}

class WordPalindromeChecker extends PalindromeChecker{


private String s;
WordPalindromeChecker(){

}
WordPalindromeChecker(String s){
this.s=s;
isPalindrome();
}
public void setS(String S){
this.s=s;
}
public String getS(){
return s;
}
public boolean isPalindrome(){
int i=0;
int j=s.length()-1;
while(i<j){
if(s.charAt(i)!=s.charAt(j)){
return false;
}
i++;
j--;
}
return true;

}
public String displayResult(){
if(isPalindrome()){
return "The word is a palindrome.";
}
else{
return "The word is not a palindrome.";
}
}
}

class Main{
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
int n= sc.nextInt();
sc.nextLine();
String s =sc.nextLine();

PalindromeChecker p = new PalindromeChecker();


p.setN(n);
System.out.println(p.displayResult());
p=new WordPalindromeChecker(s.toLowerCase());
System.out.println(p.displayResult());
}
}

______________________________________________________________

session 3
The input consists of a single integer n.

Output format :
If the input number is an automorphic number, print "n is an automorphic number".

Otherwise, print "n is not an automorphic number".

Refer to the sample output for formatting specifications.

Code constraints :
1 ≤ n ≤ 500

Sample test cases :


Input 1 :
25
Output 1 :
25 is an automorphic number
Input 2 :
7
Output 2 :
7 is not an automorphic number
Note :
The program will be evaluated only after the “Submit Code” is clicked.
Extra spaces and new line characters in the program output will result in the
failure of the test case.
Marks : 10
Negative Marks : 0

code:

// You are using Java


import java.util.*;
interface NumberInput{
public void readNumber();
}
interface AutomorphicChecker{
public void check();
}

class AutomorphicNumber implements NumberInput,AutomorphicChecker{


private int num;
public void readNumber(){
Scanner sc = new Scanner(System.in);
num= sc.nextInt();
}
public void check(){
int sqr = num*num;
String s1= sqr+"";
String s2 = num+"";
if(s1.endsWith(s2)){
System.out.println(num+" is an automorphic number");
}
else{
System.out.println(num+" is not an automorphic number");
}
}
}
class Main{
public static void main(String[]args){
AutomorphicNumber obj = new AutomorphicNumber();
obj.readNumber();
obj.check();
}
}

___________________________________________________________________________________
________--

Problem Statement

Define an interface Growing which declares the method isGrowing().

Create a class GrowingNumber which implements the interface. Override the method
isGrowing() to check if the given number is a growing number or not. A growing
number is a number where each digit is larger than the digit to its left. For
example, 369 is a growing number but 362 is not.

Create another class GrowingString which also implements the same interface.
Override the method isGrowing() to check whether the given string is growing string
or not. If on moving from left to right, each character in the string comes after
the previous character in alphabetical order. For example, ANT is a growing string
whereas APPLE is not.

Write a program to check whether the given number is a growing number or not and
whether the given string is a growing string or not.
Input format :
The input consists of a number followed by a string separated by space.

Output format :
The first line of output prints whether the given number is a growing number or
not.

The second line prints whether the given string is a growing string or not.

Refer to the sample output for formatting specifications.

Code constraints :
The input string consists of uppercase characters.

Sample test cases :


Input 1 :
369 ANT
Output 1 :
Growing number
Growing string
Input 2 :
369 APPLE
Output 2 :
Growing number
Not growing string

code____

// You are using Java


import java.util.*;
interface Growing{
public boolean isGrowing();

class GrowingNumber implements Growing{


private int num;
GrowingNumber(int num){
this.num=num;
}
public boolean isGrowing(){
String st = num+"";
for(int i=0;i<st.length()-1;i++){
if(st.charAt(i)>st.charAt(i+1))
return false;
}
return true;
}
}
class GrowingString implements Growing{
private String st;
GrowingString(String st){
this.st=st;
}
public boolean isGrowing(){
for(int i=1;i<st.length();i++){
if(st.charAt(i)<st.charAt(i-1))
return false;
}
return true;
}
}

class Main{
public static void main(String[]args){
Scanner scan = new Scanner(System.in);
int num= scan.nextInt();
String st = scan.nextLine();

Growing growing = new GrowingNumber(num);


if(growing.isGrowing()){
System.out.println("Growing number");
}
else{
System.out.println("Not growing number");
}

growing = new GrowingString(st);

if(growing.isGrowing()){
System.out.println("Growing string");
}
else{
System.out.println("Not growing string");
}
}
}

_____________________

// You are using


import java.util.*;

interface Principal{
double principal();

}
interface InterestRate{
double interestRate();

}
class Loan implements Principal, InterestRate{
private double P;
private double R;

Loan(){
this(0.0,0.0);

Loan(double P, double R){


this.P=P;
this.R=R;
}
public double principal(){
return P;
}
public double interestRate(){
return R;
}
}

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

double P = sc.nextDouble();
double R = sc.nextDouble();
int T= sc.nextInt();

if(P<1 || R>1 || P>1000000||R<=0|| T<1||T>25){


System.out.print("Invalid input values!");

}
else{
Loan l = new Loan(P,R);
double res = l.principal()*l.interestRate()*T;
System.out.printf("Total interest paid: Rs.%.2f",res);
}

***********************************************************************************
*********************

Interface collection

Write a Java program that takes integer data from the user and adds it to an
ArrayList. Perform the following operations:

Check if a given number exists in the ArrayList or not.


Remove a particular element from the ArrayList and display the updated ArrayList.
3. Print all the elements of the ArrayList using a for loop.

4. Print all the elements using the Iterator interface.

5. Print all the elements using the for-each loop.

6. Print all the elements in descending order.

7. Count how many elements are there in the ArrayList.

Input format :
The first line of the input should contain an integer representing the size of the
ArrayList

The second line of the input should contain the elements to be added to the
ArrayList

The third line of the input should contain the number to be searched in the
ArrayList.

The fourth line of the input should contain the number to be removed from the
ArrayList

Output format :
The output should display the elements in the list after the removal.

Refer to the sample output for reference.

Sample test cases :


Input 1 :
5
10 12 14 16 18
10
20
Output 1 :
Number 10 exists in the ArrayList
ArrayList after removing 20
10 12 14 16 18
ArrayList elements using normal for loop
10 12 14 16 18
ArrayList elements using Iterator interface
10 12 14 16 18
ArrayList elements using for-each loop
10 12 14 16 18
ArrayList elements in descending order
18 16 14 12 10
Number of elements in the ArrayList: 5
Input 2 :
8
20 18 17 45 89 63 27 90
10
20
Output 2 :
Number 10 not exists in the ArrayList
ArrayList after removing 20
18 17 45 89 63 27 90
ArrayList elements using normal for loop
18 17 45 89 63 27 90
ArrayList elements using Iterator interface
18 17 45 89 63 27 90
ArrayList elements using for-each loop
18 17 45 89 63 27 90
ArrayList elements in descending order
90 89 63 45 27 18 17
Number of elements in the ArrayList: 7

// You are using Java


import java.util.*;
class Main{
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<>();
int num= sc.nextInt();
for(int i=0;i<num;i++){
list.add(sc.nextInt());
}
int search = sc.nextInt();
if(list.contains(search)){
System.out.println("Number "+search+" exists in the ArrayList");
}
else
System.out.println("Number "+search+" not exists in the ArrayList");
int del =sc.nextInt();
if(list.contains(del)){
list.remove(Integer.valueOf(del));

}
System.out.println("ArrayList after removing "+del);
for(int ele : list){
System.out.print(ele+" ");
}
System.out.println("\nArrayList elements using normal for loop");
for(int i =0;i<list.size();i++){
System.out.print(list.get(i)+" ");

}
System.out.println("\nArrayList elements using Iterator interface");

Iterator<Integer> itr = list.iterator();

while(itr.hasNext()){
System.out.print(itr.next());

}
System.out.println("\nArrayList elements using for-each loop");
for(int ele:list){
System.out.print(ele+" ");
}
System.out.println("\nArrayList elements in descending order");
Collections.sort(list,Collections.reverseOrder());
for(int ele :list){
System.out.print(ele+" ");
}
System.out.println();
System.out.println("Number of elements in the ArrayList: "+ list.size());

}
}

_______________
Create a Java program that enables users to dynamically input employee details and
store them in an ArrayList.

The program should include a class named "Employee" with private attributes:

employeeName - String
employeeId - int
employeeDepartment - String

The Employee class should have the following methods:

Write a getter method for the above-mentioned attributes.


An overridden toString() method that returns the employee's details.
Input format :
The first line consists of the size of the ArrayList.

The next consecutive line contains employeeName, employeeId, employeeDepartment.

Output format :
The output should display the list of employees.

Refer to the sample output for reference.

Sample test cases :


Input 1 :
1
Elon
CEO
Output 1 :
List of All 101
Employees
Employee [employeeName=Elon, employeeId=101, employeeDepartment=CEO]
Input 2 :
2
Elon
101
CEO
Micheal
1001
Manager
Output 2 :
List of All Employees
Employee [employeeName=Elon, employeeId=101, employeeDepartment=CEO]
Employee [employeeName=Micheaal

code:

// You are using Java


import java.util.*;

class Employee{
private String employeeName;
private int employeeId;
private String employeeDepartment;

Employee (String employeeName, int employeeId,String employeeDepartment){


this.employeeName= employeeName;
this.employeeId= employeeId;
this.employeeDepartment=employeeDepartment;
}

public void setEmployeeName(String employeeName){


this.employeeName= employeeName;
}
public String getEmployeeName(){
return employeeName;
}
public void setEmployeeDepartment(String employeeDepartment){
this.employeeDepartment= employeeDepartment;
}

public String getEmployeeDepartment(){


return employeeDepartment;
}
public void setEmployeeId(int employeeId){
this.employeeId= employeeId;
}

public int getEmployeeId(){


return employeeId;
}

@Override
public String toString(){
return "Employee
[employeeName="+employeeName+",employeeId="+employeeId+",employeeDepartment="+emplo
yeeDepartment+"]";
}

class test{
public static void main(String []args){

Scanner sc= new Scanner(System.in);


int n= sc.nextInt();
List<Employee>emp = new ArrayList<>();
System.out.println("List of All Employees");
sc.nextLine();

for(int i=0;i<n;i++){
String ename= sc.nextLine();
int eid = sc.nextInt();
sc.nextLine();
String edept = sc.nextLine();
Employee e = new Employee(ename,eid,edept);
emp.add(e);
System.out.println(e);
}

}
_______________________

Single File Programming Question


You are tasked with developing a simple inventory management system for a library
that keeps track of book titles using a LinkedList. The program should allow the
user to input a specified number of book titles and then display the list of books
in the inventory.

Input format :
The first line of the input contains the number of books.

The subsequent lines each contain the title of a book.

Output format :
Displays the final list of books

Refer to the sample output

Sample test cases :


Input 1 :
2
The Great Gatsby
Moby Dick
Output 1 :
Books in the inventory:
The Great Gatsby
Moby Dick
Input 2 :
5
The Alchemist
Sapiens: A Brief History of Humankind
Educated
Becoming
The Book Thief
Output 2 :
Books in the inventory:
The Alchemist
Sapiens: A Brief History of Humankind
Educated
Becoming
The Book Thief

code
// You are using Java
import java.util.*;
class Main{
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.nextLine();
LinkedList<String> list = new LinkedList<>();
for(int i=0;i<n;i++){
list.add(sc.nextLine());

}
System.out.println("Books in the inventory:");
for(String Booktitle : list){
System.out.println(Booktitle);
}
}
}

_________________________
Weekly TEST___________

/ You are using Java


import java.util.*;

class Product{
private int productId;
private String productName;
private double productPrice;
private String productCategory;

Product(){
this(0,"",0.0,"");
}

Product(int productId,String productName,double productPrice, String


productCategory){
this.productId = productId;
this.productName = productName;
this.productPrice = productPrice;
this.productCategory = productCategory;
}

public void setProductId(int productId){


this.productId = productId;
}

public int getProductId(){


return productId;
}

public void setProductName(String productName){


this.productName = productName;
}

public String getProductName(){


return productName;
}

public void setProductPrice(double productPrice){


this.productPrice = productPrice;
}

public double getProductPrice(){


return productPrice;
}

public void setProductCategory(String productCategory){


this.productCategory = productCategory;
}

public String getProductCategory(){


return productCategory;
}

public String toString(){


return "Product ID : "+productId+", Name : "+productName+", Price :
"+productPrice+", Category : "+productCategory;
}
}

class ProductList{
private Product[] products;
private int nop;

ProductList(){
this(5);
}

ProductList(int size){
products = new Product[size];
nop = 0;
}

public void addProduct(int productId,String productName,double


productPrice,String productCategory){
Product product = new
Product(productId,productName,productPrice,productCategory);
products[nop] = product;
nop++;
}

public void displayProducts(){


for(int i=0;i<nop;i++){
System.out.println(products[i]);
}
}
}

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

int n = scan.nextInt();

ProductList list = new ProductList(n);

for(int i=0;i<n;i++){
int pid = scan.nextInt();
scan.nextLine();
String pnm = scan.nextLine();
double price = scan.nextDouble();
scan.nextLine();
String cat = scan.nextLine();

list.addProduct(pid,pnm,price,cat);
}

list.displayProducts();
}
}

_______________________________________

In a ticket reservation system, you store the available seat numbers in a TreeSet.
Users input their desired seat number, and the program checks whether the chosen
seat is available.
Using a TreeSet ensures quick and efficient verification of seat availability,
ensuring a smooth and organized ticket booking process.

Input format :
The first line of input contains a single integer n, representing the number of
available seats.

The second line contains n space-separated integers, representing the available


seat numbers.

The third line contains an integer m, representing the seat number that needs to be
searched.

Output format :
The output displays "[m] is present!" if the given seat is available. Otherwise, it
displays "[m] is not present!"

Refer to the sample output for the formatting specifications.

Code constraints :
The given test cases fall under the following constraints:

1 ≤ n ≤ 10

1 ≤ seat number ≤ 10

Sample test cases :


Input 1 :
4
2 4 5 6
5
Output 1 :
5 is present!

// You are using Java


import java.util.*;
class Main{
public static void main(String[]args){
TreeSet<Integer> ts =new TreeSet<>();
Scanner sc = new Scanner(System.in);
int n= sc.nextInt();
for(int i=0;i<n;i++){
ts.add(sc.nextInt());

}
int m = sc.nextInt();
if(!ts.contains(m)){
System.out.println(m+" is not present!");
}
else{
System.out.println(m+" is present!");
}
}
}
___________________
Problem Statement

In a bustling classroom, students are specifying their extracurricular activity


preferences. To streamline this process, write a program that employs a TreeSet.

Implement a program that takes the number of students and their unique preferences
as input, sorts the preferences, and then simulates allocating the most preferred
activity by removing the first preference from the sorted list. Output the updated
TreeSet.

Input format :
The first line consists of a single integer N, representing the number of students

The second line consists of N space-separated integers, representing individual


preferences.

Output format :
The output prints the updated TreeSet after sorting preferences and simulating
allocation by removing the first preference.

Refer to the sample output for the formatting specifications.

Code constraints :
1 ≤ N ≤ 10

Sample test cases :


Input 1 :
5
74 56 32 19 97
Output 1 :
[32, 56, 74, 97]
Input 2 :
10
96 15 88 28 63 55 41 87 8 100
Output 2 :
[15, 28, 41, 55, 63, 87, 88, 96, 100]
Note :
The program will be evaluated only after the “Submit Code” is clicked.
Extra spaces and new line characters in the program output will result in the
failure of the test case.
// You are using Java
import java.util.*;
class Main{
public static void main(String[]args){
Scanner sc= new Scanner(System.in);
TreeSet<Integer> list = new TreeSet<>();
int n= sc.nextInt();

for(int i=1;i<=n;i++){
list.add(sc.nextInt());
}
Iterator<Integer> it= list.iterator();
it.next();
it.remove();
System.out.println(list);
}

_________________

Single File Programming Question


Problem Statement:

In a fruit basket application, users input various fruits to create a TreeSet of


unique fruit names. The program, designed for efficient fruit management,
identifies and displays the longest fruit name in the basket.

This functionality is particularly useful for inventory tracking and ensuring that
longer-named fruits are accommodated in the basket.

Input format :
The first line contains a single integer n, representing the number of fruits
present in the TreeSet.

The next n lines contain a string in each, representing a fruit name.

Output format :
The output prints "Longest word: " followed by the longest fruit name present in
the TreeSet.

Refer to the sample output for the formatting specifications.

Code constraints :
The given test cases fall under the following constraints:

1 ≤ n ≤ 10

1 ≤ length of each fruit name ≤ 20

Sample test cases :


Input 1 :
2
apple
banana
Output 1 :
Longest word: banana
Input 2 :
3
orange
mango
pineapple
Output 2 :
Longest word: pineapple

code:
// You are using Java
import java.util.*;

class Main{
public static void main(String[]args){
Scanner sc= new Scanner(System.in);
TreeSet<String> ts= new TreeSet<>();
int n= sc.nextInt();
sc.nextLine();

for(int i=0;i<n;i++){
ts.add(sc.nextLine());
}
String longWord =null;
for(String word: ts){
if(longWord==null)longWord=word;
else if(word.length()>longWord.length())longWord=word;
}
System.out.println("Longest word: "+longWord);
}
}

_______________session 3_________________________

Write a program that sorts a list of Hall objects based on their cost per day using
the sort() method of the Comparable interface. Then display them in a tabular form.

Create a class Hall with the following attributes,

name - String
contactNumber - String
costPerDay - double
ownerName - String

Declare the attributes as private and add appropriate getter/setter methods, along
with default and parameterized constructors. Override the toString() method to
print the details in a tabular format. Implement the Comparable interface in the
class.

Create a driver class named Main and utilize the main method to gather inputs, sort
the objects, and display them.

Input format :
The first line contains the number of halls, denoted as 'n'.

The subsequent 'n' lines contain details of each hall.

Output format :
The output displays the details of the halls.

Refer to the sample output for reference.

Sample test cases :


Input 1 :
3
SDH hall
12345
12000.0
Jane
XUV hall
24680
15000.0
Jack
SRT hall
13579
20000.0
John
Output 1 :
SDH hall 12345 12000.0 Jane
XUV hall 24680 15000.0 Jack
SRT hall 13579 20000.0 John
Input 2 :
6
SDH hall
12345
12000.0
Jane
XUV hall
24680
15000.0
Jack
SRT hall
13579
20000.0
John
DFG hall
24680
10000
Jack
STR hall
13579
25000
Jane
JKL hall
67890
20000
Joe
Output 2 :
DFG hall 24680 10000.0 Jack
SDH hall 12345 12000.0 Jane
XUV hall 24680 15000.0 Jack
SRT hall 13579 20000.0 John
JKL hall 67890 20000.0 Joe
STR hall 13579 25000.

code 1 my sir
// You are using Java
import java.util.*;
class Hall implements Comparable<Hall>{
private String name;
private String contactNumber;
private double costPerDay;
private String ownerName;

Hall(){
this("","",0.0,"");
}
Hall(String name, String contactNumber, double costPerDay, String ownerName){
this.name = name;
this.contactNumber= contactNumber;
this.costPerDay= costPerDay;
this.ownerName= ownerName;
}

public String getContactNumber(){


return contactNumber;
}
public String getName(){
return name;
}
public String toString(){
return name+" "+contactNumber+" "+costPerDay+" "+ownerName;
}

public int compareTo(Hall h2){


Double.compare(this.costPerDay, h2.costPerDay);
if(this.costPerDay>h2.costPerDay) return 1;
else if(this.costPerDay<h2.costPerDay) return -1;
else {
return 0;
}
}
}

class NameComparator implements Comparator<Hall>{


public int compare(Hall h1, Hall h2){
return h1.getName().compareTo(h2.getName());
}
}

class Main{

public static void main(String[]args){


Scanner sc = new Scanner(System.in);
ArrayList<Hall> list = new ArrayList<>();

int n= sc.nextInt();
sc.nextLine();
for(int i=1;i<=n;i++){
String name = sc.nextLine();
String contact = sc.nextLine();
double cost = sc.nextDouble();
sc.nextLine();
String owner = sc.nextLine();

Hall hall = new Hall(name, contact ,cost,owner);


list.add(hall);

}
Collections.sort(list);
for(Hall h : list){
System.out.println(h);
}
}
}

___________code2 by agrim____________

/You are using Java


import java.util.*;
import java.util.Collections;
class Hall implements Comparable<Hall>{
private String name;
private String contactNumber ;
private double costPerDay;
private String ownerName;
public Hall(String name,String contactNumber,double costPerDay,String
ownerName){
this.name = name;
this.contactNumber = contactNumber;
this.costPerDay = costPerDay;
this.ownerName = ownerName;
}
public String getName(){
return name;
}
public String getContactNumber(){
return contactNumber;
}
public double getCostPerDay(){
return costPerDay;
}
public String ownerName(){
return ownerName;
}
public int compareTo(Hall obj){
return Double.compare(this.costPerDay,obj.costPerDay);
}
@Override
public String toString(){
return name + " " + contactNumber + " " + costPerDay + " " + ownerName;
}
}
class Driver{
public static void main(String [] args){
Scanner in = new Scanner(System.in);
ArrayList<Hall> arr = new ArrayList<>();
int n = in.nextInt();
in.nextLine();
for(int i =0;i<n;i++){
String name = in.nextLine();
String contactNumber = in.nextLine();
double costPerDay = in.nextDouble();
in.nextLine();
String ownerName = in.nextLine();
Hall h = new Hall(name,contactNumber,costPerDay,ownerName);
arr.add(h);
}
Collections.sort(arr);
for(Hall h : arr)
System.out.println(h);
}
}

________________
Employee High Score Leaderboard Management System

Develop a Java program to efficiently manage and display a leaderboard of employees


based on their scores using ArrayList.

Create a class named Employee with the following attributes:

name - String
score - double
Declare the attributes as private and add appropriate getter/setter methods, along
with default and parameterized constructors. The output should present the
leaderboard in descending order of scores using comparable.

Input format :
An integer 'n' (1 <= n <= 100) represents the number of employees.

Each employee is provided with their name, which consists of alphanumeric


characters, followed by their score, which may be an integer or a decimal number.

Output format :
Display the leaderboard in descending order of scores.

Refer to the sample output for reference.

Code constraints :
Employee names will not exceed 100 characters.

Implement the Comparable interface for natural ordering

Sample test cases :


Input 1 :
5
John 2500
Jane 1800.5
Adam 2100
Sarah 1900
Mike 2250.75
Output 1 :
John 2500.0
Mike 2250.75
Adam 2100.0
Sarah 1900.0
Jane 1800.5
Input 2 :
3
John 2500
Jane 1800.5
Adam 2100
Output 2 :
John 2500.0
Adam 2100.0
Jane 1800.5

code::
// You are using Java
import java.util.*;
class Employee implements Comparable <Employee>{
private String name;
private double score;
public Employee(String name, double score){
this.name=name;
this.score= score;
}
public String getName(){
return name;
}
public Double getScore(){
return score;
}
public int compareTo(Employee E){
return Double.compare(E.score,this.score);
}
public String toString(){
return name+" "+score;
}
}

class Driver{
public static void main(String[]args){
Scanner in = new Scanner(System.in);
ArrayList<Employee>arr = new ArrayList<>();
int n= in.nextInt();

in.nextLine();

for(int i=0;i<n;i++){
String value[]= in.nextLine().split(" ");
Employee obj = new Employee(value[0],Double.valueOf(value[1]));
arr.add(obj);
}
Collections.sort(arr);
for(Employee ele : arr){
System.out.println(ele);
}
}
}
___________________

Movie Streaming Platform: Rating-based Sorting

Develop a streaming platform similar to Netflix that manages a library of movies.


Implement the necessary classes and interfaces to support the following
functionality:

1. Create a class called Movie with the following properties:


title - String
releaseYear - int
rating - double
Declare the attributes as private and add appropriate getter/setter methods, along
with default and parameterized constructors.

2. Implement a Comparator called MovieComparator that compares movies based on


their ratings in ascending order.

3. In the Main class, create a collection (e.g., ArrayList) to store instances of


the Movie class. Prompt the user to enter the details of several movies, including
the title, release year, and rating. Create Movie objects based on the user input
and add them to the collection.

4. Display the movies in the sorted order, showing the title, release year, and
rating for each movie.

Input format :
The first line of input is an integer representing the number of movies.

The second line of input is a String representing the title of movie.

The third line of input is an integer representing the release year of movie.

The fourth line of input is a double value representing the rating of movie.

Output format :
The output displays the movies sorted by rating in ascending order.

Refer to the sample output for reference.

Sample test cases :


Input 1 :
4
Action Movie
2012
6.4
Comedy Flick
2014
7.2
Drama Film
2010
8.1
Sci-Fi Thriller
2016
7.9
Output 1 :
Title: Action Movie, Release Year: 2012, Rating: 6.4
Title: Comedy Flick, Release Year: 2014, Rating: 7.2
Title: Sci-Fi Thriller, Release Year: 2016, Rating: 7.9
Title:Drama Film, Release Year: 2010, Rating: 8.1

code:

// You are using Java


import java.util.*;
class Movie{
private String title;
private int releaseYear;
private double rating;

public Movie(String title, int releaseYear, double rating){


this.title= title;
this.releaseYear= releaseYear;
this.rating=rating;
}
public String toString(){
return "Title: "+title+", "+"Release Year: "+releaseYear+", "+"Rating:
"+rating;
}
public double getRating(){
return rating;
}
}

class MovieComparator implements Comparator<Movie>{


public int compare(Movie m1 , Movie m2){
return Double.compare(m1.getRating(),m2.getRating());
}
}

class Main{
public static void main(String[]args){
Scanner sc= new Scanner(System.in);
ArrayList<Movie>arr= new ArrayList<>();
int n= sc.nextInt();
for(int i=0;i<n;i++){
sc.nextLine();
String title= sc.nextLine();
int releaseYear = sc.nextInt();
double rating = sc.nextDouble();
Movie m1= new Movie(title, releaseYear,rating);
arr.add(m1);
}
Collections.sort(arr,new MovieComparator());
for(Movie ele: arr){
System.out.println(ele);
}

}
}

___________________

HASHMAP

SESSION 1
Using Java's 'HashMap' and 'Collections', write a program to find and sort the
common words from two lines of input text. Each line contains multiple words
separated by spaces. The program should identify the common words between the two
lines and display them in lexicographically sorted order.

Input format :
The first line contains a string of words.
The second line contains another string of words.
Output format :
The output prints the set of common words found in both lines enclosed in square
brackets, separated by commas.

Refer to the sample output for formatting specifications

Code constraints :
Each line of text may contain up to 100 words.
Words in the input lines are case-sensitive.
Sample test cases :
Input 1 :
one two three
two four
Output 1 :
[two]
Input 2 :
first second third
third fourth second
Output 2 :
[second, third]

code:

// You are using Java


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

Scanner sc = new Scanner(System.in);


String line1= sc.nextLine();
String line2 = sc.nextLine();

String[]arr1= line1.split(" ");


String[]arr2 = line2.split(" ");

HashMap<String,String> map1 = new HashMap<>();


HashMap<String, String> map2 = new HashMap<>();

for(int i=0;i<arr1.length;i++){
map1.put(arr1[i],null);
}

for(int i=0;i<arr2.length;i++){
map2.put(arr2[i],null);
}

Set<String>set= map1.keySet();
ArrayList<String> coll = new ArrayList<>();
for(String k: set){
if(map2.containsKey(k)){
coll.add(k);
}
}
Collections.sort(coll);
System.out.println(coll);
}
}

___________________
You are tasked with managing and sorting a collection of halls. Each hall has
details such as name, contact number, cost per day, and owner name. You need to
create a program that reads the details of multiple halls, stores them, and then
displays them sorted by their cost per day in ascending order.

Requirements:

Create a class named 'Hall' with the following private attributes:

String name
String contactNumber
double costPerDay
String ownerName

Include the following methods in the 'Hall' class:

Getters and setters for all attributes.


A default constructor.
A parameterized constructor: public Hall(String name, String contactNumber, double
costPerDay, String ownerName)
Override the 'toString' method to return a string representation of the hall
details.
Implement the Comparable<Hall> interface to sort halls by 'costPerDay'.

Create a 'Main' class. In the main method:

Read the number of halls.


Read the details for each hall and store them uniquely by their names in a
Map<String, Hall> data structure.
Display all the hall details sorted by 'costPerDay'.
Input format :
The first line contains an integer 'n', representing the number of halls.
The subsequent 'n' sets of lines contain the details of each hall in the following
order:
Hall name
Contact number
Cost per day
Owner name
Output format :
The output displays the details of the halls sorted by 'costPerDay'.

Refer to the sample output for formatting specifications.

Sample test cases :


Input 1 :
3
SDH hall
12345
12000.0
Jane
XUV hall
24680
15000.0
Jack
SRT hall
13579
20000.0
John
Output 1 :
SDH hall 12345 12000.0 Jane
XUV hall 24680 15000.0 Jack
SRT hall 13579 20000.0 John
Input 2 :
6
SDH hall
12345
12000.0
Jane
XUV hall
24680
15000.0
Jack
SRT hall
13579
20000.0
John
DFG hall
24680
10000
Jack
STR hall
13579
25000
Jane
JKL hall
67890
20000
Joe
Output 2 :
DFG hall 24680 10000.0 Jack
SDH hall 12345 12000.0 Jane
XUV hall 24680 15000.0 Jack
SRT hall 13579 20000.0 John
JKL hall 67890 20000.0 Joe
STR hall 13579 25000.0 Jan

code:::

// You are using Java


import java.util.*;
class Hall implements Comparable<Hall>{
private String name;
private String contactNumber;
private double costPerDay;
private String ownerName;

public Hall(){

}
Hall(String name,String contactNumber, double costPerDay, String ownerName){
this .name= name;
this.contactNumber= contactNumber;
this.costPerDay= costPerDay;
this.ownerName= ownerName;
}

public String toString(){


return name +" "+contactNumber+" "+costPerDay+" "+ownerName;
}
public int compareTo(Hall h){
return Double.compare(h.costPerDay,this.costPerDay);
}
}
class HallManagement{
public static void main(String[]args){
Scanner sc=new Scanner(System.in);
HashMap<String, Hall> mp= new HashMap<>();
ArrayList<Hall> list= new ArrayList<>();
int n= sc.nextInt();
sc.nextLine();
for(int i=0;i<n;i++){
String name= sc.nextLine();
String contactNumber= sc.nextLine();
double costPerDay= sc.nextDouble();
sc.nextLine();
String ownerName= sc.nextLine();
Hall ob = new Hall(name,contactNumber,costPerDay,ownerName);
list.add(ob);
mp.put(name,ob);

}
Collections.sort(list);
for(Hall hi:list){
System.out.println(hi);
}

}
}

Q3--
Mahesh is developing a phone book application to manage contacts efficiently. He
needs to add new contacts and display all existing contacts. Using a HashMap, write
a program to assist him with this task.

Functional Requirements
1. Add a Contact:

Implement a method addContact(String phoneNumber, String name) that adds a new


contact to the phone book.
This method should store the contact in a HashMap with the phone number as the key
and the name as the value.

2. Display All Contacts:

Implement a method displayContacts() that displays all the contacts in the phone
book.
The method should iterate over the entries in the HashMap and print the details of
each contact in the format Name: {name}, Phone Number: {phoneNumber}.

Instructions: The Main class name must be public class Main

Input format :
The first line of the input is an integer representing the number of contacts to
add.

The subsequent lines contain the contact details, where each contact is represented
by two lines:

The first line contains the name of the contact (a string).


The second line contains the phone number of the contact (a string).
Output format :
The output displays all contacts in the format:

All Contacts:

Name: {name}, Phone Number: {phoneNumber}

Refer to the sample output for formatting specifications.

Sample test cases :


Input 1 :
2
Jack Daniel
9876543210
Mary Paul
9638527410
Output 1 :
All Contacts:
Name: Jack Daniel, Phone Number: 9876543210
Name: Mary Paul, Phone Number: 9638527410
Input 2 :
3
Tom
9632587410
Jerry
9687543210
Joe
9658963256
Output 2 :
All Contacts:
Name: Joe, Phone Number: 9658963256
Name: Tom, Phone Number: 9632587410
Name: Jerry, Phone Number: 9687543210

// You are using Java


import java.util.*;

class PhoneBook{
HashMap<String, String> contacts = new HashMap<>();
/*PjhoneBook(){
contacts= new HashMap;
}*/

public void addContact(String name, String pno){


contacts.put(pno,name);
}
void displayContact(){
for(Map.Entry<String, String> me: contacts.entrySet()){
System.out.println("Name:"+me.getValue()+",Phone Number:"+me.getKey());
}
}
}
class main{
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
PhoneBook book = new PhoneBook();
int n= sc.nextInt();
sc.nextLine();
for(int i=1;i<=n;i++){
String name= sc.nextLine();
String phone = sc.nextLine();
book.addContact(name,phone);

}
System.out.println("All Contacts:");
book.displayContact();

}
}
___________________________________________________________________
SESSION 2

Prashanth is given a program that calculates the frequency of each character in a


given string. The program utilizes a TreeMap to store the characters and their
respective frequencies. After processing the input string, it prints the character
frequencies in lexicographical order.

He needs your help in completing the program.

Input format :
The input consists of a single string that contains any combination of letters,
digits, spaces, and special characters.

Output format :
For each unique character in the input string, print a line in the format:
'[character]': [frequency]

The output should be sorted in ascending order based on the characters.

Refer to the sample output for formatting specifications.

Code constraints :
The test cases will fall under the following constraints:

length of string ≤ 250

The program should be case-sensitive, meaning 'a' and 'A' are considered different
characters.

Sample test cases :


Input 1 :
Python programming!
Output 1 :
' ': 1
'!': 1
'P': 1
'a': 1
'g': 2
'h': 1
'i': 1
'm': 2
'n': 2
'o': 2
'p': 1
'r': 2
't': 1
'y': 1
Input 2 :
122233335558
Output 2 :
'1': 1
'2': 3
'3': 4
'5': 3
'8': 1
Input 3 :
Radiator
Output 3 :
'R': 1
'a': 2
'd': 1
'i': 1
'o': 1
'r': 1
't': 1

// You are using Java


import java.util.*;
class Main{
public static void main(String []args){
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
TreeMap<Character, Integer> map = new TreeMap<>();

for(int i=0;i<str.length();i++){
char ch = str.charAt(i);
if(!map.containsKey(ch)){
map.put(ch,1);
}
else{
int cnt = map.get(ch);
cnt++;
map.put(ch,cnt);
}
}
Set<Map.Entry<Character,Integer>> set = map.entrySet();
for(Map.Entry<Character,Integer> e: set){
System.out.println("'"+e.getKey()+"':"+e.getValue());
}

_________________________________________________________________

Senthil is working on a system that tracks the order of books purchased by


customers at a bookstore. He wants to create a program that records the order in
which books are added and their corresponding quantities. Additionally, the program
should allow the removal of books if they are no longer in stock. The program
should store this information in a LinkedHashMap, ensuring the order of insertion
is maintained.

The user can either add or remove a book by specifying the action followed by the
book name and quantity. If a book is removed, it should be completely deleted from
the system if its quantity reaches 0 or below.

He needs your help to complete the program.

Input format :
The input consists of multiple lines where each line represents an action (add or
remove), followed by a book title and its quantity, separated by a space.

Input ends when the user provides a blank line.

Output format :
For each unique book, print a line in the format: Book: [book_title], Quantity:
[quantity].

The output should preserve the order in which the books were added, as tracked by
the LinkedHashMap.
Code constraints :
The total number of books ≤ 50.
The length of each book title ≤ 50 characters.
Quantities are non-negative integers ≤ 1000.
The program should handle invalid inputs such as missing quantities, non-numeric
quantities, negative quantities, and invalid actions.
When a book's quantity becomes 0 or negative, it should be removed from the list

Sample test cases :


Input 1 :
add HarryPotter 3
add LOTR 5
add 1984 2
remove HarryPotter 2
Output 1 :
Final Book List:
Book: HarryPotter, Quantity: 1
Book: LOTR, Quantity: 5
Book: 1984, Quantity: 2
Input 2 :
add HarryPotter 3
add LOTR 5
add 1984 2
remove HarryPotter 3
remove LOTR 5
Output 2 :
Final Book List:
Book: 1984, Quantity: 2
Input 3 :
add HarryPotter 3
add LOTR 5
add 1984
Output 3 :
Invalid input. Please enter action, book title, and quantity.
Final Book List:
Book: HarryPotter, Quantity: 3
Book: LOTR, Quantity: 5
Input 4 :
add HarryPotter 3
add LOTR 5
remove LOTR -3
add 1984 2
Output 4 :
Quantity should be between 0 and 1000.
Final Book List:
Book: HarryPotter, Quantity: 3
Book: LOTR, Quantity: 5
Book: 1984, Quantity: 2
Input 5 :
add HarryPotter 3
remove LOTR five
add 1984 2
Output 5 :
Invalid quantity. Please enter a non-negative integer.
Final Book List:
Book: HarryPotter, Quantity: 3
Book: 1984, Quantity: 2
Input 6 :
add HarryPotter 3
remove 5
add 1984 2
Output 6 :
Invalid input. Please enter action, book title, and quantity.
Final Book List:
Book: HarryPotter, Quantity: 3
Book: 1984, Quantity: 2

code:

// You are using Java


import java.util.*;
class Book{

public static void main(String[]args){


Scanner sc = new Scanner(System.in);
LinkedHashMap<String,Integer> map = new LinkedHashMap<>();
while(sc.hasNext()){
String arr[]= sc.nextLine().split(" ");
if(arr.length!=3){
System.out.println("Invalid input. please enter action, book title,
and quantity.");
continue;
}
try{
int quantity = Integer.parseInt(arr[2]);
String book = String.valueOf(arr[1]);
if(quantity<0){
System.out.println("Quantity should be between 0 and 1000.");
continue;
}
switch(arr[0]){
case "add":
if(map.containsKey(book)){
map.put(book,map.get(book)+quantity);
}
else{
map.put(book,quantity);
}
break;
case "remove":
if(map.containsKey(book)){
if(map.get(book)-quantity<=0){
map.remove(book);
}
else{
map.put(book,map.get(book)-quantity);
}
}
break;
}
}
catch(Exception E){
System.out.println("Invalid quantity. Please enter a non-negative
integer.");
}
}
System.out.println("Final Book List:");
for(Map.Entry<String,Integer>ele:map.entrySet()){
System.out.println("Book: "+ele.getKey()+", Quantity:
"+ele.getValue());
}
}

______________________________________________

Abishek is working on a system that tracks the order of items purchased by


customers. He wants to create a program that records the order in which items are
added and their corresponding quantities. The program should store this information
in a LinkedHashMap, ensuring the order of insertion is maintained.

He needs your help to complete the program.

Input format :
The input consists of multiple lines where each line represents an item and its
quantity, separated by a space.

Input ends when the user provides a blank line.

Output format :
For each unique item, print a line in the format: Item: [item_name], Quantity:
[quantity].

The output should preserve the order in which the items were added, as tracked by
the LinkedHashMap.

Code constraints :
The total number of items ≤ 50.
The length of each item name ≤ 30.
Sample test cases :
Input 1 :
Apple 3
Banana 5
Orange 2
Output 1 :
Order Summary:
Item: Apple, Quantity: 3
Item: Banana, Quantity: 5
Item: Orange, Quantity: 2
Input 2 :
Apple 3
Banana 5
Orange 2
Banana 2
Apple 1
Output 2 :
Order Summary:
Item: Apple, Quantity: 4
Item: Banana, Quantity: 7
Item: Orange, Quantity: 2
code::
// You are using Java
import java.util.*;
class Main{
public static void main(String []args){
Scanner sc = new Scanner(System.in);
LinkedHashMap<String,Integer>map = new LinkedHashMap<>();
while(sc.hasNext()){
String s1= sc.next();
int n1= sc.nextInt();
if(!map.containsKey(s1)){
map.put(s1,n1);
}else{
int q = map.get(s1);
map.put(s1,q+n1);
}
}
System.out.println("Order Summary:");
Set<Map.Entry<String,Integer>>set= map.entrySet();
for(Map.Entry<String,Integer> e:set){
System.out.println("Item: "+e.getKey()+", Quantity: "+e.getValue());
}
}
}
_______________________________________________________________

Management is building a Student Grades Tracker for a school. The program needs to
record the grades for students in different subjects. Each student can be enrolled
in multiple subjects, and their grades should be updated as new scores are
provided. The order of input for students and subjects must be preserved.

The program should allow adding new students and their subject grades.
It should also allow updating the grades for existing students in specific
subjects.
Input format :
The input consists of multiple lines where each line contains an action (add,
update, or remove), followed by a student name, a subject, and a grade (only
applicable for add and update actions).

The input ends when the user provides a blank line.

Output format :
For each student, print their subjects and corresponding grades in the format:

Student: [student_name], Subject: [subject], Grade: [grade]

The output should preserve the order of student entries and the order of their
subjects, as stored in the LinkedHashMap.

Code constraints :
The total number of students ≤ 50.
Each student can have up to 10 subjects.
Grades are integers between 0 and 100.
The length of student names and subjects ≤ 30 characters.

Sample test cases :


Input 1 :
add ram Math 85
add ram Science 90
add damu Math 78
add damu English 88
update damu Math 80
Output 1 :
Added: ram in Math with grade 85
Added: ram in Science with grade 90
Added: damu in Math with grade 78
Added: damu in English with grade 88
Updated: damu in Math with grade 80
Input 2 :
add Abi Math 85
add Abi Science 90
add Gopi Math 78
update Gopi English 88
Output 2 :
Added: Abi in Math with grade 85
Added: Abi in Science with grade 90
Added: Gopi in Math with grade 78
Subject English not found for student Gopi.
Input 3 :
add gopi Math 85
update gopi
Output 3 :
Added: gopi in Math with grade 85
Invalid input. Please enter 'action student_name subject_name [grade]'.
Input 4 :
add Abishek Math 85
add Gopi Math 78
update Gopi Math 110
Output 4 :
Added: Abishek in Math with grade 85
Added: Gopi in Math with grade 78
Grade should be between 0 and 100.
Input 5 :
add Abishek Math 85
add Gopi Math seventy
Output 5 :
Added: Abishek in Math with grade 85
Invalid grade. Please enter an integer between 0 and 100.

// You are using Java


import java.util.*;
class Main{
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
LinkedHashMap<String,LinkedHashMap<String,Integer>>map= new LinkedHashMap<>();
String cmd;

while(sc.hasNextLine()){
String input = sc.nextLine().trim();
if(input.isEmpty()){
break;
}
String[] parts = input.split(" ");

if(parts.length<3){
System.out.println("Invalid input. Please enter 'action student_name
subject_name [grade]'.");
continue;
}

cmd = parts[0];
String name = parts[1];
String subject = parts[2];
int marks =0;

if(cmd.equals("add")||cmd.equals("update")){
if(parts.length!=4){
System.out.println("Invalid input. Please enter 'action
student_name subject_name [grade]'.");
continue;
}
try{
marks= Integer.parseInt(parts[3]);
if(marks<0 || marks>100){
System.out.println("Grade should be between 0 and 100.");
continue;
}
}
catch(NumberFormatException e){
System.out.println("Invalid grade. Please enter an integer between
0 and 100.");
continue;
}

}
switch(cmd){
case "add":
map.putIfAbsent(name,new LinkedHashMap<>());
map.get(name).put(subject,marks);
System.out.println("Added: "+ name +" in "+ subject +" with grade
"+ marks);
break;
case "update":
if(map.containsKey(name) && map.get(name).containsKey(subject)){
map.get(name).put(subject,marks);
System.out.println("Updated: "+name+" in" +subject+" with
grade "+marks);
}else{
System.out.println("Subject "+subject+" not found for student
"+name+".");
}
break;
default:
System.out.println("Invalid action. Please use 'add' or 'update'.");
break;
}

}
}

_______________________________

Problem Statement:

State Board of secondary education had recently conducted a board exam for grade
10th students. They need to sort the “n” students based on rank. Write a program to
help the board members get the student's name list on a rank basis using TreeMap.

Note: Consider that there are “n” numbers of students whose marks are calculated
out of 600.

Input format :
The first line of input consists of integer n represents the number of students.

The next n line of inputs represents the student's mark and name separated by next
lines.

Output format :
The output should display the ranks of students based on their marks in ascending
order.

Each rank should be formatted as Rank X: StudentName, where X is the rank number
starting from 1.

Refer to the sample output for formatting specifications.

Code constraints :
The number of students (n) is ≤ 10.

The student's mark are ≤ 600.

Sample test cases :


Input 1 :
4
541
Sangeetha
452
Arshad
367
Ganesh
456
Priya
Output 1 :
The ranks based on their marks:
Rank 1: Sangeetha
Rank 2: Priya
Rank 3: Arshad
Rank 4: Ganesh

import java.util.*;
class Test{
public static void main(String[]args){
TreeMap<Integer, String> t= new TreeMap<>(Collections.reverseOrder());

Scanner sc = new Scanner(System.in);


int n = sc.nextInt();
for(int i=0;i<n;i++){
int a = sc.nextInt();
sc.nextLine();
String str = sc.nextLine();
t.put(a,str);
}
System.out.println("The ranks based on their marks:");
int i=1;

for(Map.Entry < Integer,String> ele: t.entrySet()){


System.out.println("Rank "+i+": "+ele.getValue());
i++;
}

}
}

/----/----------------------------------------------

Problem Statement

Prashanth is given a program that calculates the frequency of each character in a


given string. The program utilizes a TreeMap to store the characters and their
respective frequencies. After processing the input string, it prints the character
frequencies in lexicographical order.

He needs your help in completing the program.

Input format :
The input consists of a single string that contains any combination of letters,
digits, spaces, and special characters.

Output format :
For each unique character in the input string, print a line in the format:
'[character]': [frequency]

The output should be sorted in ascending order based on the characters.


Refer to the sample output for formatting specifications.

Code constraints :
The test cases will fall under the following constraints:

length of string ≤ 250

The program should be case-sensitive, meaning 'a' and 'A' are considered different
characters.

Sample test cases :


Input 1 :
Python programming!
Output 1 :
' ': 1
'!': 1
'P': 1
'a': 1
'g': 2
'h': 1
'i': 1
'm': 2
'n': 2
'o': 2
'p': 1
'r': 2
't': 1
'y': 1
Input 2 :
122233335558
Output 2 :
'1': 1
'2': 3
'3': 4
'5': 3
'8': 1
Input 3 :
Radiator
Output 3 :
'R': 1
'a': 2
'd': 1
'i': 1
'o': 1
'r': 1
't': 1

// You are using Java


import java.util.*;
class Main{
public static void main(String []args){
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
TreeMap<Character, Integer> map = new TreeMap<>();

for(int i=0;i<str.length();i++){
char ch = str.charAt(i);
if(!map.containsKey(ch)){
map.put(ch,1);
}
else{
int cnt = map.get(ch);
cnt++;
map.put(ch,cnt);
}
}
Set<Map.Entry<Character,Integer>> set = map.entrySet();
for(Map.Entry<Character,Integer> e: set){
System.out.println("'"+e.getKey()+"':"+e.getValue());
}

________________________________________________________

EXCEPTION HANDLING

Divide by zero exception.

Write a program to obtain two numbers and print their quotient. In case of an
exception print the exception message.

Input format :
Provide a single line of input separated by a space. Obtain the integers N1 and N2.

Output format :
Display the quotient if there is no exception; otherwise, print the exception
message.

Refer to the sample output for reference.

Code constraints :
Integers only.

Sample test cases :


Input 1 :
44 2
Output 1 :
22
Input 2 :
2 0
Output 2 :
java.lang.ArithmeticException: / by zero

// You are using Java

import java.util.*;
class Main{
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
try{
int n= sc.nextInt();
int m = sc.nextInt();

int q = n/m;
System.out.println(q);
}
catch(InputMismatchException e){
System.out.println(e);
}
catch(ArithmeticException e){
System.out.println(e);
}

}
}

__________________________

Input Mismatch Exception

InputMismatchException occurs when an input of a different datatype is given other


than the required. In common practice, it occurs when a String or double datatype
is given for an int datatype. Let's handle this exception for practice.

Create a driver class called Main. In the Main method, obtain integer input from
the user. If the input is an integer, print the value or else throw the
InputMismatchException.

Input format :
The input consists of a integer value.

Output format :
The output prints the given input otherwise throws InputMismatchException.

Refer sample output for reference.

Sample test cases :


Input 1 :
hello
Output 1 :
java.util.InputMismatchException
Input 2 :
9
Output 2 :
9
// You are using Java
import java.util.*;
class Main{

public static void main(String[]args){


Scanner sc = new Scanner(System.in);

try{
int input = sc.nextInt();
System.out.println(input);
}
catch(InputMismatchException e){
System.out.println(e);
}
}
}

_________________________________________

Handling IllegalArgumentException and ArithmeticException

You are tasked with developing a Java program to manage operations involving a
critical number. The program must handle potential errors using exception handling.

Create a class named 'Main' with an integer attribute number.

Write a Java program that performs the following tasks:

If the input number is 0, the program should throw an ArithmeticException with the
message "ArithmeticException caught - / by zero".
If the input number is greater than 7, the program should throw an
IllegalArgumentException with the message "IllegalArgumentException caught - Number
should not be greater than 7".
If neither of the above conditions is true, the program should return the given
number.

HINT: Use nested try block

Input format :
The input consists of a single integer.

Output format :
The output is based on the following conditions:

If an ArithmeticException is caught, print "ArithmeticException caught - / by


zero".
If an IllegalArgumentException is caught, print "IllegalArgumentException caught -
Number should not be greater than 7".
If no exception is caught, print the number itself.

Refer to the sample output for formatting specifications.

Sample test cases :


Input 1 :
5
Output 1 :
5
Input 2 :
8
Output 2 :
IllegalArgumentException caught - Number should not be greater than 7
Input 3 :
0
Output 3 :
ArithmeticException caught - / by zero

code:

// You are using Java


import java.util.*;
class Main{
public static void main(String[]args){
Scanner sc = new Scanner(System.in);

try{
int n = sc.nextInt();
if(n==0){
System.out.println("ArithmeticException caught - /by zero");

}
else if(n>7){
System.out.println("IllegalArgumentException caught - Number should not
be greater than 7");

}
else{
System.out.println(n);
}
}
catch(ArithmeticException e){
System.out.println(e);

}
catch(IllegalArgumentException e){
System.out.println(e);

}
}
}

**************************************************
Session 2:
Handling Invalid Book Quantity Exception in Library Software

Mohan, a librarian, is developing software to automate his library tasks. He needs


to handle exceptions when attempting to purchase more books than are available in
stock.

Create a Java class named "Book" with the following attributes:

id - String
bookTitle - String
authorName - String
price - float
quantityAvailable - int

Define a custom exception class named InvalidQuantityException to be used within


the 'Book' class. Implement a method purchase(int quantity) in the 'Book' class
that takes the quantity of books to be purchased as a parameter. This method should
update the quantityAvailable attribute if the purchase is valid, otherwise throw an
InvalidQuantityException with an appropriate error message.

Input format :
The input consists of the following lines:

Book ID as a String.
Book title as a String.
Author name as a String.
Price of the book as a float.
Quantity of the book available in stock as a positive integer.
Quantity of the book to be purchased as a positive integer.
Output format :
The output should display:

"Quantity Available : <quantity>" if the purchase is successful.


"InvalidQuantityException: Quantity not available" if the purchase quantity exceeds
the available quantity.

Refer to the sample output for formatting specifications.

Sample test cases :


Input 1 :
YCW2019
You can win
Shiv Khera
245
25
20
Output 1 :
Quantity Available : 5
Input 2 :
YCW2019
You can win
Shiv Khera
245
25
30
Output 2 :
InvalidQuantityException: Quantity not availabl

code::
// You are using J
import java.util.*;
class InvalidQuantityException extends Exception{
public InvalidQuantityException(){

}
public InvalidQuantityException(String message){
super(message);
}

}
class Book{
public String id;
public String bookTitle;
public String authorName;
public float price;
public int quantityAvailable;

public Book(String id,String bookTitle, String authorName,float price, int


quantityAvailable)
{
this.id =id;
this.bookTitle=bookTitle;
this.authorName= authorName;
this.price= price;
this.quantityAvailable= quantityAvailable;
}

public int purchase(int qty) throws InvalidQuantityException{


if(qty<=quantityAvailable){
quantityAvailable-=qty;
return quantityAvailable;
}
else{
throw new InvalidQuantityException("InvalidQuantityException: Quantity
not available");
}
}
}

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

String id= sc.nextLine();


String bookTitle= sc.nextLine();
String authorName= sc.nextLine();
float price = sc.nextFloat();
int quantityAvailable= sc.nextInt();
int purchaseQuantity = sc.nextInt();

Book book = new Book(id,bookTitle,authorName,price,quantityAvailable);


try{
int qty = book.purchase(purchaseQuantity);
System.out.println("quantityAvailable: "+ qty);
}
catch(InvalidQuantityException e){
System.out.println(e.getMessage());
}
}
}

__________________________

Handling Driving License Registration Exceptions

Write a program to approve or display suitable exceptions whenever a person tries


to register for a driving license.

Create a class named Main with the following attributes

name - String
userAge - int
mark - int
Minimum eligibility for obtaining a driving license:

Age should be above 18 years old.


A person should pass the road rules eligibility test (with above 80 marks) for a
total mark of 100.
Create two exceptions InvalidAgeForDrivingLicenseException and
InvalidMarkForDrivingLicenseException to handle the above scenarios.

Input format :
The first line consists of a name a String.

The second line consists of age as an integer.

The next line consists of marks obtained as integers.

Output format :
The output should display "Approved" if he meets the criteria or the appropriate
exception.

Refer to the sample output for reference.

Sample test cases :


Input 1 :
Guru
33
95
Output 1 :
Approved
Input 2 :
Smith
2
95
Output 2 :
InvalidAgeForDrivingLicenseException: Age should be more than 18 years old

code:
// You are using Java
import java.util.*;
class InvalidAgeForDrivingLicenseException extends Exception{
public InvalidAgeForDrivingLicenseException(String message){
super(message);
}
}

class InvalidMarkForDrivingLicenseException extends Exception{


public InvalidMarkForDrivingLicenseException(String message){
super(message);
}
}

class Main{
String name ;
int userAge;
int mark;

public Main(String name, int userAge, int mark){


this.name=name;
this.userAge=userAge;
this.mark=mark;

}
public void checkEligiblity()throws
InvalidAgeForDrivingLicenseException,InvalidMarkForDrivingLicenseException{
if(userAge<=0){
throw new InvalidAgeForDrivingLicenseException("Invalid age");
}
else if(userAge<=18){
throw new InvalidAgeForDrivingLicenseException("Age should be more than
18 years old");
}

if(mark<0 || mark>100){
throw new InvalidMarkForDrivingLicenseException("Invalid mark");
}
else if(mark<=80){
throw new InvalidMarkForDrivingLicenseException("Mark should be more
than 80");
}
System.out.println("Approved");
}
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
int userAge = sc.nextInt();
int mark= sc.nextInt();
sc.close();
Main app = new Main(name, userAge,mark);

try{
app.checkEligiblity();
}catch(InvalidAgeForDrivingLicenseException |
InvalidMarkForDrivingLicenseException e){
System.out.println(e.getClass().getSimpleName()+":"+e.getMessage());

}
}
}

_________________________________________

SESSION 3
Problem Statement

Sampad wants to implement a program that takes input for a student's name and
grade, validates the input, and then displays the grade for the given student.

The grade should be an integer value.


The program should validate the grade using the validateGrade() method. The method
should throw an IllegalArgumentException if the grade is less than 0 or greater
than 100.
If the input is invalid due to a non-integer grade, catch the NumberFormatException
and print the built-in exception message.
If the input is invalid due to an out-of-range grade, catch the
IllegalArgumentException and print the built-in exception message.
Catch the exceptions using the multi-catch block.

Assist Sampad to implement this program.

Input format :
The first line of input consists of a string, representing the student's name.

The second line consists of an integer, representing the student's grade.

Output format :
If the input is valid and the grade is within the allowed range, print "Grade for
[student name]: [grade]".

If there is an exception related to invalid input, print "Invalid input: " followed
by the built-in exception message.

If the grade is outside the allowed range, print "Invalid grade: " followed by the
built-in exception message.

Refer to the sample output for formatting specifications.


Code constraints :
length of input string ≤ 10

Sample test cases :


Input 1 :
Alice
85
Output 1 :
Grade for Alice: 85
Input 2 :
Bob
abc
Output 2 :
Invalid input: For input string: "abc"
Input 3 :
Eve
120
Output 3 :
Invalid grade: Invalid grade: 120
Input 4 :
John
-5
Output 4 :
Invalid grade: Invalid grade: -5

code:
import java.util.*;
class StudentGrade{
public static void main(String[]args){
Scanner sc= new Scanner(System.in);
String studentName= sc.nextLine();
String gradeInput = sc.nextLine();
try{
int grade = Integer.parseInt(gradeInput);
validateGrade(grade);
System.out.println("Grade for "+studentName+": "+grade );

}
catch(NumberFormatException e){
System.out.println("Invalid input:"+e.getMessage());

}
catch(IllegalArgumentException e){
System.out.println("Invalid grade:"+e.getMessage());

}
public static void validateGrade(int grade){
if(grade<0 || grade>100){
throw new IllegalArgumentException("Invalid grade: "+grade);
}
}

}
__________________________
mine book question mock 2nd
import java.util.*;
class main{
public static void main(String[]args){
Scanner sc= new Scanner(System.in);
HashMap<String, Double> map = new HashMap<>();
int n= sc.nextInt();
for(int i=1;i<=n;i++){
sc.nextLine();
String title = sc.nextLine();
double price = sc.nextDouble();
map.put(title,price);

}
double threshold = sc.nextDouble();
double totprice=0.00;

System.out.println("Books purchased");

for(Map.Entry<String,Double>e:map.entrySet()){
System.out.printf("Book name :"+e.getKey()+", price %2f\
n",e.getValue());
totprice= totprice+e.getValue();
}
System.out.printf("total bill before discount: %.2f\n",totprice);

if(totprice>threshold){
totprice= totprice*0.75;
System.out.printf("total bill after 25%% discount: %2f\n",totprice);
}
else{
System.out.printf("No discount applied");
}

}
}
__________________________________________________

Problem Statement

Ashok wants to determine if a given integer is an Armstrong number. He requires


your help in implementing a multi-catch block to handle potential issues during
user input or calculation.

Create a method isArmstrongNumber that takes an integer input and returns true if
it is an Armstrong number, and false otherwise. Throw an IllegalArgumentException
if the input is negative.
In the main method, input an integer.
Utilize a multi-catch block to handle the following scenarios:
If the input is negative, catch IllegalArgumentException and print "Error: Input
number must be non-negative"
If the input is not a valid integer, catch inputMismatchException and print "Error:
Input must be a valid integer."
Finally, print the result.

Assist Ashok in this task.

Input format :
The input consists of an integer N.

Output format :
If N is an Armstrong number, print "N is Armstrong number."

If it is not an Armstrong number, print "N is not Armstrong number."

If N < 0, print "Error: Input number must be non-negative"

If N is other than an integer value, print "Error: Input must be a valid integer."

Refer to the sample output for formatting specifications.

Code constraints :
1 ≤ valid input value ≤ 104

Sample test cases :


Input 1 :
153
Output 1 :
153 is Armstrong number.
Input 2 :
745
Output 2 :
745 is not Armstrong number.
Input 3 :
-9
Output 3 :
Error: Input number must be non-negative
Input 4 :
@34
Output 4 :
Error: Input must be a valid integer.

code:
// You are using Java
import java.util.*;

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

try{
int n = sc.nextInt();
if(n<0) throw new IllegalArgumentException("Input number must be non-
negative");
if(isarmstrong(n)){
System.out.println(n+" is Armstrong number.");
}
else{
System.out.println(n+" is not Armstrong number.");
}
}catch(InputMismatchException e){
System.out.println("Error: input must be a valid Integer.");

}
catch(IllegalArgumentException e){
System.out.println("Error: "+e.getMessage());

}
}

public static boolean isarmstrong(int n){


int org = n;
int sum =0;
int nod = String.valueOf(n).length();
while(n!=0){
int digit = n%10;
sum+=Math.pow(digit,nod);
n/=10;
}
return sum==org;
}
}

_____________________________________

4th // You are using Java


import java.util.*;
class main{
public static void main(String []args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.nextLine();
HashMap<String, Double> map = new HashMap<>();
for(int i=0;i<n;i++){
String name = sc.nextLine();
Double salary = sc.nextDouble();
sc.nextLine();

if(salary <=0){
System.out.println("Salary should be greater than 0");
i--;
continue;

map.put(name,salary);
}
double threshold = sc.nextDouble();
boolean found =false;
for(Map.Entry<String,Double>entry : map.entrySet()){
if(entry.getValue()>threshold){
System.out.printf("Employee: %s,Salary: %.2f
%n",entry.getKey(),entry.getValue());
found= true;;
}

}
if(!found){
System.out.println("No employees have a salary greater than the
threshold");
}

}
}

__________________________________

JDBC

SESSION 1

Write an SQL Query to find the first longest CITY names, as well as their
respective lengths (i.e.: number of characters in the name).

Note:

Utilize try/catch and finally block to handle the SQLException.

The table name is case-sensitive and must match the one specified above.

All the records are prepopulated.

Input format :
No console Input

Output format :
The output of the query should include the following headers to be considered:

CITY, LENGTH

SELECT CITY, LENGTH(CITY) as length


from station
order by LENGTH(CITY) DESC limit 1;
_________________________________________________________
Single File Programming Question
Stark is a data analyst working for an e-commerce company. The company's sales data
is stored in a database, which includes information about buyers, products, and
sales transactions. Your task is to identify the buyers who have bought the S8 but
not the iPhone. Note that S8 and iPhone are products listed in the Product table.
Table: product

product_id is the primary key.

Table: sales

This table has no primary key, it can have repeated rows.

product_id is a foreign key to the Product table.

# You are using MYSQL


SELECT DISTINCT s.Buyer_ID
FROM sales s JOIN product p on s.product_id = p.product_id
WHERE p.product_name = 'S8';

___________

Write an SQL query to display the product_name, year and price associated with each
sale_id in the sales table.

Table: sales

Table: product

Note:

The table name is case-sensitive and must match the one specified above.

All the records are prepopulated.

Input format :
No Console Input

# You are using MYSQL


SELECT p.product_name, year, s.price
from product p, sales s
where p.product_id = s.product_id;
____________________________________-
Write a SQL query to display a list of employee names from the employee table in
alphabetical order.

# You are using MYSQL


SELECT name
from employee
Order by name ASC;

___________________________

Write a SQL Query to display the count of the number of product sales on each date
from the orders table.

# You are using MYSQL


select sell_date as date, count(product) as no_of_products
from orders
group by sell_date;

___________________________________________________________________________________
_______________________________

SESSION 3
:

Loan data Management

You are tasked with developing a Java application to manage loan data using JDBC
and MySQL. The application should allow users to perform CRUD (Create, Read,
Update, Delete) operations on the loan data stored in the database.

Table Name: loans

1. Insert loan details.

2. Update loan details.

3. Delete loan details.

4. Show all loan details.

NOTE:
Utilize try/catch and finally block to handle the SQLException.

The table name is case-sensitive and must match the one specified above.

The Table is created and some tuples have been already inserted into the table.

id range is between 1001 to 1005.

Input format :
The input consists of a number representing the CRUD operation like

1 - Inserting (the input should be of all attributes)

2 - Update (update the interestrate based on loanId)

3 - Delete

4 - Show all details

Output format :
The output should perform all the crud operations based on Menu driven.

Sample test cases :


Input 1 :
1
1006
Frank Taylor
80000.00
4.1
12
Output 1 :
Loan added successfully.
Loan ID: 1001, Borrower Name: Alice Johnson, Loan Amount: 50000.0, Interest Rate:
3.5%, Loan Term: 5 years
Loan ID: 1002, Borrower Name: Bob Smith, Loan Amount: 75000.0, Interest Rate: 4.0%,
Loan Term: 10 years
Loan ID: 1003, Borrower Name: Catherine Brown, Loan Amount: 120000.0, Interest
Rate: 3.75%, Loan Term: 15 years
Loan ID: 1004, Borrower Name: David Wilson, Loan Amount: 90000.0, Interest Rate:
4.25%, Loan Term: 20 years
Loan ID: 1005, Borrower Name: Evelyn Clark, Loan Amount: 65000.0, Interest Rate:
3.9%, Loan Term: 7 years
Loan ID: 1006, Borrower Name: Frank Taylor, Loan Amount: 80000.0, Interest Rate:
4.1%, Loan Term: 12 years
Input 2 :
2
1001
4.1
Output 2 :
Loan updated successfully.
Loan ID: 1001, Borrower Name: Alice Johnson, Loan Amount: 50000.0, Interest Rate:
4.1%, Loan Term: 5 years
Loan ID: 1002, Borrower Name: Bob Smith, Loan Amount: 75000.0, Interest Rate: 4.0%,
Loan Term: 10 years
Loan ID: 1003, Borrower Name: Catherine Brown, Loan Amount: 120000.0, Interest
Rate: 3.75%, Loan Term: 15 years
Loan ID: 1004, Borrower Name: David Wilson, Loan Amount: 90000.0, Interest Rate:
4.25%, Loan Term: 20 years
Loan ID: 1005, Borrower Name: Evelyn Clark, Loan Amount: 65000.0, Interest Rate:
3.9%, Loan Term: 7 years
Input 3 :
3
1001
Output 3 :
Loan deleted successfully.
Loan ID: 1002, Borrower Name: Bob Smith, Loan Amount: 75000.0, Interest Rate: 4.0%,
Loan Term: 10 years
Loan ID: 1003, Borrower Name: Catherine Brown, Loan Amount: 120000.0, Interest
Rate: 3.75%, Loan Term: 15 years
Loan ID: 1004, Borrower Name: David Wilson, Loan Amount: 90000.0, Interest Rate:
4.25%, Loan Term: 20 years
Loan ID: 1005, Borrower Name: Evelyn Clark, Loan Amount: 65000.0, Interest Rate:
3.9%, Loan Term: 7 years
Input 4 :
4
Output 4 :
Loan ID: 1001, Borrower Name: Alice Johnson, Loan Amount: 50000.0, Interest Rate:
3.5%, Loan Term: 5 years
Loan ID: 1002, Borrower Name: Bob Smith, Loan Amount: 75000.0, Interest Rate: 4.0%,
Loan Term: 10 years
Loan ID: 1003, Borrower Name: Catherine Brown, Loan Amount: 120000.0, Interest
Rate: 3.75%, Loan Term: 15 years
Loan ID: 1004, Borrower Name: David Wilson, Loan Amount: 90000.0, Interest Rate:
4.25%, Loan Term: 20 years
Loan ID: 1005, Borrower Name: Evelyn Clark, Loan Amount: 65000.0, Interest Rate:
3.9%, Loan Term: 7 years

code:

// You are using Java


import java.util.*;
import java.sql.*;

class Main{
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
Connection con= null;
PreparedStatement ps = null;
Statement st = null;
ResultSet rs =null;
String url = "jdbc:mysql://localhost/ri_db";
String user = "test";
String pass= "test123";

try{
con= DriverManager.getConnection(url,user,pass);
int choice = sc.nextInt();
switch(choice){
case 1:{

int id = sc.nextInt();
sc.nextLine();
String name= sc.nextLine();
double amt = sc.nextDouble();
double interestRate = sc.nextDouble();
int term = sc.nextInt();
ps= con.prepareStatement("INSERT INTO loans
VALUES(?,?,?,?,?)");
ps.setInt(1,id);
ps.setString(2,name);
ps.setDouble(3,amt);
ps.setDouble(4,interestRate);
ps.setInt(5,term);

ps.executeUpdate();

System.out.println("loan added successfully.");

st= con.createStatement();
rs= st.executeQuery("Select * FROM loans");

while(rs.next()){
System.out.println("Loan ID: "+rs.getInt(1)+", Borrower
Name: "+rs.getString(2)+", Loan Amount: "+rs.getDouble(3)+", Interest Rate:
"+rs.getDouble(4)+"%, Loan Term: "+rs.getInt(5)+"years");
}

}
break;
case 2:{

int loanid = sc.nextInt();


double interestRate = sc.nextDouble();
ps= con.prepareStatement("UPDATE loans SET interestRate=? WHERE
loanid=?");

ps.setDouble(1,interestRate);
ps.setInt(2,loanid);
int flag = ps.executeUpdate();
if(flag!=0) System.out.println("Loan updated successfully.");
else{
System.out.println("Loan ID not found");
}

st= con.createStatement();
rs= st.executeQuery("Select * FROM loans");

while(rs.next()){
System.out.println("Loan ID: "+rs.getInt(1)+", Borrower
Name: "+rs.getString(2)+", Loan Amount: "+rs.getDouble(3)+", Interest Rate:
"+rs.getDouble(4)+"%, Loan Term: "+rs.getInt(5)+"years");
}

}
break;
case 3:{

int loanid = sc.nextInt();


ps= con.prepareStatement("DELETE FROM loans WHERE loanid=?");
ps.setInt(1,loanid);
int flag = ps.executeUpdate();
if(flag!=0) System.out.println("loan deleted successfully.");
else{
System.out.println("loan ID not found");
}

st= con.createStatement();
rs= st.executeQuery("Select * FROM loans");

while(rs.next()){
System.out.println("Loan ID: "+rs.getInt(1)+", Borrower
Name: "+rs.getString(2)+", Loan Amount: "+rs.getDouble(3)+", Interest Rate:
"+rs.getDouble(4)+"%, Loan Term: "+rs.getInt(5)+"years");
}

}
break;
case 4:{

st= con.createStatement();
rs= st.executeQuery("Select * FROM loans");

while(rs.next()){
System.out.println("Loan ID: "+rs.getInt(1)+", Borrower
Name: "+rs.getString(2)+", Loan Amount: "+rs.getDouble(3)+", Interest Rate:
"+rs.getDouble(4)+"%, Loan Term: "+rs.getInt(5)+"years");
}

}
break;

}
}catch(SQLException e){
e.printStackTrace();

}finally{
try{
con.close();
}catch(SQLException e){
e.printStackTrace();
}
}
}
}

++++++++++++

Write a Java (JDBC) program to connect to a MySQL database and print all the
employee details who have salaries greater than or equal to a given input.

Use the below Database Credentials


Table Name: employee

Note:

Utilize try/catch and finally blocks to handle SQLException.


The table name is case-sensitive and must match the one specified above.
All records in the table are prepopulated.
Input format :
The input consists of a double value that represents the salary.
Output format :
The output prints the respective employee details.
If no employee meets the criteria, print "No records found for the given salary
threshold."

Refer to the sample output for formatting specifications.

Sample test cases :


Input 1 :
25000
Output 1 :
Database connected successfully.
1 Alice 40000.0
2 Bob 35000.0
4 Darvin 28000.0
5 Embella 25000.0
Connection closed successfully.
Input 2 :
55000
Output 2 :
Database connected successfully.
No records found for the given salary threshold.
Connection closed successfully.
Note :
The program will be evaluated only after the “Submit Code” is clicked.
Extra spaces and new line characters in the program output will result in the
failure of the test case.

code:
// You are using Java
import java.util.*;
import java.sql.*;

class Main{
public static void main(String[]args){

Scanner sc= new Scanner(System.in);


Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
String user = "test";
String password = "test123";
String url = "jdbc:mysql://localhost/ri_db";
try{
con = DriverManager.getConnection(url,user,password);
System.out.println("Database connected successfully.");
double salary = sc.nextDouble();
ps = con.prepareStatement("select * from employee where salary
>= ?");
ps.setDouble(1,salary);
rs = ps.executeQuery();
int count =0;
while(rs.next()){
count++;
System.out.println(rs.getInt(1)+" "+rs.getString(2)+"
"+rs.getDouble(3));
}
if(count==0 ) System.out.println("No records found for the
given salary threshold.");
con.close();
//System.out.println("Connection closed successfully");

}
catch(SQLException e){
System.out.println(e);
}
finally{
try{
if(rs!=null) rs.close();
if(ps!=null) ps.close();
if(rs!=null) con.close();
System.out.println("Connection closed successfully.");
}catch(SQLException e){
System.out.println(e);
}
}

}
}

_______________________

Write a Java (JDBC) program to insert student details into a table and display the
inserted details and the total number of rows affected.

Use the below Database Credentials:


TableName: student

Note:

Utilize try/catch and finally block to handle the SQLException.

The table name is case-sensitive and must match the one specified above.

Input format :
The number of students (integer) on the first line.

For each student:

Roll number (integer)


Name (string)
Marks of three subjects (three integers, one for each line)
Output format :
"Database connected successfully."

For each student inserted:

"Roll No: [roll number]"


"Name: [name]"
"Marks1: [marks of subject 1]"
"Marks2: [marks of subject 2]"
"Marks3: [marks of subject 3]"
Total number of rows inserted (an integer).

"Connection closed successfully."

Sample test cases :


Input 1 :
2
1234567
Babu
37
89
98
1001
Moni
90
87
44
Output 1 :
Database connected successfully.
Roll No: 1234567
Name: Babu
Marks1: 37
Marks2: 89
Marks3: 98
Roll No: 1001
Name: Moni
Marks1: 90
Marks2: 87
Marks3: 44
2
Connection closed successfully.
Input 2 :
3
7840534
Babu
37
89
98
6849906
Moni
90
87
44
179596
Mona
60
47
94
Output 2 :
Database connected successfully.
Roll No: 7840534
Name: Babu
Marks1: 37
Marks2: 89
Marks3: 98
Roll No: 6849906
Name: Moni
Marks1: 90
Marks2: 87
Marks3: 44
Roll No: 179596
Name: Mona
Marks1: 60
Marks2: 47
Marks3: 94
3
Connection closed successfully.

code::
// You are using Java
import java.util.*;
import java.sql.*;

class Main{
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
Connection con = null;
PreparedStatement ps =null;
Statement st =null;
ResultSet rs =null;
int x=0;
String user ="test";
String password = "test123";
String url = "jdbc:mysql://localhost/ri_db";

try{
con= DriverManager.getConnection(url,user,password);
System.out.println("Database connected successfully.");
ps = con.prepareStatement("Insert into student VALUES(?,?,?,?,?)");
int n= sc.nextInt();
for(int i=0;i<n;i++){
int roll = sc.nextInt();
sc.nextLine();
String name = sc.nextLine();
int m1= sc.nextInt();
int m2= sc.nextInt();
int m3= sc.nextInt();

ps.setInt(1,roll);
ps.setString(2,name);
ps.setInt(3,m1);
ps.setInt(4,m2);
ps.setInt(5,m3);
ps.executeUpdate();
}

st= con.createStatement();
rs= st.executeQuery("SELECT * FROM student");
while(rs.next()){
x++;
System.out.println("Roll No: "+rs.getInt(1)+"\nName:
"+rs.getString(2)+"\nMarks1: "+rs.getInt(3)+""+"\nMarks2: "+rs.getInt(4)+""+"\
nMarks3: "+rs.getInt(5)+"\n");

}
System.out.println(x);

}catch(SQLException e){
System.out.println(e);
}
finally{
try{
ps.close();
con.close();
System.out.println("Connection closed successfully.");
}
catch(SQLException e){
System.out.println(e);
}
}

}
}

_____________________________________________

session 2:

Write a Java (JDBC) program to connect with the MySQL database, insert the given
data in the table, and display the employee details.
Use the below Database Credentials:

Table Name: office

Note:

Utilize try/catch and finally block to handle the SQLException.

The table name is case-sensitive and must match the one specified above.

Input format :
The first line of the input consists of a number of employees in the first line.

EID, ENAME, ESALARY in the next consecutive lines.

Refer to the sample input.

Output format :
Displays office table details.

Refer to the sample output for reference.

Sample test cases :


Input 1 :
3
101
Ashwin
10000
102
Kumar
20000
103
amore
30000
Output 1 :
Database connected successfully.
101 Ashwin 10000
102 Kumar 20000
103 amore 30000
Connection closed successfully.

code:
import java.util.*;
import java.sql.*;
class Main{
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
ResultSet rs = null;
Connection con = null;
PreparedStatement ps =null;
Statement st =null;
String Username = "test";
String Password = "test123";
String url = "jdbc:mysql://localhost/ri_db";

try{
con = DriverManager.getConnection(url,Username,Password);
System.out.println("Database connected successfully.");
ps= con.prepareStatement("INSERT INTO office VALUES(?,?,?)");

int n=sc.nextInt();
for(int i=0;i<n;i++){
int id =sc.nextInt();
sc.nextLine();
String name = sc.nextLine();
int salary = sc.nextInt();
ps.setInt(1,id);
ps.setString(2,name);
ps.setInt(3,salary);
ps.executeUpdate();
}
st=con.createStatement();
rs= st.executeQuery("SELECT * FROM office");

while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2)+"
"+rs.getInt(3));
}

}catch(SQLException e){
System.out.println(e);
}
finally{
try{
con.close();
st.close();
rs.close();
System.out.println("Connection closed successfully.");
}catch(SQLException e)
{
System.out.println(e);
}
}
}
}

_______________

Write a JDBC Program to get the 2nd row from the "contacts" table using ResultSet
interface methods.

Table Name: contacts


Note: All records are prepopulated.

Input format :
No console input

Output format :
The output should display the second row from the table.

Sample test cases :


Input 1 :
Output 1 :
ID: 2, Name: Priya Sharma, Email: [email protected], Phone Number: 9876543211,
City: Mumbai

// You are using Java


import java.sql.*;
class Main{
public static void main(String[]args){
Connection con = null;
Statement st =null;
ResultSet rs = null;
String id = "test";
String password ="test123";
String url ="jdbc:mysql://localhost/ri_db";

try{
con= DriverManager.getConnection(url,id,password);
st = con.createStatement();
String sql = "SELECT * FROM contacts";
rs = st.executeQuery(sql);
rs.next();
rs.next();
System.out.println("ID: "+rs.getInt(1)+", Name:
"+rs.getString(2)+",Email: "+rs.getString(3)+", Phone Number: "+rs.getString(4)+",
City: "+rs.getString(5));

}catch(SQLException e){
e.printStackTrace();
}
finally{
try{
con.close();

}catch(SQLException e){
e.printStackTrace();
}
}

}
}

______________

Write a JDBC program to retrieve all the data from the contacts table.

Table Name: contacts


Note: All Records are Prepopulated.

Input format :
No console input

Output format :
The output should display the contact details as shown in the sample output.

Sample test cases :


Input 1 :
Output 1 :
ID: 1, Name: Ravi Kumar, Email: [email protected], Phone Number: 9876543210, City:
Delhi
ID: 2, Name: Priya Sharma, Email: [email protected], Phone Number: 9876543211,
City: Mumbai
ID: 3, Name: Amit Patel, Email: [email protected], Phone Number: 9876543212, City:
Bangalore
ID: 4, Name: Neha Gupta, Email: [email protected], Phone Number: 9876543213, City:
Kolkata
ID: 5, Name: Sandeep Singh, Email: [email protected], Phone Number: 9876543214,
City: Chennai

import java.sql.*;
class Main{
public static void main(String[] args){
Connection com = null;
Statement st = null;
ResultSet rs =null;
String url = "jdbc:mysql://localhost/ri_db";
String username= "test";
String password ="test123";

try{
com = DriverManager.getConnection(url,username,password);
st =com.createStatement();
String sql = "SELECT * FROM contacts";
rs= st.executeQuery(sql);

while(rs.next()){
System.out.println("ID: "+rs.getInt(1)+", Name:
"+rs.getString(2)+", Email: "+rs.getString(3)+", Phone Number: "+rs.getString(4)+",
City: "+rs.getString(5));
}
}catch(SQLException e){
e.printStackTrace();
}
finally{
try{
st.close();
com.close();
}catch(SQLException e){
e.printStackTrace();
}
}
}

______________________________________

session 10:

Election
ee Management

You are tasked with developing a Java application to manage election committee data
using JDBC and MySQL. The application should allow users to perform CRUD (Create,
Read, Update, Delete) operations on the election committee data stored in the
database.

Table Name: election_committee

1. Insert election committee details.

2. Update election committee details.

3. Delete election committee details.

4. Show election committee details.

NOTE:

Utilize try/catch and finally block to handle the SQLException.

The table name is case-sensitive and must match the one specified above.

The Table is created and some tuples have been already inserted into the table.

id range is between 1001 to 1005.

Input format :
The input consists of a number representing the CRUD operation like

1 - Inserting (the input should be of all attributes)

2 - Update (update the role based on committee_id)

3 - Delete

4 - Show all details


Output format :
The output should perform all the crud operations based on Menu driven.

Sample test cases :


Input 1 :
1
1006
Legal Advisor
Frank Martinez
State
2024-06-01 to 2024-12-31
Output 1 :
Committee member added successfully.
ID: 1001, Role: Chairperson, Member Name: Alice Johnson, Committee Type: National,
Term Period: 2024-01-01 to 2024-12-31
ID: 1002, Role: Secretary, Member Name: Bob Smith, Committee Type: Local, Term
Period: 2024-02-01 to 2024-12-31
ID: 1003, Role: Treasurer, Member Name: Carol Davis, Committee Type: State, Term
Period: 2024-03-01 to 2024-12-31
ID: 1004, Role: Campaign Manager, Member Name: David Wilson, Committee Type:
National, Term Period: 2024-04-01 to 2024-11-30
ID: 1005, Role: Election Coordinator, Member Name: Eve Thompson, Committee Type:
Local, Term Period: 2024-05-01 to 2024-10-31
ID: 1006, Role: Legal Advisor, Member Name: Frank Martinez, Committee Type: State,
Term Period: 2024-06-01 to 2024-12-31
Input 2 :
2
1001
Legal Advisor
Output 2 :
Committee member updated successfully.
ID: 1001, Role: Legal Advisor, Member Name: Alice Johnson, Committee Type:
National, Term Period: 2024-01-01 to 2024-12-31
ID: 1002, Role: Secretary, Member Name: Bob Smith, Committee Type: Local, Term
Period: 2024-02-01 to 2024-12-31
ID: 1003, Role: Treasurer, Member Name: Carol Davis, Committee Type: State, Term
Period: 2024-03-01 to 2024-12-31
ID: 1004, Role: Campaign Manager, Member Name: David Wilson, Committee Type:
National, Term Period: 2024-04-01 to 2024-11-30
ID: 1005, Role: Election Coordinator, Member Name: Eve Thompson, Committee Type:
Local, Term Period: 2024-05-01 to 2024-10-31
Input 3 :
3
1001
Output 3 :
Committee member deleted successfully.
ID: 1002, Role: Secretary, Member Name: Bob Smith, Committee Type: Local, Term
Period: 2024-02-01 to 2024-12-31
ID: 1003, Role: Treasurer, Member Name: Carol Davis, Committee Type: State, Term
Period: 2024-03-01 to 2024-12-31
ID: 1004, Role: Campaign Manager, Member Name: David Wilson, Committee Type:
National, Term Period: 2024-04-01 to 2024-11-30
ID: 1005, Role: Election Coordinator, Member Name: Eve Thompson, Committee Type:
Local, Term Period: 2024-05-01 to 2024-10-31
Input 4 :
4
Output 4 :
ID: 1001, Role: Chairperson, Member Name: Alice Johnson, Committee Type: National,
Term Period: 2024-01-01 to 2024-12-31
ID: 1002, Role: Secretary, Member Name: Bob Smith, Committee Type: Local, Term
Period: 2024-02-01 to 2024-12-31
ID: 1003, Role: Treasurer, Member Name: Carol Davis, Committee Type: State, Term
Period: 2024-03-01 to 2024-12-31
ID: 1004, Role: Campaign Manager, Member Name: David Wilson, Committee Type:
National, Term Period: 2024-04-01 to 2024-11-30
ID: 1005, Role: Election Coordinator, Member Name: Eve Thompson, Committee Type:
Local, Term Period: 2024-05-01 to 2024-10-31

code:

// You are using Java


import java.util.*;
import java.sql.*;

class ElectionComitteeManagement{
public static void main(String[]args){
Scanner sc= new Scanner(System.in);
Connection con = null;
PreparedStatement ps = null;
Statement st = null;
ResultSet rs = null;

String url = "jdbc:mysql://localhost/ri_db";


String pwd ="test123";
String user= "test";

try{

con = DriverManager.getConnection(url,user,pwd);
int choice = sc.nextInt();

switch(choice){
case 1:{
int id = sc.nextInt();
sc.nextLine();
String role=sc.nextLine();
String memberName=sc.nextLine();
String committeType=sc.nextLine();
String term_period= sc.nextLine();
ps =con.prepareStatement("INSERT INTO election_committee
VALUES(?,?,?,?,?)");
ps.setInt(1,id);
ps.setString(2,role);
ps.setString(3,memberName);
ps.setString(4,committeType);
ps.setString(5,term_period);
ps.executeUpdate();
System.out.println("Committee member added successfully.");
st = con.createStatement();
rs= st.executeQuery("SELECT * from election_committee");
while(rs.next()){
System.out.println("ID: "+rs.getInt(1)+", Role:
"+rs.getString(2)+", Member Name: "+rs.getString(3)+", committee Type:
"+rs.getString(4)+", Term Period: "+rs.getString(5));
}
}
break;

case 2:{
int id = sc.nextInt();
sc.nextLine();
String role=sc.nextLine();

ps =con.prepareStatement("UPDATE election_committee set role=?


where committee_id=?");
ps.setString(1,role);

ps.setInt(2,id);

ps.executeUpdate();
System.out.println("Committee member updated successfully.");
st = con.createStatement();
rs= st.executeQuery("SELECT * from election_committee");
while(rs.next()){
System.out.println("ID: "+rs.getInt(1)+", Role:
"+rs.getString(2)+", Member Name: "+rs.getString(3)+", committee Type:
"+rs.getString(4)+", Term Period: "+rs.getString(5));
}
}
break;

case 3:{
int id = sc.nextInt();

ps =con.prepareStatement("DELETE FROM election_committee where


committee_id = ?");

ps.setInt(1,id);

ps.executeUpdate();
System.out.println("Committee member deleted successfully.");
st = con.createStatement();
rs= st.executeQuery("SELECT * from election_committee");
while(rs.next()){
System.out.println("ID: "+rs.getInt(1)+", Role:
"+rs.getString(2)+", Member Name: "+rs.getString(3)+", committee Type:
"+rs.getString(4)+", Term Period: "+rs.getString(5));
}
}
break;

case 4:{
st = con.createStatement();
rs= st.executeQuery("SELECT * from election_committee");
while(rs.next())
{
System.out.println("ID: "+rs.getInt(1)+", Role:
"+rs.getString(2)+", Member Name: "+rs.getString(3)+", committee Type:
"+rs.getString(4)+", Term Period: "+rs.getString(5));
}

}
break;
default:
System.out.println("Invalid choice");

}catch(SQLException e){
e.printStackTrace();
}
finally{
try{
if(con!=null) con.close();
if(st!=null) sc.close();
if(rs!=null) rs.close();

}catch(SQLException e){
e.printStackTrace();
}
}
}
}

sample ans __

// You are using Java


import java.util.*;
class Appliance{
private int id;
private String name;
private boolean rented;

private static int cnt;

static{
cnt=301;
}

Appliance(){

Appliance(String name){
id=cnt;
cnt++;
this.name=name;
rented=false;
}
public void setID(int id){
this.id=id;
}

public void setName(String name){


this.name=name;
}

public void setRented(boolean flag){


rented=flag;
}

public int getID(){


return id;
}

public String getName(){


return name;
}

public boolean getRented(){


return rented;
}

public String toString(){


return "Appliance{id="+id+", name='"+name+"', rented="+rented+"}";
}

public boolean equals(Object obj){


Appliance ap = (Appliance)obj;
if(this.id == ap.id) return true;
return false;
}
}

class ApplianceRentalSystem{
private ArrayList<Appliance> list;

public ApplianceRentalSystem(){
list = new ArrayList<>();
}

public void addAppliance(String name){


Appliance ap = new Appliance(name);
list.add(ap);
}

public void rentAppliance(int id){


Appliance ap = new Appliance();
ap.setID(id);
int ix = list.indexOf(ap);
if(ix == -1){
System.out.println("Appliance with ID "+id+" not found.");
}
else{
list.get(ix).setRented(true);
System.out.println("Appliance with ID "+id+" is rented");
}
}
public void removeAppliance(int id){
Appliance ap = new Appliance();
ap.setID(id);
int ix = list.indexOf(ap);
if(ix == -1){
System.out.println("Appliance with ID "+id+" not found.");
}
else{
list.remove(ix);
System.out.println("Appliance successfully removed.");
}
}

public int countNonRentedAppliances(){


int x=0;
for(Appliance ap : list){
if(ap.getRented())
x++;
}
return x;
}

public void displayAppliances(){


for(Appliance ap : list){
System.out.println(ap);
}
}
}

class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.nextLine();

ApplianceRentalSystem ap = new ApplianceRentalSystem();

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


String s = sc.nextLine();
ap.addAppliance(s);
}

System.out.println("Appliances in the inventory");


ap.displayAppliances();

int rentID = sc.nextInt();


ap.rentAppliance(rentID);

int removeID = sc.nextInt();


ap.removeAppliance(removeID);

System.out.println("Updated Inventory");
ap.displayAppliances();

System.out.print("Total non-rented Appliances:


"+ap.countNonRentedAppliances());
}
}
__________________________________________________________________

JDBC CRUD

Election Committee Management

You are tasked with developing a Java application to manage election committee data
using JDBC and MySQL. The application should allow users to perform CRUD (Create,
Read, Update, Delete) operations on the election committee data stored in the
database.

Table Name: election_committee

1. Insert election committee details.

2. Update election committee details.

3. Delete election committee details.

4. Show election committee details.

NOTE:

Utilize try/catch and finally block to handle the SQLException.

The table name is case-sensitive and must match the one specified above.

The Table is created and some tuples have been already inserted into the table.

id range is between 1001 to 1005.

Input format :
The input consists of a number representing the CRUD operation like

1 - Inserting (the input should be of all attributes)

2 - Update (update the role based on committee_id)

3 - Delete

4 - Show all details

Output format :
The output should perform all the crud operations based on Menu driven.

Sample test cases :


Input 1 :
1
1006
Legal Advisor
Frank Martinez
State
2024-06-01 to 2024-12-31
Output 1 :
Committee member added successfully.
ID: 1001, Role: Chairperson, Member Name: Alice Johnson, Committee Type: National,
Term Period: 2024-01-01 to 2024-12-31
ID: 1002, Role: Secretary, Member Name: Bob Smith, Committee Type: Local, Term
Period: 2024-02-01 to 2024-12-31
ID: 1003, Role: Treasurer, Member Name: Carol Davis, Committee Type: State, Term
Period: 2024-03-01 to 2024-12-31
ID: 1004, Role: Campaign Manager, Member Name: David Wilson, Committee Type:
National, Term Period: 2024-04-01 to 2024-11-30
ID: 1005, Role: Election Coordinator, Member Name: Eve Thompson, Committee Type:
Local, Term Period: 2024-05-01 to 2024-10-31
ID: 1006, Role: Legal Advisor, Member Name: Frank Martinez, Committee Type: State,
Term Period: 2024-06-01 to 2024-12-31
Input 2 :
2
1001
Legal Advisor
Output 2 :
Committee member updated successfully.
ID: 1001, Role: Legal Advisor, Member Name: Alice Johnson, Committee Type:
National, Term Period: 2024-01-01 to 2024-12-31
ID: 1002, Role: Secretary, Member Name: Bob Smith, Committee Type: Local, Term
Period: 2024-02-01 to 2024-12-31
ID: 1003, Role: Treasurer, Member Name: Carol Davis, Committee Type: State, Term
Period: 2024-03-01 to 2024-12-31
ID: 1004, Role: Campaign Manager, Member Name: David Wilson, Committee Type:
National, Term Period: 2024-04-01 to 2024-11-30
ID: 1005, Role: Election Coordinator, Member Name: Eve Thompson, Committee Type:
Local, Term Period: 2024-05-01 to 2024-10-31
Input 3 :
3
1001
Output 3 :
Committee member deleted successfully.
ID: 1002, Role: Secretary, Member Name: Bob Smith, Committee Type: Local, Term
Period: 2024-02-01 to 2024-12-31
ID: 1003, Role: Treasurer, Member Name: Carol Davis, Committee Type: State, Term
Period: 2024-03-01 to 2024-12-31
ID: 1004, Role: Campaign Manager, Member Name: David Wilson, Committee Type:
National, Term Period: 2024-04-01 to 2024-11-30
ID: 1005, Role: Election Coordinator, Member Name: Eve Thompson, Committee Type:
Local, Term Period: 2024-05-01 to 2024-10-31
Input 4 :
4
Output 4 :
ID: 1001, Role: Chairperson, Member Name: Alice Johnson, Committee Type: National,
Term Period: 2024-01-01 to 2024-12-31
ID: 1002, Role: Secretary, Member Name: Bob Smith, Committee Type: Local, Term
Period: 2024-02-01 to 2024-12-31
ID: 1003, Role: Treasurer, Member Name: Carol Davis, Committee Type: State, Term
Period: 2024-03-01 to 2024-12-31
ID: 1004, Role: Campaign Manager, Member Name: David Wilson, Committee Type:
National, Term Period: 2024-04-01 to 2024-11-30
ID: 1005, Role: Election Coordinator, Member Name: Eve Thompson, Committee Type:
Local, Term Period: 2024-05-01 to 2024-10-31
// You are using Java
import java.util.*;
import java.sql.*;

class ElectionComitteeManagement{
public static void main(String[]args){
Scanner sc= new Scanner(System.in);
Connection con = null;
PreparedStatement ps = null;
Statement st = null;
ResultSet rs = null;

String url = "jdbc:mysql://localhost/ri_db";


String pwd ="test123";
String user= "test";

try{

con = DriverManager.getConnection(url,user,pwd);
int choice = sc.nextInt();

switch(choice){
case 1:{
int id = sc.nextInt();
sc.nextLine();
String role=sc.nextLine();
String memberName=sc.nextLine();
String committeType=sc.nextLine();
String term_period= sc.nextLine();
ps =con.prepareStatement("INSERT INTO election_committee
VALUES(?,?,?,?,?)");
ps.setInt(1,id);
ps.setString(2,role);
ps.setString(3,memberName);
ps.setString(4,committeType);
ps.setString(5,term_period);
ps.executeUpdate();
System.out.println("Committee member added successfully.");
st = con.createStatement();
rs= st.executeQuery("SELECT * from election_committee");
while(rs.next()){
System.out.println("ID: "+rs.getInt(1)+", Role:
"+rs.getString(2)+", Member Name: "+rs.getString(3)+", committee Type:
"+rs.getString(4)+", Term Period: "+rs.getString(5));
}
}
break;

case 2:{
int id = sc.nextInt();
sc.nextLine();
String role=sc.nextLine();

ps =con.prepareStatement("UPDATE election_committee set role=?


where committee_id=?");
ps.setString(1,role);
ps.setInt(2,id);

ps.executeUpdate();
System.out.println("Committee member updated successfully.");
st = con.createStatement();
rs= st.executeQuery("SELECT * from election_committee");
while(rs.next()){
System.out.println("ID: "+rs.getInt(1)+", Role:
"+rs.getString(2)+", Member Name: "+rs.getString(3)+", committee Type:
"+rs.getString(4)+", Term Period: "+rs.getString(5));
}
}
break;

case 3:{
int id = sc.nextInt();

ps =con.prepareStatement("DELETE FROM election_committee where


committee_id = ?");

ps.setInt(1,id);

ps.executeUpdate();
System.out.println("Committee member deleted successfully.");
st = con.createStatement();
rs= st.executeQuery("SELECT * from election_committee");
while(rs.next()){
System.out.println("ID: "+rs.getInt(1)+", Role:
"+rs.getString(2)+", Member Name: "+rs.getString(3)+", committee Type:
"+rs.getString(4)+", Term Period: "+rs.getString(5));
}
}
break;

case 4:{
st = con.createStatement();
rs= st.executeQuery("SELECT * from election_committee");
while(rs.next())
{
System.out.println("ID: "+rs.getInt(1)+", Role:
"+rs.getString(2)+", Member Name: "+rs.getString(3)+", committee Type:
"+rs.getString(4)+", Term Period: "+rs.getString(5));

}
break;
default:
System.out.println("Invalid choice");

}
}catch(SQLException e){
e.printStackTrace();
}
finally{
try{
if(con!=null) con.close();
if(st!=null) sc.close();
if(rs!=null) rs.close();

}catch(SQLException e){
e.printStackTrace();
}
}
}
}

__________________________________

subscriber data Management

You are tasked with developing a Java application to manage subscriber data using
JDBC and MySQL. The application should allow users to perform CRUD (Create, Read,
Update, Delete) operations on the subscriber data stored in the database.

Table Name: subscriber

1. Insert subscriber details.

2. Update subscriber details.

3. Delete subscriber details.

4. Show all subscriber details.

NOTE:

Utilize try/catch and finally block to handle the SQLException.

The table name is case-sensitive and must match the one specified above.

The Table is created and some tuples have been already inserted into the table.

id range is between 1001 to 1005.

Input format :
The input consists of a number representing the CRUD operation like

1 - Inserting (the input should be of all attributes)


2 - Update (update the email based on subscriber_id)

3 - Delete

4 - Show all details

Output format :
The output should perform all the crud operations based on Menu driven.

Sample test cases :


Input 1 :
1
1006
Michael Wilson
2024-06-20
2024-12-20
[email protected]
Output 1 :
Subscriber added successfully.
ID: 1001, Name: John Doe, Start Date: 2024-01-15, End Date: 2024-12-15, Email:
[email protected]
ID: 1002, Name: Jane Smith, Start Date: 2024-02-01, End Date: 2024-11-01, Email:
[email protected]
ID: 1003, Name: Alice Johnson, Start Date: 2024-03-10, End Date: 2024-09-10, Email:
[email protected]
ID: 1004, Name: Bob Brown, Start Date: 2024-04-22, End Date: 2024-10-22, Email:
[email protected]
ID: 1005, Name: Emily Davis, Start Date: 2024-05-15, End Date: 2024-11-15, Email:
[email protected]
ID: 1006, Name: Michael Wilson, Start Date: 2024-06-20, End Date: 2024-12-20,
Email: [email protected]
Input 2 :
2
1001
[email protected]
Output 2 :
Subscriber updated successfully.
ID: 1001, Name: John Doe, Start Date: 2024-01-15, End Date: 2024-12-15, Email:
[email protected]
ID: 1002, Name: Jane Smith, Start Date: 2024-02-01, End Date: 2024-11-01, Email:
[email protected]
ID: 1003, Name: Alice Johnson, Start Date: 2024-03-10, End Date: 2024-09-10, Email:
[email protected]
ID: 1004, Name: Bob Brown, Start Date: 2024-04-22, End Date: 2024-10-22, Email:
[email protected]
ID: 1005, Name: Emily Davis, Start Date: 2024-05-15, End Date: 2024-11-15, Email:
[email protected]
Input 3 :
3
1001
Output 3 :
Subscriber deleted successfully.
ID: 1002, Name: Jane Smith, Start Date: 2024-02-01, End Date: 2024-11-01, Email:
[email protected]
ID: 1003, Name: Alice Johnson, Start Date: 2024-03-10, End Date: 2024-09-10, Email:
[email protected]
ID: 1004, Name: Bob Brown, Start Date: 2024-04-22, End Date: 2024-10-22, Email:
[email protected]
ID: 1005, Name: Emily Davis, Start Date: 2024-05-15, End Date: 2024-11-15, Email:
[email protected]
Input 4 :
4
Output 4 :
ID: 1001, Name: John Doe, Start Date: 2024-01-15, End Date: 2024-12-15, Email:
[email protected]
ID: 1002, Name: Jane Smith, Start Date: 2024-02-01, End Date: 2024-11-01, Email:
[email protected]
ID: 1003, Name: Alice Johnson, Start Date: 2024-03-10, End Date: 2024-09-10, Email:
[email protected]
ID: 1004, Name: Bob Brown, Start Date: 2024-04-22, End Date: 2024-10-22, Email:
[email protected]
ID: 1005, Name: Emily Davis, Start Date: 2024-05-15, End Date: 2024-11-15, Email:
[email protected]

code:
// You are using Java
import java.sql.*;
import java.util.*;
class CrudeOil{
static void DisplayAllData(Connection con){
try{
PreparedStatement pst =con.prepareStatement("select * from
subscriber");
ResultSet rs= pst.executeQuery();
while(rs.next()){
System.out.println("ID: "+rs.getInt(1)+", Name:
"+rs.getString(2)+", Start Date: "+rs.getString(3)+", End Date:
"+rs.getString(4)+", Email: "+rs.getString(5));

}catch(SQLException sqe){
sqe.printStackTrace();
}

}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost/ri_db","test","test123");
PreparedStatement pst = null;
int choice = sc.nextInt();
switch(choice){
case 1:{
int id = sc.nextInt();
sc.nextLine();
String name = sc.nextLine();
String stdate = sc.nextLine();
String edate = sc.nextLine();
String email = sc.nextLine();
pst = con.prepareStatement("insert into subscriber
values(?,?,?,?,?)");
pst.setInt(1,id);
pst.setString(2,name);
pst.setString(3,stdate);
pst.setString(4,edate);
pst.setString(5,email);
int x = pst.executeUpdate();
if(x>0)
System.out.println("Subscriber added successfully.");
DisplayAllData(con);
}
break;
case 2:{
int id = sc.nextInt();
sc.nextLine();
String email = sc.nextLine();
pst = con.prepareStatement("update subscriber set email=? where
subscriber_id=?");

pst.setString(1,email);
pst.setInt(2,id);

int x = pst.executeUpdate();
if(x>0){
System.out.println("Subscriber updated successfully.");
DisplayAllData(con);

}
break;
case 3:{
int id = sc.nextInt();

pst = con.prepareStatement("delete from subscriber where


subscriber_id=?");

pst.setInt(1,id);

int x = pst.executeUpdate();
if(x>0){
System.out.println("Subscriber deleted successfully.");
DisplayAllData(con);

}
break;
case 4:{
DisplayAllData(con);
}
break;

}
}catch(ClassNotFoundException cde){
System.out.println("Driver issue...");

}
catch(SQLException sqe){
sqe.printStackTrace();

}
}
_______________________________________

Voter data Management

You are tasked with developing a Java application to manage voter data using JDBC
and MySQL. The application should allow users to perform CRUD (Create, Read,
Update, Delete) operations on the voter data stored in the database.

Table Name: voter

1. Insert voter details.

2. Update voter details.

3. Delete voter details.

4. Show all voter details.

NOTE:

Utilize try/catch and finally block to handle the SQLException.

The table name is case-sensitive and must match the one specified above.

The Table is created and some tuples have been already inserted into the table.

id range is between 1001 to 1005.

Input format :
The input consists of a number representing the CRUD operation like

1 - Inserting (the input should be of all attributes)

2 - Update (update the age based on voter_id)

3 - Delete

4 - Show all details

Output format :
The output should perform all the crud operations based on Menu driven.

Sample test cases :


Input 1 :
1
1006
Michael Wilson
50
Male
2024-01-06
Output 1 :
Voter added successfully.
ID: 1001, Name: John Doe, Age: 30, Gender: Male, Registration Date: 2024-01-01
ID: 1002, Name: Jane Smith, Age: 25, Gender: Female, Registration Date: 2024-01-02
ID: 1003, Name: Alice Johnson, Age: 45, Gender: Female, Registration Date: 2024-01-
03
ID: 1004, Name: Bob Brown, Age: 60, Gender: Male, Registration Date: 2024-01-04
ID: 1005, Name: Emily Davis, Age: 35, Gender: Female, Registration Date: 2024-01-05
ID: 1006, Name: Michael Wilson, Age: 50, Gender: Male, Registration Date: 2024-01-
06
Input 2 :
2
1001
45
Output 2 :
Voter updated successfully.
ID: 1001, Name: John Doe, Age: 45, Gender: Male, Registration Date: 2024-01-01
ID: 1002, Name: Jane Smith, Age: 25, Gender: Female, Registration Date: 2024-01-02
ID: 1003, Name: Alice Johnson, Age: 45, Gender: Female, Registration Date: 2024-01-
03
ID: 1004, Name: Bob Brown, Age: 60, Gender: Male, Registration Date: 2024-01-04
ID: 1005, Name: Emily Davis, Age: 35, Gender: Female, Registration Date: 2024-01-05
Input 3 :
3
1001
Output 3 :
Voter deleted successfully.
ID: 1002, Name: Jane Smith, Age: 25, Gender: Female, Registration Date: 2024-01-02
ID: 1003, Name: Alice Johnson, Age: 45, Gender: Female, Registration Date: 2024-01-
03
ID: 1004, Name: Bob Brown, Age: 60, Gender: Male, Registration Date: 2024-01-04
ID: 1005, Name: Emily Davis, Age: 35, Gender: Female, Registration Date: 2024-01-05
Input 4 :
4
Output 4 :
ID: 1001, Name: John Doe, Age: 30, Gender: Male, Registration Date: 2024-01-01
ID: 1002, Name: Jane Smith, Age: 25, Gender: Female, Registration Date: 2024-01-02
ID: 1003, Name: Alice Johnson, Age: 45, Gender: Female, Registration Date: 2024-01-
03
ID: 1004, Name: Bob Brown, Age: 60, Gender: Male, Registration Date: 2024-01-04
ID: 1005, Name: Emily Davis, Age: 35, Gender: Female, Registration Date: 2024-01-05

code 3:// You are using Java


import java.sql.*;
import java.util.*;

class CrudeOil{
static void DisplayAlldata(Connection con){
try{
PreparedStatement pst = con.prepareStatement("select * from voter");
ResultSet rs = pst.executeQuery();
while(rs.next()){
System.out.println("ID: "+rs.getInt(1)+", Name:
"+rs.getString(2)+", Age: "+rs.getInt(3)+", Gender: "+rs.getString(4)+",
Registration Date: "+rs.getString(5));
}
}catch(SQLException sqe){
sqe.printStackTrace();
}

}
public static void main(String args[]){

Scanner sc = new Scanner(System.in);


try{
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost/ri_db","test","test123");
PreparedStatement pst = null;
int choice = sc.nextInt();
switch(choice){
case 1:{
int id = sc.nextInt();
sc.nextLine();
String name = sc.nextLine();
int age = sc.nextInt();
sc.nextLine();
String gender = sc.nextLine();
String rdate = sc.nextLine();
pst = con.prepareStatement("insert into voter
values(?,?,?,?,?)");
pst.setInt(1,id);
pst.setString(2,name);
pst.setInt(3,age);
pst.setString(4,gender);
pst.setString(5,rdate);
int x = pst.executeUpdate();
if(x>0){
System.out.println("Voter added successfully.");
DisplayAlldata(con);
}
}
break;
case 2:{
int id = sc.nextInt();
int age = sc.nextInt();

pst = con.prepareStatement("update voter set age = ? where


voter_id = ?");
pst.setInt(1,age);

pst.setInt(2,id);

int x = pst.executeUpdate();
if(x>0){
System.out.println("Voter updated successfully.");
DisplayAlldata(con);
}
}
break;
case 3:{
int id = sc.nextInt();
pst = con.prepareStatement("delete from voter where
voter_id=?");
pst.setInt(1,id);

int x = pst.executeUpdate();
if(x>0){
System.out.println("Voter deleted successfully.");
DisplayAlldata(con);
}
}
break;
case 4:{
DisplayAlldata(con);
}

}
}catch(ClassNotFoundException cde){
System.out.println("Driver issue...");
}
catch(SQLException sqe){
sqe.printStackTrace();
}

// You are using Java


import java.util.*;
class Venue{
String name;
String city;
String address;
int pincode;

public Venue(String name , String city , String address , int pincode){


this.name = name;
this.city = city;
this.address= address;
this.pincode=pincode;
}
public String getName(){
return name;
}

public String getCity(){


return city;
}

public String getAddress(){


return address;
}
public int getPincode(){
return pincode;
}
}

class Main{

public static void main(String[]args){


Scanner sc= new Scanner(System.in);

String name;
String city;
String address;
int pincode;
name = sc.nextLine();
city = sc.nextLine();
address= sc.nextLine();
pincode= sc.nextInt();
Venue venue = new Venue(name,city,address,pincode);

System.out.println("Venue Details");
System.out.println("Venue Name: "+ venue.getName());
System.out.println("City Name : "+ venue.getCity());
System.out.println("City address : "+ venue.getAddress());
System.out.println("City Pincode : "+ venue.getPincode());

}
}

____________________________

// You are using Java


import java.util.*;
class Main{
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
ArrayList<String> list = new ArrayList<>();
int n= sc.nextInt();
sc.nextLine();
for(int i=0;i<n;i++){
String bookTitle = sc.nextLine();
list.add(bookTitle);
}

String SearchBook = sc.nextLine();


if(list.contains(SearchBook)){
System.out.println("Book Found");

}
else{
System.out.println("Book not found");
}

int cnt =0;


Iterator<String>it= list.iterator();
String keyword = sc.nextLine();
while(it.hasNext()){
if(it.next().contains(keyword)){
cnt++;

}
}
System.out.println(cnt);
Iterator<String>iti = list.iterator();
String longd = iti.next();
while(iti.hasNext()){
String data = iti.next();
if(longd.length()<data.length()){
longd= data;
}
}
System.out.println(longd);

String replace = sc.nextLine();


String replaceWith = sc.nextLine();
int index = list.indexOf(replace);
if(index==-1){
System.out.println("not found");
}else{
list.set(index,replaceWith);

}
Iterator<String> tt= list.iterator();
while(tt.hasNext()){
System.out.println(tt.next());
}

}
}

______________________________________________________________________________

import java.util.*;
class Tool{
private int id ;
private String name;
private boolean status;
private static int value;
static{
value=201;
}
Tool(){

}
Tool(String name){
id=value;
value++;
this.name= name;
this.status=false;
}
public int getId(){
return id;
}
public String getName(){
return name;
}
public boolean getStatus(){
return status;
}

public void setId(int id){


this.id=id;
}
public void setName(String name){
this.name=name;
}
public void setStatus(boolean status){
this.status=status;
}

class ToolRentalSystem{
private ArrayList<Tool>list= new ArrayList<>();

public void addTool(String name){


Tool tool = new Tool(name);
list.add(tool);
}

public void display(){


Iterator<Tool>it = list.iterator();
while(it.hasNext()){
Tool ts = it.next();
System.out.println("Tool (id="+ts.getId()+",name='"+ts.getName()
+"',rented="+ts.getStatus()+"}");

}
}
public void removeTool(int id){
Iterator<Tool> rf = list.iterator();
while(rf.hasNext()){
Tool rst = rf.next();
if()
}

}
}
class Main{
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
int n= sc.nextInt();
sc.nextLine();
ToolRentalSystem trs = new ToolRentalSystem();
for(int i=0;i<n;i++){
String name= sc.nextLine();
trs.addTool(name);

trs.display();

}
}

You might also like