Milestone 1
Milestone 1
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.
___________________________________________________________________________________
________
Problem statement
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
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
}
}
___________________________________________________________________________________
____________________
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".
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
Code constraints :
The input array should have at least one element.
}
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.
Output format :
Output consist of the concatenation of the array
Code constraints :
The input arrays can be of any length, including empty.
}
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.
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:
Code constraints :
The number of words (n) ≤ 20.
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();
}
}
________________________________________________________________________________
if(vowel==0){
return "invalid";}
char ch= sen.charAt(sen.length()-1);
if(ch!='.'&& ch!='?'&& ch!= '!') return "invalid";
return "valid";
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{
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();
}
}
___________________________________________________________________________________
________________________
DAY 4
Session 1
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.
Output format :
The output should display the venue details.
CODE::
// You are using Java
import java.util.*;
class Venue{
private String name;
private String city;
private String address;
private int pincode;
class Main{
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());
}
}
___________________________________________________________________________________
______________
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.
Output format :
The output should display delivery details.
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;
}
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());
___________________________________________________
For example: 9
9^2=81 =>8+1=9
Create a class named 'Main' with an attribute named 'num' of type int.
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
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:
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.
Code constraints :
In this scenario, the test cases fall under the following constraints:
1 ≤ m ≤ 100
1.00 ≤ n ≤ 100.00
CODE::
// You are using Java
import java.util.*;
class Circle{
class Main{
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 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 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.
Code constraints :
In this scenario, the test cases fall under the following constraints:
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();
}
___________________________________________________________________________________
________
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.
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){
}
}
________________________________________________________________________________
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;
}
}
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;
}
class Main{
public static void main(String []args){
Scanner sc = new Scanner(System.in);
_______________________________________
}
class OnlinePurchaseTransaction extends Transaction{
private String merchant;
OnlinePurchaseTransaction(int transactionId,double amount, String merchant){
super(transactionId,amount);
this.merchant=merchant;
}
class Main{
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
}
}
____________________________________________________________________________
}
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");
}
}
}
_______________________________________________________________________________
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.
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.
Code constraints :
1 ≤ amount ≤ 10,000
}
}
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
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:
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:
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.
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.
Code constraints :
The base price and the cost per topping should be greater than zero.
1 ≤ number of toppings ≤ 10
}
Pizza(double basePrice, double toppingCost, int numberOfTopping){
this.basePrice= basePrice;
this.toppingCost= toppingCost;
this.numberOfTopping=numberOfTopping;
}
public double calculatePrice(){
return basePrice +(toppingCost*numberOfTopping);
}
}
DiscountedPizza(){
}
}
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().
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.
Output format :
If the choice is 1, the output displays the actions of a warrior in the following
format:
"Warrior Actions:
If the choice is 2, the output displays the actions of a wizard in the following
format:
"Wizard Actions:
Code constraints :
1 ≤ M, N ≤ 106
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
// You are using Java
import java.util.*;
abstract class GameCharacter{
public abstract void attack();
public abstract void defend();
}
public void defend(){
System.out.println("Defend: raises shield , 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
Input format :
The first line of input consists of an integer, representing the initial resource
level.
Output format :
The output displays the predicted resource levels of each planet, separated by
space.
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
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.
Output format :
The output prints the army strength, which is the addition of the given matrices.
Code constraints :
The given test cases fall under the following constraints:
1 ≤ N ≤ 5
code::::
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();
}
}
}
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."
If the given string is a palindrome, the second line of output prints "The word is
a palindrome."
Code constraints :
1 ≤ input integer ≤ 109
}
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.";
}
}
}
}
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();
______________________________________________________________
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".
Code constraints :
1 ≤ n ≤ 500
code:
___________________________________________________________________________________
________--
Problem Statement
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.
Code constraints :
The input string consists of uppercase characters.
code____
class Main{
public static void main(String[]args){
Scanner scan = new Scanner(System.in);
int num= scan.nextInt();
String st = scan.nextLine();
if(growing.isGrowing()){
System.out.println("Growing string");
}
else{
System.out.println("Not growing string");
}
}
}
_____________________
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);
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();
}
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:
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.
}
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");
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
Output format :
The output should display the list of employees.
code:
class Employee{
private String employeeName;
private int employeeId;
private String employeeDepartment;
@Override
public String toString(){
return "Employee
[employeeName="+employeeName+",employeeId="+employeeId+",employeeDepartment="+emplo
yeeDepartment+"]";
}
class test{
public static void main(String []args){
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);
}
}
_______________________
Input format :
The first line of the input contains the number of books.
Output format :
Displays the final list of books
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___________
class Product{
private int productId;
private String productName;
private double productPrice;
private String productCategory;
Product(){
this(0,"",0.0,"");
}
class ProductList{
private Product[] products;
private int nop;
ProductList(){
this(5);
}
ProductList(int size){
products = new Product[size];
nop = 0;
}
class Main{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
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 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!"
Code constraints :
The given test cases fall under the following constraints:
1 ≤ n ≤ 10
1 ≤ seat number ≤ 10
}
int m = sc.nextInt();
if(!ts.contains(m)){
System.out.println(m+" is not present!");
}
else{
System.out.println(m+" is present!");
}
}
}
___________________
Problem Statement
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
Output format :
The output prints the updated TreeSet after sorting preferences and simulating
allocation by removing the first preference.
Code constraints :
1 ≤ N ≤ 10
for(int i=1;i<=n;i++){
list.add(sc.nextInt());
}
Iterator<Integer> it= list.iterator();
it.next();
it.remove();
System.out.println(list);
}
_________________
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.
Output format :
The output prints "Longest word: " followed by the longest fruit name present in
the TreeSet.
Code constraints :
The given test cases fall under the following constraints:
1 ≤ n ≤ 10
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.
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'.
Output format :
The output displays the details of the halls.
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;
}
class Main{
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();
}
Collections.sort(list);
for(Hall h : list){
System.out.println(h);
}
}
}
___________code2 by agrim____________
________________
Employee High Score Leaderboard Management System
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.
Output format :
Display the leaderboard in descending order of scores.
Code constraints :
Employee names will not exceed 100 characters.
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);
}
}
}
___________________
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 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.
code:
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.
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:
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:
String name
String contactNumber
double costPerDay
String ownerName
code:::
public Hall(){
}
Hall(String name,String contactNumber, double costPerDay, String ownerName){
this .name= name;
this.contactNumber= contactNumber;
this.costPerDay= costPerDay;
this.ownerName= ownerName;
}
}
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 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}.
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:
All Contacts:
class PhoneBook{
HashMap<String, String> contacts = new HashMap<>();
/*PjhoneBook(){
contacts= new HashMap;
}*/
}
System.out.println("All Contacts:");
book.displayContact();
}
}
___________________________________________________________________
SESSION 2
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]
Code constraints :
The test cases will fall under the following constraints:
The program should be case-sensitive, meaning 'a' and 'A' are considered different
characters.
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());
}
_________________________________________________________________
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.
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.
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
code:
______________________________________________
Input format :
The input consists of multiple lines where each line represents an item and its
quantity, separated by a space.
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).
Output format :
For each student, print their subjects and corresponding grades in the format:
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.
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.
Code constraints :
The number of students (n) is ≤ 10.
import java.util.*;
class Test{
public static void main(String[]args){
TreeMap<Integer, String> t= new TreeMap<>(Collections.reverseOrder());
}
}
/----/----------------------------------------------
Problem Statement
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]
Code constraints :
The test cases will fall under the following constraints:
The program should be case-sensitive, meaning 'a' and 'A' are considered different
characters.
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
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.
Code constraints :
Integers only.
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);
}
}
}
__________________________
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.
try{
int input = sc.nextInt();
System.out.println(input);
}
catch(InputMismatchException e){
System.out.println(e);
}
}
}
_________________________________________
You are tasked with developing a Java program to manage operations involving a
critical number. The program must handle potential errors using exception handling.
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.
Input format :
The input consists of a single integer.
Output format :
The output is based on the following conditions:
code:
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
id - String
bookTitle - String
authorName - String
price - float
quantityAvailable - int
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:
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;
class Main{
public static void main(String []args){
Scanner sc = new Scanner(System.in);
__________________________
name - String
userAge - int
mark - int
Minimum eligibility for obtaining a driving license:
Input format :
The first line consists of a name a String.
Output format :
The output should display "Approved" if he meets the criteria or the appropriate
exception.
code:
// You are using Java
import java.util.*;
class InvalidAgeForDrivingLicenseException extends Exception{
public InvalidAgeForDrivingLicenseException(String message){
super(message);
}
}
class Main{
String name ;
int userAge;
int 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.
Input format :
The first line of input consists of a string, representing the student's name.
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.
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
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.
Input format :
The input consists of an integer N.
Output format :
If N is an Armstrong number, print "N is Armstrong number."
If N is other than an integer value, print "Error: Input must be a valid integer."
Code constraints :
1 ≤ valid input value ≤ 104
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());
}
}
_____________________________________
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:
The table name is case-sensitive and must match the one specified above.
Input format :
No console Input
Output format :
The output of the query should include the following headers to be considered:
CITY, LENGTH
Table: sales
___________
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.
Input format :
No Console Input
___________________________
Write a SQL Query to display the count of the number of product sales on each date
from the orders table.
___________________________________________________________________________________
_______________________________
SESSION 3
:
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.
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.
Input format :
The input consists of a number representing the CRUD operation like
3 - Delete
Output format :
The output should perform all the crud operations based on Menu driven.
code:
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();
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:{
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:{
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.
Note:
code:
// You are using Java
import java.util.*;
import java.sql.*;
class Main{
public static void main(String[]args){
}
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.
Note:
The table name is case-sensitive and must match the one specified above.
Input format :
The number of students (integer) on the first line.
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:
Note:
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.
Output format :
Displays office table details.
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.
Input format :
No console input
Output format :
The output should display the second row from the table.
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.
Input format :
No console input
Output format :
The output should display the contact details as shown in the sample output.
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.
NOTE:
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.
Input format :
The input consists of a number representing the CRUD operation like
3 - Delete
code:
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;
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.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.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 __
static{
cnt=301;
}
Appliance(){
Appliance(String name){
id=cnt;
cnt++;
this.name=name;
rented=false;
}
public void setID(int id){
this.id=id;
}
class ApplianceRentalSystem{
private ArrayList<Appliance> list;
public ApplianceRentalSystem(){
list = new ArrayList<>();
}
class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.nextLine();
System.out.println("Updated Inventory");
ap.displayAppliances();
JDBC CRUD
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.
NOTE:
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.
Input format :
The input consists of a number representing the CRUD operation like
3 - Delete
Output format :
The output should perform all the crud operations based on Menu driven.
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;
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.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.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();
}
}
}
}
__________________________________
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.
NOTE:
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.
Input format :
The input consists of a number representing the CRUD operation like
3 - Delete
Output format :
The output should perform all the crud operations based on Menu driven.
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.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();
}
}
_______________________________________
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.
NOTE:
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.
Input format :
The input consists of a number representing the CRUD operation like
3 - Delete
Output format :
The output should perform all the crud operations based on Menu driven.
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[]){
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();
}
class Main{
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());
}
}
____________________________
}
else{
System.out.println("Book not found");
}
}
}
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);
}
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;
}
class ToolRentalSystem{
private ArrayList<Tool>list= new ArrayList<>();
}
}
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();
}
}