0% found this document useful (0 votes)
60 views

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
0% found this document useful (0 votes)
60 views

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
You are on page 1/ 47

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

1. Print Message

public class UserInterface {

public static void main(String[] args)


{
//Fill your code here
System.out.println("Thank you for your order");
}

2. Sky Airlines

import java.util.Scanner;
public class UserInterface {

public static void main(String[] args)


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

}
3. Swap two numbers

import java.util.Scanner;

public class UserInterface {

public static void main(String[] args)


{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the numbers");
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println("Before swapping");
System.out.println("first="+a+", second="+b);
a = a^b;
b = a^b;
a = a^b;
System.out.println("After swapping");
System.out.println("first="+a+", second="+b);

4. Oxygen Plants

import java.util.Scanner;
public class UserInterface {
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the length of the room(in m)");
double len = sc.nextInt();
if(len<=0){
System.out.println("Invalid length");
return;
}
System.out.println("Enter the breadth of the room(in m)");
double bre = sc.nextInt();
if(bre<=0){
System.out.println("Invalid breadth");
return;
}
System.out.println("Enter the plant area of a single plant(in cm2)");
double area = sc.nextInt();
if(area<=0){
System.out.println("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 = String.format("%.02f",oxy);


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

5. BMI Calculator

import java.util.Scanner;

public class UserInterface {

public static void main(String[] args)


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

6. Sim Card

import java.util.Scanner;

public class UserInterface{

public static void main(String[] args){

Scanner sc=new Scanner(System.in);

//Fill the code here


System.out.println("Enter the phone number");
long phone = sc.nextLong();
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){
System.out.println("Sum of odd is greater than sum of even");
}
else if(odd<even){
System.out.println("Sum of even is greater than sum of odd");
}
else{
System.out.println("Sum of odd and even are equal");
}

}
}

7. Reverse and Expand

import java.util.Scanner;

public class UserInterface {

public static void main(String[] args)


{
Scanner sc = new Scanner(System.in);
//Fill the code here
System.out.println("Enter the number");
int num = sc.nextInt();
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){
System.out.println(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;
}
System.out.println("Reversed number is "+rev);
System.out.println(res.substring(0,res.length()-1));
}

8. Magic goose

import java.util.Scanner;

public class UserInterface {

public static void main(String[] args)


{
Scanner sc = new Scanner(System.in);
//Fill the code here
int day, var1=0,var2=1;
int[] egg = new int[31];
System.out.println("Enter the day");
day = sc.nextInt();
if(day>30 || day<=0){
System.out.println(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];
}
System.out.println("Number of eggs in "+day+"th day is "+egg[day]);
}

9. Lottery Winner

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

10. Ludo King

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

11. Student Details - Constructor

File 1. Student.java

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. UserInterface.java

import java.util.Scanner;
public class UserInterface {

public static void main(String[] arg)


{
// Fill the code
Scanner sc = new Scanner(System.in);
int flag;
String cname="";
System.out.println("Enter Student's Id:");
int sid=sc.nextInt();
sc.nextLine();
System.out.println("Enter Student's Name:");
String sname=sc.nextLine();
System.out.println("Enter Student's address:");
String sadd = sc.nextLine();
while(true){
System.out.println("Whether the student is from NIT(Yes/No):");
String check=sc.nextLine();
if(check.equalsIgnoreCase("yes")){
flag=1;
break;
}
else{
if(check.equalsIgnoreCase("no")){
flag=0;
System.out.println("Enter the college name:");
cname = sc.nextLine();
break;
}
else
System.out.println("Wrong input");
}
}
if(flag==1){
Student s = new Student(sid,sname,sadd);
System.out.println("Student id:"+s.getStudentId());
System.out.println("Student name:"+s.getStudentName());
System.out.println("Address:"+s.getStudentAddress());
System.out.println("College name:"+s.getCollegeName());
}
else{
Student s = new Student(sid,sname,sadd,cname);
System.out.println("Student id:"+s.getStudentId());
System.out.println("Student name:"+s.getStudentName());
System.out.println("Address:"+s.getStudentAddress());
System.out.println("College name:"+s.getCollegeName());
}
}
}

12. Volume calculator- Over Loading

File 1. UserInterface.java

import java.util.Scanner;
public class UserInterface {

public static void main(String[] arg)


{
// Fill the code
VolumeCalculator vc = new VolumeCalculator();
Scanner sc=new Scanner(System.in);
System.out.println("Enter the choice");
System.out.println("1.Find Volume For Cylinder\n2.Find Volume For Cuboid");
int choice= sc.nextInt();
switch(choice){
case 1:
{
System.out.println("Enter the radius");
double r=sc.nextDouble();
System.out.println("Enter the height");
double h = sc.nextDouble();
System.out.println("Volume of the Cylinder is
"+String.format("%.2f",vc.calculateVolume(r,h)));
break;
}
case 2:
{
System.out.println("Enter the length");
int l = sc.nextInt();
System.out.println("Enter the breadth");
int b = sc.nextInt();
System.out.println("Enter the height");
int h = sc.nextInt();
System.out.println("Volume of the Cuboid is
"+String.format("%.2f",vc.calculateVolume(l,b,h)));
break;
}
default:
System.out.println("Invalid Input");
break;

}
}
}

File 2. VolumeCalculator.java

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. DonorDetails.java

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){
this.name=name;
}
public void setAge(int name){
this.age=age;
}
public void setGender(String gen){
this.gender=gen;
}
public void setBloodGroup(String bg){
this.bloodGroup=bg;
}
public void setPhoneNumber(long no){
this.phoneNumber=no;
}
public String getName(){
return this.name;
}
public int getAge(){
return this.age;
}
public String getGender(){
return this.gender;
}
public String getBloodGroup(){
return this.bloodGroup;
}
public long getPhoneNumber(){
return this.phoneNumber;
}
public DonorDetails(String name, int age, String gender, String bloodGroup, long
phoneNumber){
this.name = name;
this.age = age;
this.gender = gender;
this.bloodGroup = bloodGroup;
this.phoneNumber = phoneNumber;
}

File 2. UserInterface.java

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

Scanner sc =new Scanner(System.in);


//Fill the code
System.out.println("Enter the name");
String name = sc.nextLine();
System.out.println("Enter the age");
int age = sc.nextInt();
sc.nextLine();
System.out.println("Enter the gender");
String gender = sc.nextLine();
System.out.println("Enter the blood group");
String bloodGroup = sc.nextLine();
System.out.println("Enter the phone no");
long phoneNumber = sc.nextLong();
DonorDetails d = new DonorDetails(name,age,gender,bloodGroup,phoneNumber);
System.out.println("Name:"+name);
System.out.println("Age:"+age);
System.out.println("Gender:"+gender);
System.out.println("Blood group:"+bloodGroup);
System.out.println("Phone no:"+phoneNumber);
}

14. Movie Ticket – Static

File 1. Ticket.java

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){


this.ticketid=ticketid;
}

public int getPrice(){


return price;
}

public void setPrice(int price){


this.price=price;
}

public static void setAvailableTickets(int availableTickets){


Ticket.availableTickets=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. UserInterface.java

import java.util.Scanner;
public class UserInterface {

public static void main(String[] arg)


{
// Fill the code
Scanner sc=new Scanner(System.in);
System.out.println("Enter movie name");
String movieName=sc.nextLine();

System.out.println("Enter no of bookings");
int numberOfBookings=sc.nextInt();

System.out.println("Enter the available tickets");


int availableTickets=sc.nextInt();
Ticket.setAvailableTickets(availableTickets);

for(int i=0;i<numberOfBookings;i++){
Ticket ticket=new Ticket();
System.out.println("Enter the ticketid");
int ticketId=sc.nextInt();
ticket.setTicketid(ticketId);

System.out.println("Enter the price");


int price=sc.nextInt();
ticket.setPrice(price);

System.out.println("Enter the no of tickets");


int numberOfTickets=sc.nextInt();

System.out.println("Available Tickets: "+Ticket.getAvailableTickets());

int totalAmount=ticket.calculateTicketCost(numberOfTickets);

if(totalAmount==-1){
System.out.println("Tickets are not available");

}else if(Ticket.getAvailableTickets()==0){
System.out.println("Total amount: "+totalAmount);
System.out.println("House Full");
return;
}
else{
System.out.println("Total amount: "+totalAmount);
System.out.println("Available ticket after booking: "+Ticket.getAvailableTickets());

}
}
if(Ticket.getAvailableTickets()==0){
System.out.println("House full");
}

}
}

15. Date Validation - Use SimpleDateFormat


import java.util.Scanner;
import java.text.SimpleDateFormat;
import java.text.ParseException;

public class UserInterface {

public static void main(String[] args) {


Scanner sc=new Scanner(System.in);

//FILL THE CODE


System.out.println("Enter the date");
String date = sc.nextLine();
if(!valid(date)){
System.out.println(date+" is not a valid date");
return;
}
if(date.length()!=10){
System.out.println(date+" is not a valid date");
}
if(date.charAt(2)!='/'&& date.charAt(5)!='/'){
System.out.println(date+" is not a valid date");
return;
}
String[] str = date.split("/");
if(str.length!=3){
System.out.println(date+" is not a valid date");
return;
}
int curr = Integer.parseInt(str[0]);
int months = Integer.parseInt(str[1]);
int year = Integer.parseInt(str[2]);

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


if(months==2 && curr <=29){
if(curr ==29){
if(check(year)){
System.out.println(date+" is a valid date");
return;
}else{
System.out.println(date+" is not a valid date");
return;
}
}else{
System.out.println(date+" is a valid date");
return;
}

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


if(curr<=30 && curr>0){
System.out.println(date+" is a valid date");
return;
}else{
System.out.println(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){
System.out.println(date+ " is a valid date");
return;
}else{
System.out.println(date+" is not a valid date");
return;
}
}
}else{
System.out.println(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");
dateFormat.setLenient(false);
try{
dateFormat.parse(date);
return true;
}catch(ParseException e){
return false;
}
}
}

16. Calculate Expiry Date - Use Calendar

import java.util.Scanner;
import java.util.Calendar;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.ParseException;

public class UserInterface {

public static void main(String[] args) {


Scanner sc=new Scanner(System.in);

//FILL THE CODE


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

}
public static Date parseDate(String dateStr) throws ParseException{
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
dateFormat.setLenient(false);
return dateFormat.parse(dateStr);
}
public static Date calculateExpDate(Date mfd, int months){
Calendar calendar = Calendar.getInstance();
calendar.setTime(mfd);
calendar.add(Calendar.MONTH,months);
return calendar.getTime();
}
}

17. Sum of Max

import java.util.Scanner;

public class UserInterface{

public static void main(String[] args){

Scanner sc=new Scanner(System.in);

//Fill the code here


System.out.println("Enter the array size");
int n = sc.nextInt();
if(n%2==1){
System.out.println(n+" is an odd number. Please enter even number.");
}
else if(n<=0){
System.out.println(n+" is an invalid array size.");
}else{
int[] arr= new int[n];
System.out.println("Enter the number");
for(int i=0; i<n; i++){
arr[i] = sc.nextInt();
}
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;
}
}
System.out.println("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 java.util.*;

public class UserInterface{

public static void main(String[] args){

Scanner sc=new Scanner(System.in);

//Fill the code here


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

19. Prime Number Game

import java.util.Scanner;

public class UserInterface {


public static void main(String[]args)
{
Scanner sc=new Scanner(System.in);
//Fill the code here
System.out.println("Enter the size of first array");
int n1 = sc.nextInt();
if(n1<=0){
System.out.println(n1+" is an invalid array size");
return;
}
System.out.println("Enter the array elements");
int[] arr = new int[n1];
for(int i = 0; i<n1; i++){
arr[i] = sc.nextInt();
if(arr[i]<0){
System.out.println(arr[i]+" is an invalid input");
return;
}
}
System.out.println("Enter the size of second array");
int n2 = sc.nextInt();
if(n2<=0){
System.out.println(n2+" is an invalid array size");
return;
}
if(n2!=n1){
System.out.println("Both array size is different");
return;
}
System.out.println("Enter the array elements");
int sum = 0;
for(int i = 0; i <n2;i++){
int val = sc.nextInt();
arr[i]=arr[i]+val;
sum+=arr[i]%10;
if(val<0){
System.out.println(val+" is an invalid input");
return;
}
}
if(isPrime(sum)==false){
System.out.println(sum+" is a prime number");
}else{
System.out.println(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 java.util.*;
public class UserInterface{

public static void main(String[] args){

Scanner sc=new Scanner(System.in);

//Fill the code here


System.out.println("Enter the array size");
int num = sc.nextInt();
if(num<1 || num>5){
System.out.println(num+" is an invalid array size");
return;
}
System.out.println("Enter the numbers");
List<Integer> res=new ArrayList<>();
int[] arr= new int[num];
for(int i = 0; i < num; i++){
arr[i] = sc.nextInt();
if(arr[i]<=0 || arr[i]>=100){
System.out.println(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){
res.add(sum);
break;
}
if(val>sum){
break;
}
}
}
}
if(res.size()!= 0){
System.out.println("The sum of prime numbers is");
for(int ele:res){
System.out.println(ele);
}
}else{
System.out.println("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 java.util.*;

public class UserInterface{

public static void main(String[] args){

Scanner sc=new Scanner(System.in);

//Fill the code here


System.out.println("Enter the total number of PIN numbers");
int n = sc.nextInt();
if(n<=0){
System.out.println(n+" is an invalid number");
return;
}
int[] arr = new int[n];
System.out.println("Enter the PIN numbers");
for(int i = 0; i <n; i++){
arr[i] = sc.nextInt();
int temp = arr[i];
int cnt=0;
while(temp>0){
cnt++;
temp/=10;
}
if(cnt!=4){
System.out.println(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)){
res.add(arr[i]);
}
}
if(res.size()!=0){
System.out.println("Valid PIN numbers are");
for(int ele:res){
System.out.println(ele);
}
}else{
System.out.println("All these "+n+" numbers are not a valid PIN number");
}

}
}
22. Two arrays game

import java.util.Scanner;

public class UserInterface{

public static void main(String[] args){

Scanner sc=new Scanner(System.in);

//Fill the code here


System.out.println("Enter the size for the first array");
int n = sc.nextInt();
if(n<=0){
System.out.println(n+" is an invalid array size");
return;
}
System.out.println("Enter the elements for the first array");
int[] arr = new int[n];
for(int i = 0; i < n; i++){
arr[i] = sc.nextInt();
}
System.out.println("Enter the size for the second array");
int m = sc.nextInt();
if(m<=0){
System.out.println(m+" is an invalid array size");
return;
}
System.out.println("Enter the elements for the second array");
int[] arrm = new int[m];
for(int i =0; i<m;i++){
arrm[i] = sc.nextInt();
}
if(n!=m){
System.out.println("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];
}
}
System.out.println("The elements of the third array");
for(int i = 0; i < n; i++){
System.out.println(arr[i]);
}
}
}

23. Simple Addition - Varargs

// Don't Change the Structure

import java.util.Scanner;

public class UserInterface


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

//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;
System.out.println("Number of arguments is "+a.length);
for(int ele:a){
sum+=ele;
}
System.out.println("Total "+sum);
return sum;
}
}

24. Happy Mart - Arrays Class

File 1. Product.java

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){
this.productId=productId;
this.productName=productName;
this.price=price;
}

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

File 2. SortById.java

import java.util.Comparator;

public class SortById implements Comparator<Product> {


public int compare(Product a, Product b){
return a.productId - b.productId;
}
}

File 3. SortByPrice.java

import java.util.Comparator;
public class SortByPrice implements Comparator<Product> {
public int compare(Product a, Product b){
return (int) (a.price - b.price);
}
}

File 4. UserInterface.java

import java.util.Arrays;
import java.util.Scanner;

public class UserInterface {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);


// Fill the code here
System.out.println("Enter the products count");
int productCount = sc.nextInt();
if(productCount <= 0){
System.out.println("Invalid count");
return;
}

Product[] products = new Product[productCount];


System.out.println("Enter Product details");
for(int i = 0; i < productCount; i++){
String[] productDetails = sc.next().split(":");
int productId = Integer.parseInt(productDetails[0]);
String productName = productDetails[1];
double price = Double.parseDouble(productDetails[2]);
products[i] = new Product(productId, productName, price);
}
System.out.println("1.Sort By Id\n2. Sort By Price\nEnter your choice");
int choice = sc.nextInt();
if(choice==1){
Arrays.sort(products, new SortById());
System.out.println("After Sorting By Id");
}else if(choice ==2){
Arrays.sort(products, new SortByPrice());
System.out.println("After Sorting By Price");
}else{
System.out.println("Invalid choice");
return;
}
for(Product product : products){
System.out.println(product);
}
}

25. Resort booking

import java.util.Scanner;
public class UserInterface {
public static void main(String args[])
{
//fill the code here
Scanner sc=new Scanner(System.in);
System.out.println("Enter the customer details");

String input =sc.next();

String[] str =input.split(":");

String name = str[0];

int ad = Integer.parseInt(str[1]);

int ch =Integer.parseInt(str[2]);

int d =Integer.parseInt(str[3]);

if(ad<0){

System.out.println("Invalid input for number of adults");

return;

}else if(ch<0){

System.out.println("Invalid input for number of children");

return;

}else if(d<=0){

System.out.println("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;


System.out.println(name+" your booking is confirmed and the total cost is "+total);

26. Travel Agency

import java.util.*;

public class UserInterface{

public static void main(String[] args){

Scanner sc=new Scanner(System.in);

//Fill the code here


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

set.add("chennai");

set.add("coimbatore");

set.add("erode");

set.add("karur");

set.add("madurai");

set.add("hyderabad");

set.add("salem");

set.add("bangalore");

set.add("delhi");
set.add("agra");

System.out.println("Enter the city name");

String str = sc.next();

String ch = str.toLowerCase();

if(set.contains(ch)){

System.out.println("Bus for "+str+" is available");


return;

}else{

System.out.println("Bus for "+str+" is not available");

return;

}
}

27. Complete the Caption

import java.util.Scanner;
public class UserInterface {
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
//fill the code here
System.out.println("Enter the first string");

String fs = sc.nextLine();

System.out.println("Enter the second string");


String sec = sc.nextLine();

if(sec.length()!=fs.length()){

System.out.println("Length of the strings "+fs+" and "+sec+" does not match");

return;

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

System.out.println(fs+" and "+sec+" contains invalid symbols");

return;

}else if(!check(fs)){

System.out.println(fs+" contains invalid symbols");

return;

}else if (!check(sec)){
System.out.println(sec+" contains invalid symbols");

return;

}else{

StringBuilder sb =new StringBuilder();

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

char ch1 =fs.charAt(i);

char ch2 =sec.charAt(i);

if(ch1=='!' && Character.isAlphabetic(ch2)){

sb.append(ch2);

}else{

sb.append(ch1);
}

System.out.println(sb);

public static boolean check (String str){

for(char ch:str.toCharArray()){

if(!Character.isLetterOrDigit(ch) && ch!='!' && ch!=' '){

return false;

return true;
}
}

28. Fishing competition

import java.util.Scanner;

public class UserInterface


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

Scanner sc =new Scanner(System.in);


//Fill the code
System.out.println("Enter the details");

String st = sc.nextLine();

String[] str = st.split(":");

String name =str[0];

int age = Integer.parseInt (str[1]);

if(age<18){

System.out.println(age+" is an invalid age");

return;

int bf = Integer.parseInt (str[2]) ;

int mf = Integer.parseInt(str[3]);

int sf =Integer.parseInt (str[4]) ;

if(bf<0){

System.out.println(bf+" is an invalid input");

return;

if(mf<0){

System.out.println (mf+" is an invalid input");

return;

if(sf<0){

System.out.println(sf+" is an invalid input");


return;

}
int cal =bf*10+mf*6+sf*3;
System.out.println(name+" scored "+cal+" points");

29. Employee ID Generation

import java.util.Scanner;

public class UserInterface


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

Scanner sc =new Scanner(System.in);


//Fill the code
System.out.println("Enter the training id");

String str =sc.nextLine();

if(str.length()<9 || str.length()>9){

System.out.println(str+" is an invalid training id");

return;

int year =Integer.parseInt(str.substring(0,4));

if(year!=2021){
System.out.println(year+" is an invalid year");

return;

String streams =str.substring(4,6);

int stream = Integer.parseInt(streams);

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

System.out.println(streams+" is an invalid team code");

return;
}

String rr =str.substring(6);

int roll =Integer.parseInt(rr);

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

System.out.println(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";

System.out.println("Employee Id:"+" SIET"+code+rr);

30. Swap and Reverse

import java.util.Scanner;

public class UserInterface


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

Scanner sc =new Scanner(System.in);


//Fill the code
System.out.println("Enter the sentence");

String st =sc.nextLine();

String[] str = st.split(" ");

if(str.length<=2){
System.out.println("Invalid Length");

return;

String res = "";

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

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

System.out.println(st+" is an invalid sentence");

return;

if(i!=0 && i!=str.length-1){

String rev="";

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

rev = ch+rev;

res = rev+" "+res;

System.out.println(str[str.length-1]+" "+res+str[0]);

public static boolean check(String st){

for(char ch: st.toCharArray()){

if(!Character.isLetter(ch)){
return false;
}
}
return true;

31. Profile Update

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

32. Event ID Validation

import java.util.Scanner;
public class UserInterface
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
//Fill code here
System.out.println("Enter your name");
String name = sc.nextLine();
System.out.println("Enter your ID");
String id = sc.nextLine();
if(!valid(id)){
System.out.println(id+" is an invalid ID");
}else{
int seat = Integer.parseInt(id.substring(3,6));
int time = Integer.parseInt(id.substring(6,8));
String std = id.substring(8);

System.out.println("Hi "+name+" your seat number is "+seat+" and the event


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

33. Password Validator

import java.util.Scanner;
public class UserInterface
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
//Fill code here
System.out.println("Generate your password");
String pass = sc.nextLine();
if(!isValid(pass)){
System.out.println(pass+" is an invalid password");
return;
}else{
int lc=0,up=0,ss=0,dg=0;
for(char ch:pass.toCharArray()){
if(Character.isLowerCase(ch)){
lc++;
}else if(Character.isUpperCase(ch)){
up++;
}else if("@$#*".indexOf(ch)!=-1){
ss++;
}else if(Character.isDigit(ch)){
dg++;
}
}
System.out.println("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 pass.length()>=6 && pass.length()<=12 && containsLUDS(pass);
}
public static boolean containsLUDS(String pass){
boolean f1 = pass.matches(".*[a-z].*");
boolean f2 = pass.matches(".*[A-Z].*");
boolean f3 = pass.matches(".*[@$*#].*");
boolean f4 = pass.matches(".*\\d.*");

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


}
}

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

You might also like