100% found this document useful (2 votes)
2K views47 pages

Java Handsom

Accenture Primer

Uploaded by

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

Java Handsom

Accenture Primer

Uploaded by

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

<----------------------- JAVA PRACTICE PROGRAMS -------------------------->

1. Print Message

public class UserInterface {

public static void main(String[] args)


{
//Fill your code here
[Link]("Thank you for your order");
}

2. Sky Airlines

import [Link];
public class UserInterface {

public static void main(String[] args)


{
Scanner sc= new Scanner([Link]);
//Fill your code here
[Link]("Enter name");
String name = [Link]();
[Link]("Enter source");
String src = [Link]();
[Link]("Enter destination");
String dest = [Link]();
[Link]("Dear "+name+",welcome onboard with service from "+src+"
to "+dest+". "+"Thankyou for choosing Sky Airlines. Enjoy your flight.");
}

}
3. Swap two numbers

import [Link];

public class UserInterface {

public static void main(String[] args)


{
Scanner sc = new Scanner([Link]);
[Link]("Enter the numbers");
int a = [Link]();
int b = [Link]();
[Link]("Before swapping");
[Link]("first="+a+", second="+b);
a = a^b;
b = a^b;
a = a^b;
[Link]("After swapping");
[Link]("first="+a+", second="+b);

4. Oxygen Plants

import [Link];
public class UserInterface {
public static void main(String args[])
{
Scanner sc=new Scanner([Link]);
[Link]("Enter the length of the room(in m)");
double len = [Link]();
if(len<=0){
[Link]("Invalid length");
return;
}
[Link]("Enter the breadth of the room(in m)");
double bre = [Link]();
if(bre<=0){
[Link]("Invalid breadth");
return;
}
[Link]("Enter the plant area of a single plant(in cm2)");
double area = [Link]();
if(area<=0){
[Link]("Invalid plant area");
return;
}
double a = (len * bre);
double t1 = area/10000;
double temp = a/t1;
double rem = temp%10;
temp -= rem;

double oxy = temp * 0.9;

String poxygen = [Link]("%.02f",oxy);


String pl = [Link]("%.02f",len);
String pb = [Link]("%.02f",bre);
String pplant = [Link]("%.0f",temp);
[Link]("Total number of plants is"+pplant);
[Link]("Total oxygen production is "+poxygen+" litres");
}

5. BMI Calculator

import [Link];

public class UserInterface {

public static void main(String[] args)


{
Scanner sc = new Scanner([Link]);
//Fill the code here
[Link]("Enter weight in kg");
double wt = [Link]();
[Link]("Enter height in cm");
double h = [Link]();
//double val = h * h;
//val = val/10000;
double bmi = wt/((h/100) * (h/100));
if(bmi>=25){
[Link]("Your BMI is %.2f. You are overweight\n",bmi);
[Link]("Reduce %.2f kg to be fit",(bmi-25));
}
else if(bmi<25 && bmi>18.5){
[Link]("Your BMI is %.2f. You are fit and healthy\n", bmi);
}
else{
[Link]("Your BMI is %.2f. You are underweight\n", bmi);
[Link]("Gain %.2f kg to be fit", (18.5-bmi));
}
}

6. Sim Card

import [Link];

public class UserInterface{

public static void main(String[] args){

Scanner sc=new Scanner([Link]);

//Fill the code here


[Link]("Enter the phone number");
long phone = [Link]();
int odd = 0, even = 0;
long temp = phone, rem = 0;
while(temp>0){
rem = temp % 10;
if(rem % 2 == 1){
odd += rem;
}else{
even +=rem;
}
temp /=10;
}
if(odd>even){
[Link]("Sum of odd is greater than sum of even");
}
else if(odd<even){
[Link]("Sum of even is greater than sum of odd");
}
else{
[Link]("Sum of odd and even are equal");
}

}
}

7. Reverse and Expand

import [Link];

public class UserInterface {

public static void main(String[] args)


{
Scanner sc = new Scanner([Link]);
//Fill the code here
[Link]("Enter the number");
int num = [Link]();
int f=0,s=0,th=0,fo=0;
int cnt=0;
int temp = num;
int rev = 0;
while(temp>0){
cnt++;
int rem = temp%10;
rev = rev*10+rem;
temp /=10;
}
if(cnt!=4){
[Link](num+" is an invalid number");
return;
}
temp = rev;
String res = "";
int rev2=1;
while(temp>0){
int rem = temp%10;
String st = ""+rev2*rem;
res = st+"+"+res;
rev2*=10;
temp/=10;
}
[Link]("Reversed number is "+rev);
[Link]([Link](0,[Link]()-1));
}

8. Magic goose

import [Link];

public class UserInterface {

public static void main(String[] args)


{
Scanner sc = new Scanner([Link]);
//Fill the code here
int day, var1=0,var2=1;
int[] egg = new int[31];
[Link]("Enter the day");
day = [Link]();
if(day>30 || day<=0){
[Link](day+" is invalid day");
return;
}
egg[0] = 0;
egg[1] = 1;
for(int i = 2; i <31;i++){
egg[i] = var1+2*var2;
var1=var2;
var2=egg[i];
}
[Link]("Number of eggs in "+day+"th day is "+egg[day]);
}

9. Lottery Winner

import [Link];
public class UserInterface
{
public static void main(String[] args)
{
Scanner sc=new Scanner([Link]);
//Fill code here
[Link]("Enter the ticket id");
long val = [Link]();
[Link]("Enter the unlucky code");
long un = [Link]();
long temp = val;
int cnt = 0;
while(temp>0){
long rem = temp%10;
if(rem==un){
cnt++;
}
temp/=10;
}
if(cnt==0){
[Link](val+" is lucky ticket");
}else if(cnt<3){
[Link](val+" is partially lucky");
}else{
[Link](val+" is unlucky ticket");
}
}
}

10. Ludo King

import [Link];
public class UserInterface
{
public static void main(String[] args)
{
Scanner sc=new Scanner([Link]);
//Fill code here
[Link]("Enter Alex points");
int alex = [Link]();
if(alex<0 || alex>50){
[Link](alex+" is an invalid number");
return;
}
[Link]("Enter Nikil points");
int ni = [Link]();
if(ni<0 || ni>50){
[Link](ni+" is an invalid number");
return;
}
[Link]("Enter Sam points");
int sam = [Link]();
if(sam<0 || sam>50){
[Link](sam+" is an invalid number");
return;
}
if(alex==ni || alex==sam || ni==sam){
[Link]("The game is a tie");
}
else if(alex>ni && alex>sam){
[Link]("Alex scored "+alex+" points and won the game");
}else if(ni>alex && ni>sam){
[Link]("Nikil scored "+ni+" points and won the game");
}else if(sam>alex && sam>ni){
[Link]("Sam scored "+sam+" points and won the game");
}
}
}

11. Student Details - Constructor

File 1. [Link]

public class Student {

// Fill the code


private int studentId;
private String studentName, studentAddress, collegeName;
public int getStudentId(){
return studentId;
}
public String getStudentName(){
return studentName;
}
public String getStudentAddress(){
return studentAddress;
}
public String getCollegeName(){
return collegeName;
}
public Student(int sid, String sname, String sadd){
studentId = sid;
studentName = sname;
collegeName="NIT";
studentAddress=sadd;
}
public Student(int sid, String sname, String sadd, String cname){
studentId = sid;
studentName = sname;
collegeName = cname;
studentAddress = sadd;
}

File 2. [Link]

import [Link];
public class UserInterface {

public static void main(String[] arg)


{
// Fill the code
Scanner sc = new Scanner([Link]);
int flag;
String cname="";
[Link]("Enter Student's Id:");
int sid=[Link]();
[Link]();
[Link]("Enter Student's Name:");
String sname=[Link]();
[Link]("Enter Student's address:");
String sadd = [Link]();
while(true){
[Link]("Whether the student is from NIT(Yes/No):");
String check=[Link]();
if([Link]("yes")){
flag=1;
break;
}
else{
if([Link]("no")){
flag=0;
[Link]("Enter the college name:");
cname = [Link]();
break;
}
else
[Link]("Wrong input");
}
}
if(flag==1){
Student s = new Student(sid,sname,sadd);
[Link]("Student id:"+[Link]());
[Link]("Student name:"+[Link]());
[Link]("Address:"+[Link]());
[Link]("College name:"+[Link]());
}
else{
Student s = new Student(sid,sname,sadd,cname);
[Link]("Student id:"+[Link]());
[Link]("Student name:"+[Link]());
[Link]("Address:"+[Link]());
[Link]("College name:"+[Link]());
}
}
}

12. Volume calculator- Over Loading

File 1. [Link]

import [Link];
public class UserInterface {

public static void main(String[] arg)


{
// Fill the code
VolumeCalculator vc = new VolumeCalculator();
Scanner sc=new Scanner([Link]);
[Link]("Enter the choice");
[Link]("[Link] Volume For Cylinder\[Link] Volume For Cuboid");
int choice= [Link]();
switch(choice){
case 1:
{
[Link]("Enter the radius");
double r=[Link]();
[Link]("Enter the height");
double h = [Link]();
[Link]("Volume of the Cylinder is
"+[Link]("%.2f",[Link](r,h)));
break;
}
case 2:
{
[Link]("Enter the length");
int l = [Link]();
[Link]("Enter the breadth");
int b = [Link]();
[Link]("Enter the height");
int h = [Link]();
[Link]("Volume of the Cuboid is
"+[Link]("%.2f",[Link](l,b,h)));
break;
}
default:
[Link]("Invalid Input");
break;

}
}
}

File 2. [Link]

public class VolumeCalculator {

// Fill the code


public double calculateVolume(double radius, double height){
double cylinder=3.14*radius*radius*height;
return cylinder;
}
public double calculateVolume(int length, int breadth, int height){
double cuboid=(double)length*breadth*height;
return cuboid;
}
}

13. Bloodworks Northwest

File 1. [Link]

public class DonorDetails


{

//Include Getters and Setters


//Include five argument constructor
private String name;
private int age;
private String gender;
private String bloodGroup;
private long phoneNumber;
public void setName(String name){
[Link]=name;
}
public void setAge(int name){
[Link]=age;
}
public void setGender(String gen){
[Link]=gen;
}
public void setBloodGroup(String bg){
[Link]=bg;
}
public void setPhoneNumber(long no){
[Link]=no;
}
public String getName(){
return [Link];
}
public int getAge(){
return [Link];
}
public String getGender(){
return [Link];
}
public String getBloodGroup(){
return [Link];
}
public long getPhoneNumber(){
return [Link];
}
public DonorDetails(String name, int age, String gender, String bloodGroup, long
phoneNumber){
[Link] = name;
[Link] = age;
[Link] = gender;
[Link] = bloodGroup;
[Link] = phoneNumber;
}

File 2. [Link]

import [Link];
public class UserInterface
{
public static void main(String args[])
{

Scanner sc =new Scanner([Link]);


//Fill the code
[Link]("Enter the name");
String name = [Link]();
[Link]("Enter the age");
int age = [Link]();
[Link]();
[Link]("Enter the gender");
String gender = [Link]();
[Link]("Enter the blood group");
String bloodGroup = [Link]();
[Link]("Enter the phone no");
long phoneNumber = [Link]();
DonorDetails d = new DonorDetails(name,age,gender,bloodGroup,phoneNumber);
[Link]("Name:"+name);
[Link]("Age:"+age);
[Link]("Gender:"+gender);
[Link]("Blood group:"+bloodGroup);
[Link]("Phone no:"+phoneNumber);
}

14. Movie Ticket – Static

File 1. [Link]

public class Ticket


{
// Fill the code
private int ticketid;
private int price;
private static int availableTickets;

public int getTicketId(){


return ticketid;
}

public void setTicketid(int ticketid){


[Link]=ticketid;
}

public int getPrice(){


return price;
}

public void setPrice(int price){


[Link]=price;
}

public static void setAvailableTickets(int availableTickets){


[Link]=availableTickets;
}
public static int getAvailableTickets(){
return availableTickets;
}

public int calculateTicketCost(int nooftickets)


{
// Fill the code
if(availableTickets>=nooftickets&&availableTickets>0&&nooftickets>0){
int totalAmount=nooftickets*price;
availableTickets-=nooftickets;
return totalAmount;
} else{
return -1;
}

File 2. [Link]

import [Link];
public class UserInterface {

public static void main(String[] arg)


{
// Fill the code
Scanner sc=new Scanner([Link]);
[Link]("Enter movie name");
String movieName=[Link]();

[Link]("Enter no of bookings");
int numberOfBookings=[Link]();

[Link]("Enter the available tickets");


int availableTickets=[Link]();
[Link](availableTickets);

for(int i=0;i<numberOfBookings;i++){
Ticket ticket=new Ticket();
[Link]("Enter the ticketid");
int ticketId=[Link]();
[Link](ticketId);

[Link]("Enter the price");


int price=[Link]();
[Link](price);

[Link]("Enter the no of tickets");


int numberOfTickets=[Link]();

[Link]("Available Tickets: "+[Link]());

int totalAmount=[Link](numberOfTickets);

if(totalAmount==-1){
[Link]("Tickets are not available");

}else if([Link]()==0){
[Link]("Total amount: "+totalAmount);
[Link]("House Full");
return;
}
else{
[Link]("Total amount: "+totalAmount);
[Link]("Available ticket after booking: "+[Link]());

}
}
if([Link]()==0){
[Link]("House full");
}

}
}

15. Date Validation - Use SimpleDateFormat


import [Link];
import [Link];
import [Link];

public class UserInterface {

public static void main(String[] args) {


Scanner sc=new Scanner([Link]);

//FILL THE CODE


[Link]("Enter the date");
String date = [Link]();
if(!valid(date)){
[Link](date+" is not a valid date");
return;
}
if([Link]()!=10){
[Link](date+" is not a valid date");
}
if([Link](2)!='/'&& [Link](5)!='/'){
[Link](date+" is not a valid date");
return;
}
String[] str = [Link]("/");
if([Link]!=3){
[Link](date+" is not a valid date");
return;
}
int curr = [Link](str[0]);
int months = [Link](str[1]);
int year = [Link](str[2]);

if(curr>0 && curr <=31 && months>0 && months <=12){


if(months==2 && curr <=29){
if(curr ==29){
if(check(year)){
[Link](date+" is a valid date");
return;
}else{
[Link](date+" is not a valid date");
return;
}
}else{
[Link](date+" is a valid date");
return;
}

}else if(months==4 || months==6 || months ==9 || months ==11){


if(curr<=30 && curr>0){
[Link](date+" is a valid date");
return;
}else{
[Link](date+" is not a valid date");
return;
}
}else if(months ==1 || months == 3 || months == 5 || months ==7 || months == 8 ||
months ==10 || months ==12){
if(curr<=31&&curr>0){
[Link](date+ " is a valid date");
return;
}else{
[Link](date+" is not a valid date");
return;
}
}
}else{
[Link](date+ " is not a valid date");
return;
}

}
public static boolean check(int year){
boolean flag = false;
if(year%4==0){
flag = true;
if(year%100==0){
flag = true;
if(year%400==0){
flag=true;
}else{
flag=false;
}
}
}
else{
flag=false;
}
return flag;
}
public static boolean valid(String date){
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy");
[Link](false);
try{
[Link](date);
return true;
}catch(ParseException e){
return false;
}
}
}

16. Calculate Expiry Date - Use Calendar

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class UserInterface {

public static void main(String[] args) {


Scanner sc=new Scanner([Link]);

//FILL THE CODE


[Link]("Enter the Manufacturing Date");
String mfD = [Link]();
Date mfDate=null;
try{
mfDate=parseDate(mfD);
[Link]("Enter the Month of Validity");
int mfV= [Link]();
Date exD = calculateExpDate(mfDate,mfV);
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyy");
String expDate = [Link](exD);
[Link](expDate+" is the expiry date");
}catch(ParseException e){
[Link](mfD+" is not a valid date");
return;
}

}
public static Date parseDate(String dateStr) throws ParseException{
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
[Link](false);
return [Link](dateStr);
}
public static Date calculateExpDate(Date mfd, int months){
Calendar calendar = [Link]();
[Link](mfd);
[Link]([Link],months);
return [Link]();
}
}

17. Sum of Max

import [Link];

public class UserInterface{

public static void main(String[] args){

Scanner sc=new Scanner([Link]);

//Fill the code here


[Link]("Enter the array size");
int n = [Link]();
if(n%2==1){
[Link](n+" is an odd number. Please enter even number.");
}
else if(n<=0){
[Link](n+" is an invalid array size.");
}else{
int[] arr= new int[n];
[Link]("Enter the number");
for(int i=0; i<n; i++){
arr[i] = [Link]();
}
sort(arr,n);
int maxi=0;
for(int i = 0; i<n/2;i++){
int sum = arr[i] + arr[n-i-1];
if(maxi<sum){
maxi=sum;
}
}
[Link]("The maximum number is "+maxi);
}
}
public static void sort(int[] arr, int n){
int indx=-1;
for(int i = 0; i <n;i++){
indx=i;
for(int j=i; j<n;j++){
if(arr[j]<arr[indx]){
indx = j;
}
}
int temp = arr[i];
arr[i] = arr[indx];
arr[indx] = temp;
}
}
}

18. Subset or not


import [Link].*;

public class UserInterface{

public static void main(String[] args){

Scanner sc=new Scanner([Link]);

//Fill the code here


[Link]("Enter the first array size");
int s1=[Link]();
if(s1<=0){
[Link](s1+" is an invalid array size");
return;
}
[Link]("Enter the numbers");
HashSet<Integer> set= new HashSet<>();
for(int i = 0; i <s1; i++){
int val = [Link]();
[Link](val);
}
[Link]("Enter the second array size");
int s2 = [Link]();
if(s2<=0){
[Link](s2+" is an invalid array size");
return;
}
if(s2>s1){
[Link](s2+" is an invalid size as it is greater than first array size "+s1);
return;
}
[Link]("Enter the numbers");
int cnt=0;
for(int i = 0; i <s2;i++){
int val = [Link]();
if([Link](val)){
cnt++;
}
}
if(cnt==s2){
[Link]("Array2 of size "+s2+" is a subset of array1");
}else{
[Link]("Array2 of size "+s2+" is not a subset of array1");
}
}
}

19. Prime Number Game

import [Link];

public class UserInterface {


public static void main(String[]args)
{
Scanner sc=new Scanner([Link]);
//Fill the code here
[Link]("Enter the size of first array");
int n1 = [Link]();
if(n1<=0){
[Link](n1+" is an invalid array size");
return;
}
[Link]("Enter the array elements");
int[] arr = new int[n1];
for(int i = 0; i<n1; i++){
arr[i] = [Link]();
if(arr[i]<0){
[Link](arr[i]+" is an invalid input");
return;
}
}
[Link]("Enter the size of second array");
int n2 = [Link]();
if(n2<=0){
[Link](n2+" is an invalid array size");
return;
}
if(n2!=n1){
[Link]("Both array size is different");
return;
}
[Link]("Enter the array elements");
int sum = 0;
for(int i = 0; i <n2;i++){
int val = [Link]();
arr[i]=arr[i]+val;
sum+=arr[i]%10;
if(val<0){
[Link](val+" is an invalid input");
return;
}
}
if(isPrime(sum)==false){
[Link](sum+" is a prime number");
}else{
[Link](sum+" is not a prime number");
}

}
public static boolean isPrime(int n){
boolean flag = false;
for(int i = 2;i<=n/2; i++){
if(n%i==0){
flag=true;
break;
}
}
return flag;
}

20. Magic Sum

import [Link].*;
public class UserInterface{

public static void main(String[] args){

Scanner sc=new Scanner([Link]);

//Fill the code here


[Link]("Enter the array size");
int num = [Link]();
if(num<1 || num>5){
[Link](num+" is an invalid array size");
return;
}
[Link]("Enter the numbers");
List<Integer> res=new ArrayList<>();
int[] arr= new int[num];
for(int i = 0; i < num; i++){
arr[i] = [Link]();
if(arr[i]<=0 || arr[i]>=100){
[Link](arr[i]+" is an invalid input");
return;
}
}
for(int i = 0; i < num; i++){
if(checkPrime(arr[i])){
int sum = arr[i];
int val = 0;
for(int j = 2;j<sum; j++){
if(checkPrime(j)){
val+=j;
}
if(val==sum){
[Link](sum);
break;
}
if(val>sum){
break;
}
}
}
}
if([Link]()!= 0){
[Link]("The sum of prime numbers is");
for(int ele:res){
[Link](ele);
}
}else{
[Link]("The "+num+" numbers are not sum of prime numbers");
}
}
public static boolean checkPrime(int n){
if(n<2) return false;
for(int i = 2; i <= n/2; i++){
if(n%i == 0){
return false;
}
}
return true;
}
}

21. PIN Number

import [Link].*;

public class UserInterface{

public static void main(String[] args){

Scanner sc=new Scanner([Link]);

//Fill the code here


[Link]("Enter the total number of PIN numbers");
int n = [Link]();
if(n<=0){
[Link](n+" is an invalid number");
return;
}
int[] arr = new int[n];
[Link]("Enter the PIN numbers");
for(int i = 0; i <n; i++){
arr[i] = [Link]();
int temp = arr[i];
int cnt=0;
while(temp>0){
cnt++;
temp/=10;
}
if(cnt!=4){
[Link](arr[i]+" is an invalid PIN number");
return;
}
}
List<Integer> res = new ArrayList<>();
for(int i = 0; i <n; i++){
int num = arr[i];
int four = num%10;
num/=10;
int three = num%10;
num/=10;
int two=num%10;
num/=10;
int one = num;
if(four==0 || three ==0 || two ==0 || one ==0){
continue;
}else if((one%2==1)&&(two%2==0)&&(three==2 || three==3 || three ==5
||three==7)&&(four==4 || four==6 || four==8||four==9)){
[Link](arr[i]);
}
}
if([Link]()!=0){
[Link]("Valid PIN numbers are");
for(int ele:res){
[Link](ele);
}
}else{
[Link]("All these "+n+" numbers are not a valid PIN number");
}

}
}
22. Two arrays game

import [Link];

public class UserInterface{

public static void main(String[] args){

Scanner sc=new Scanner([Link]);

//Fill the code here


[Link]("Enter the size for the first array");
int n = [Link]();
if(n<=0){
[Link](n+" is an invalid array size");
return;
}
[Link]("Enter the elements for the first array");
int[] arr = new int[n];
for(int i = 0; i < n; i++){
arr[i] = [Link]();
}
[Link]("Enter the size for the second array");
int m = [Link]();
if(m<=0){
[Link](m+" is an invalid array size");
return;
}
[Link]("Enter the elements for the second array");
int[] arrm = new int[m];
for(int i =0; i<m;i++){
arrm[i] = [Link]();
}
if(n!=m){
[Link]("Both array size are not same");
return;
}
for(int i = 0; i < n; i++){
if(i%2==0){
arr[i] = arr[i]+arrm[i];
}else{
arr[i]=arr[i]-arrm[i];
}
}
[Link]("The elements of the third array");
for(int i = 0; i < n; i++){
[Link](arr[i]);
}
}
}

23. Simple Addition - Varargs

// Don't Change the Structure

import [Link];

public class UserInterface


{
public static void main(String args[])
{
Scanner sc =new Scanner([Link]);

//Call the addition method with two arguments 10,15


int res1 = addition(10,15);

//Call the addition method with three arguments 10,20,30


int res2 = addition(10,20,30);

//Call the addition method with six arguments 10,30,60,100,5,15


int res3 = addition(10,30,60,100,5,15);
}

//Include the public static int addition(int... a) method

public static int addition(int... a){


int sum =0;
[Link]("Number of arguments is "+[Link]);
for(int ele:a){
sum+=ele;
}
[Link]("Total "+sum);
return sum;
}
}

24. Happy Mart - Arrays Class

File 1. [Link]

public class Product {


public int productId;
public String productName;
public double price;

//Include three argument constructor to initialize values


public Product(int productId, String productName, double price){
[Link]=productId;
[Link]=productName;
[Link]=price;
}

//This method should return the productId, productName and price seperated by
whitespace
public String toString()
{
return productId + " " + productName + " " + price;
}

File 2. [Link]

import [Link];

public class SortById implements Comparator<Product> {


public int compare(Product a, Product b){
return [Link] - [Link];
}
}

File 3. [Link]

import [Link];
public class SortByPrice implements Comparator<Product> {
public int compare(Product a, Product b){
return (int) ([Link] - [Link]);
}
}

File 4. [Link]

import [Link];
import [Link];

public class UserInterface {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);


// Fill the code here
[Link]("Enter the products count");
int productCount = [Link]();
if(productCount <= 0){
[Link]("Invalid count");
return;
}

Product[] products = new Product[productCount];


[Link]("Enter Product details");
for(int i = 0; i < productCount; i++){
String[] productDetails = [Link]().split(":");
int productId = [Link](productDetails[0]);
String productName = productDetails[1];
double price = [Link](productDetails[2]);
products[i] = new Product(productId, productName, price);
}
[Link]("[Link] By Id\n2. Sort By Price\nEnter your choice");
int choice = [Link]();
if(choice==1){
[Link](products, new SortById());
[Link]("After Sorting By Id");
}else if(choice ==2){
[Link](products, new SortByPrice());
[Link]("After Sorting By Price");
}else{
[Link]("Invalid choice");
return;
}
for(Product product : products){
[Link](product);
}
}

25. Resort booking

import [Link];
public class UserInterface {
public static void main(String args[])
{
//fill the code here
Scanner sc=new Scanner([Link]);
[Link]("Enter the customer details");

String input =[Link]();

String[] str =[Link](":");

String name = str[0];

int ad = [Link](str[1]);

int ch =[Link](str[2]);

int d =[Link](str[3]);

if(ad<0){

[Link]("Invalid input for number of adults");

return;

}else if(ch<0){

[Link]("Invalid input for number of children");

return;

}else if(d<=0){

[Link]("Invalid input for number of days");

return;

CalCost(name, ad,ch,d);
}

public static void CalCost(String name, int peroid, int child, int day){

int total =((peroid*1000)+(child*650))*day;


[Link](name+" your booking is confirmed and the total cost is "+total);

26. Travel Agency

import [Link].*;

public class UserInterface{

public static void main(String[] args){

Scanner sc=new Scanner([Link]);

//Fill the code here


HashSet<String> set = new HashSet<>();

[Link]("chennai");

[Link]("coimbatore");

[Link]("erode");

[Link]("karur");

[Link]("madurai");

[Link]("hyderabad");

[Link]("salem");

[Link]("bangalore");

[Link]("delhi");
[Link]("agra");

[Link]("Enter the city name");

String str = [Link]();

String ch = [Link]();

if([Link](ch)){

[Link]("Bus for "+str+" is available");


return;

}else{

[Link]("Bus for "+str+" is not available");

return;

}
}

27. Complete the Caption

import [Link];
public class UserInterface {
public static void main(String[] args){
Scanner sc=new Scanner([Link]);
//fill the code here
[Link]("Enter the first string");

String fs = [Link]();

[Link]("Enter the second string");


String sec = [Link]();

if([Link]()!=[Link]()){

[Link]("Length of the strings "+fs+" and "+sec+" does not match");

return;

}else if(!check(fs) && !check(sec)){

[Link](fs+" and "+sec+" contains invalid symbols");

return;

}else if(!check(fs)){

[Link](fs+" contains invalid symbols");

return;

}else if (!check(sec)){
[Link](sec+" contains invalid symbols");

return;

}else{

StringBuilder sb =new StringBuilder();

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

char ch1 =[Link](i);

char ch2 =[Link](i);

if(ch1=='!' && [Link](ch2)){

[Link](ch2);

}else{

[Link](ch1);
}

[Link](sb);

public static boolean check (String str){

for(char ch:[Link]()){

if(![Link](ch) && ch!='!' && ch!=' '){

return false;

return true;
}
}

28. Fishing competition

import [Link];

public class UserInterface


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

Scanner sc =new Scanner([Link]);


//Fill the code
[Link]("Enter the details");

String st = [Link]();

String[] str = [Link](":");

String name =str[0];

int age = [Link] (str[1]);

if(age<18){

[Link](age+" is an invalid age");

return;

int bf = [Link] (str[2]) ;

int mf = [Link](str[3]);

int sf =[Link] (str[4]) ;

if(bf<0){

[Link](bf+" is an invalid input");

return;

if(mf<0){

[Link] (mf+" is an invalid input");

return;

if(sf<0){

[Link](sf+" is an invalid input");


return;

}
int cal =bf*10+mf*6+sf*3;
[Link](name+" scored "+cal+" points");

29. Employee ID Generation

import [Link];

public class UserInterface


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

Scanner sc =new Scanner([Link]);


//Fill the code
[Link]("Enter the training id");

String str =[Link]();

if([Link]()<9 || [Link]()>9){

[Link](str+" is an invalid training id");

return;

int year =[Link]([Link](0,4));

if(year!=2021){
[Link](year+" is an invalid year");

return;

String streams =[Link](4,6);

int stream = [Link](streams);

if(stream<1 || stream>5){

[Link](streams+" is an invalid team code");

return;
}

String rr =[Link](6);

int roll =[Link](rr);

if(roll<1 || roll>999){

[Link](rr+" is an invalid roll number");

return;

String code="";

if(stream ==1){

code ="LP";

}else if(stream==2){

code = "TA";

}else if(stream==3){

code ="CT";
}else if(stream==4){

code ="PT";

}else if(stream==5){

code = "TT";

[Link]("Employee Id:"+" SIET"+code+rr);

30. Swap and Reverse

import [Link];

public class UserInterface


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

Scanner sc =new Scanner([Link]);


//Fill the code
[Link]("Enter the sentence");

String st =[Link]();

String[] str = [Link](" ");

if([Link]<=2){
[Link]("Invalid Length");

return;

String res = "";

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

if(!check(str[i])){

[Link](st+" is an invalid sentence");

return;

if(i!=0 && i!=[Link]-1){

String rev="";

for(char ch:str[i].toCharArray()){

rev = ch+rev;

res = rev+" "+res;

[Link](str[[Link]-1]+" "+res+str[0]);

public static boolean check(String st){

for(char ch: [Link]()){

if(![Link](ch)){
return false;
}
}
return true;

31. Profile Update

import [Link];
public class UserInterface
{
public static void main(String[] args)
{
Scanner sc=new Scanner([Link]);
//Fill code here
[Link]("Enter your name");
String name = [Link]();
[Link]("Enter your PAN number");
String pan = [Link]();
if(!validPan(pan)){
[Link](pan+" is an invalid PAN number");
return;
}
[Link]("Enter your E-mail ID");
String email = [Link]();
if(!validEmail(email)){
[Link]("Invalid E-mail ID");
return;
}
[Link]("Profile of "+name+" updated successfully");
}
public static boolean validPan(String pan){
return [Link]("[A-Z]{5}[0-9]{4}[A-Z]");
}
public static boolean validEmail(String email){
return [Link]("[a-z]{5,10}@[Link]");
}
}

32. Event ID Validation

import [Link];
public class UserInterface
{
public static void main(String[] args)
{
Scanner sc=new Scanner([Link]);
//Fill code here
[Link]("Enter your name");
String name = [Link]();
[Link]("Enter your ID");
String id = [Link]();
if(!valid(id)){
[Link](id+" is an invalid ID");
}else{
int seat = [Link]([Link](3,6));
int time = [Link]([Link](6,8));
String std = [Link](8);

[Link]("Hi "+name+" your seat number is "+seat+" and the event


starts at "+time+""+std);
return;
}
}
public static boolean valid(String id){
return [Link]("SPC\\d{3}(0[1-9]|1[0-2])(AM|PM)");
}
}

33. Password Validator

import [Link];
public class UserInterface
{
public static void main(String[] args)
{
Scanner sc=new Scanner([Link]);
//Fill code here
[Link]("Generate your password");
String pass = [Link]();
if(!isValid(pass)){
[Link](pass+" is an invalid password");
return;
}else{
int lc=0,up=0,ss=0,dg=0;
for(char ch:[Link]()){
if([Link](ch)){
lc++;
}else if([Link](ch)){
up++;
}else if("@$#*".indexOf(ch)!=-1){
ss++;
}else if([Link](ch)){
dg++;
}
}
[Link]("The Generated password "+pass+" is valid and has "+lc+"
lowercase alphabet "+up+" uppercase alphabet "+ss+" special character "+dg+" digit");
return;
}
}
public static boolean isValid(String pass){
return [Link]()>=6 && [Link]()<=12 && containsLUDS(pass);
}
public static boolean containsLUDS(String pass){
boolean f1 = [Link](".*[a-z].*");
boolean f2 = [Link](".*[A-Z].*");
boolean f3 = [Link](".*[@$*#].*");
boolean f4 = [Link](".*\\d.*");

return f1 && f2 && f3 && f4;


}
}

<---------------------------------------- The End ---------------------------------------------------->

Common questions

Powered by AI

The programs demonstrate varying effectiveness in handling 'invalid input' scenarios. In 'Profile Update', input validation is rigorously applied using pattern matching to ensure email and PAN formats are correct, providing clear feedback regarding invalid inputs . Similarly, in the 'Magic Sum' program, constraints on input numbers ensure valid entries and outputs immediate feedback on invalid values . However, the 'VolumeCalculator' has a default case for erroneous choices, resulting merely in a general 'Invalid Input' message without specific guidance on the error . Overall, these mechanisms prevent invalid operations and improve user experience, though some programs could benefit from more detailed error messages.

The Java applications use several techniques for input validation to ensure data integrity. For instance, different methods validate input sizes and formats using condition checks and regular expressions. In the 'DonorDetails' example, input types such as age and phone number are strictly typed, with getters and setters ensuring data encapsulation. The 'Profile Update' application uses string pattern matching to validate a PAN number and email address format, ensuring entries follow a specified pattern . These techniques protect against invalid inputs and maintain data consistency.

The 'Prime Number Game' checks the primality of a sum using a basic for-loop iteration. This approach iterates from 2 to n/2, marking the sum as prime if it has no divisors other than 1 and itself . However, this method is suboptimal for large numbers due to its time complexity. An improvement would be implementing a more sophisticated algorithm like the Sieve of Eratosthenes or optimizing with trial division only up to the square root of the number, which significantly reduces execution time making it more efficient, especially with higher numerical inputs.

Method overloading in the 'VolumeCalculator' class is crucial as it allows the program to handle multiple scenarios of calculating volumes using the same method name 'calculateVolume'. The method is overloaded to accept parameters for calculating the volume of both a cylinder and a cuboid. This design provides flexibility and simplicity in usage, allowing the same concept (volume calculation) to be applied to different contexts without changing the method's name . It enhances code readability and reduces the complexity of managing different function names for similar operations.

HashSets are used in the 'Travel Agency' program for storing city names to check bus availability because they provide constant time complexity for lookup operations. This structure is efficient for quickly determining if a requested city is part of the set, minimizing search time compared to a list or array, which would require linear search. The use of HashSet also avoids duplicates, ensuring efficient storage and preventing redundant data checks . This strategy enhances performance in applications requiring fast and repeated membership tests.

The 'Product' class employs constructors and accessor methods effectively to uphold encapsulation, a core object-oriented principle. The constructor initializes the product properties, ensuring that objects are created with valid states . The accessor methods (getters and setters) allow controlled access and modification of these properties, maintaining data integrity by hiding the internal representation from the user. This design pattern protects against unauthorized changes to the product's data and aids in maintaining an internal consistency, enhancing both code safety and flexibility. Overall, these practices demonstrate a strong adherence to encapsulation.

In the 'Calculate Expiry Date' program, Java's SimpleDateFormat and Calendar classes are utilized for parsing and date calculations. Date parsing is done using SimpleDateFormat to convert user-input strings into Date objects, accommodating a non-lenient parsing mode to validate the format strictly . The Calendar class manages the arithmetic calculation, adding months to the manufacturing date to determine the expiry date. These methods ensure accurate and consistent manipulation of dates, handling various edge cases such as month-end transitions seamlessly.

To improve user feedback in the 'Subset' problem when invalid array sizes are entered, it is advisable to implement a loop that continuously prompts the user to re-enter valid sizes instead of terminating the program prematurely. This could involve wrapping the size input in a while-loop that checks if sizes are greater than zero and asks for re-entry upon invalid inputs, displaying an informative message like 'Please enter a positive integer for array size.' This approach would enhance user experience by facilitating correction of errors without needing to restart the program and guide users to the correct input format .

The 'Event ID Validation' program employs a regular expression to ensure the ID format is correct. The regex 'SPC\d{3}(0[1-9]|1[0-2])(AM|PM)' validates IDs by checking for the prefix 'SPC', followed by exactly three digits for the seat number, a valid month number (01 to 12), and a time of day indicator ('AM' or 'PM'). This regex pattern rigorously enforces format adherence, thereby reducing data entry errors and ensuring ID consistency across the application.

The 'Password Validator' enforces multiple criteria to ensure the creation of strong passwords. The program checks whether the password length is between 6 to 12 characters and verifies the inclusion of various character types: at least one lowercase letter, one uppercase letter, one digit, and one special character ('@', '$', '#', '*'). This multi-faceted approach creates passwords that are resilient against simple attacks, ensuring a balance between complexity and memorability, thus enhancing security measures.

You might also like