0% found this document useful (0 votes)
114 views47 pages

Solutions For Java Practice Coding

The document describes a Java coding practice problem to convert temperatures between Fahrenheit and Celsius and determine temperature levels based on array sums. It provides the class structures, method signatures, and sample inputs/outputs. The solution code implements the Utility class with the specified methods to perform the conversions and level determination. It also implements the main method to take user input and call the appropriate Utility method.

Uploaded by

Akkina Sowmya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
114 views47 pages

Solutions For Java Practice Coding

The document describes a Java coding practice problem to convert temperatures between Fahrenheit and Celsius and determine temperature levels based on array sums. It provides the class structures, method signatures, and sample inputs/outputs. The solution code implements the Utility class with the specified methods to perform the conversions and level determination. It also implements the main method to take user input and call the appropriate Utility method.

Uploaded by

Akkina Sowmya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 47

Solutions for Java Practice Coding

Q1.Fahrenheit to Celsius

Complete the static methods in the class Utility as per following requirements

Option 1 : Method fahrenheitToCelcius :

This method should convert farhenheit in to celcius based on the formula [celcius =

(farhenheit - 32) X 5 / 9]

The method takes farhenheit(double) as input parameter

Method should return calculated temperature celcius rounded to an integer

Option 2 : Method getLevel :

Takes an integer array as input parameter

Should calculate the sum of all array elements and return a String as per below rules

HIGH - when sum is greater than or equal to 100, MEDIUM - when sum is greater than or

equal to 70, LOW - when sum is less than 70

Complete the main method in class Source as below

Program should take console input and call appropriate methods of Utility class based on the

Input.

Input and Output sample formats are given below in Example section

First input should be option 1 or 2.

Option 1 is for Celcius calculation

Option 2 for finding Level

In case of option 1, the second input should be temperature in farhenheit

In case of option 2, the second input should be number of elements in the array, followed by

the array elements In case of incorrect option, program should display 'Invalid Option'

Methods Of Utility Class:

public static String getLevel(int[] arr){}

public static int fahrenheitToCelcius(double farhenheit) {}


Example

Sample Input:
1 // Option
100 // temperature in Farhenheit
Expected Output:
38
Sample Input:
1
95.5
Expected Output:
35
Sample Input:
2 // option
3 // number of elements in array
40 // array elements
50 // array elements
11 // array elements
Expected Output:
HIGH
Sample Input:
2
4
10
20
5
10
Expected Output:
LOW

Solution:

import java.lang.Math;

import java.util.Scanner;

class Utility {

public static int fahrenheitToCelcius(double farhenheit) {

int celcius;

celcius=(int)Math.round(((farhenheit-32)*5)/9);
return celcius;

public static String getLevel(int[] array) {

int sum=0,i;

for(i=0;i<array.length;i++)

sum+=array[i];

if(sum>=100)

return "HIGH";

else if(sum>=70 && sum<100)

return "MEDIUM";

else if(sum<70)

return "LOW";

else

return null;

//CODE END

public class Source {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

int choice=scan.nextInt();

switch(choice)

case 1:double farhenheit;

farhenheit=scan.nextDouble();

Utility u1=new Utility();

System.out.println(u1.fahrenheitToCelcius(farhenheit));

break;
case 2:int n,i;

n=scan.nextInt();

int ar[]=new int[n];

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

ar[i]=scan.nextInt();

Utility u2=new Utility();

System.out.println(u2.getLevel(ar));

break;

default:

System.out.println("Invalid Option");

break;

scan.close();

*****************************************************************************
Q2.Prime Larger

Write a Java program that accepts two integer values from the user and prints the larger

value if both the values are prime numbers otherwise it prints smaller value and

it prints 0 if both the values are same.

Example:

Sample Input:
5
11
Expected Output:
11

Sample Input:
5
16
Expected output:
5

Sample Input:
5
5
Expected output:
0

Solution:

import java.util.Scanner;

public class Source {

public static void main(String[] args) {

// TODO Auto-generated method stub

Scanner in = new Scanner(System.in);

int result=-1;

int a = in.nextInt();

int b = in.nextInt();

if(a == b){

result=0;

}
else if(isPrime(a) & isPrime(b)) {

if(a>b)

result=a;

else

result=b;

else

if(a>b){

result=b;

else

result=a;

System.out.println(result);

public static boolean isPrime(int num){

boolean flag=true;

for(int i = 2; i <= num/2; ++i)

// condition for nonprime number

if(num % i == 0) {

flag = false;
break;

return flag;

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

Q3.Count HR Designations

Write a program which accepts designations in an String array.


Check the given array elements contain “HR” and display the total number of elements
which contains “HR” and display the elements in upper case also.
Display the message as given in Expected output.

Example:

Sample Input:
4
HRExecutive
Accountant
HRManager
SalesMan

Expected output:
Total 2 designations in HR Department
HREXECUTIVE
HRMANAGER

Sample Input:
2
Operator
Programmer

Expected output:
No designation of HR department found in given data

Sample Input:
-2
Operator
Programmer

Expected output:
INVALID INPUT
Solution:

import java.util.Scanner;

public class Source {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

int no = scanner.nextInt();

if(no>0){

int count=0;

String designations[]=new String[no];

String input[] = new String[no];

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

input[i] = scanner.next();

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

if(input[i].contains("HR")){

designations[count]=input[i];

count++;

if(count>0)

System.out.println("Total "+ count +" designations in HR


Department");

for(int j=0;j<count;j++)

System.out.println(designations[j].toUpperCase());
}

else

System.out.println("No designation of HR department found in


given data");

else {

System.out.println("INVALID INPUT");

Q4. Engineering Student

Write code in given class Student which has private attributes:

studentId : int

studentName : String

college: String

with the method getDetails() to display the attributes.

Write code in another given class EngineeringStudent which should inherit Student class

and have to override getDetails() with additional information stream to be displayed.

stream : String

Accept the input from the user to create Student or EngineeringStudent object and display

the details using getDetails method. Other then "Student " or "EngineeringStudent" input, it

must display "Invalid Input".

Example

Sample Input:
Student
111
Ram
National College

Expected output:
Student ID: 111
Student Name: Ram
College: National College

Sample Input:
EngineeringStudent
123
Ananya
IIT
Computer

Expected output:
Student ID: 123
Student Name: Ananya
College: IIT
Stream: Computer

Sample Input:
Trainer

Expected output:
Invalid Input

Solution:

import java.util.Scanner;

class Student {

private int studentId;

private String studentName;

private String college;

public Student(int studentId, String studentName, String college) {

super();

this.studentId = studentId;

this.studentName = studentName;

this.college = college;

}
public int getStudentId() {

return studentId;

public void setStudentId(int studentId) {

this.studentId = studentId;

public String getStudentName() {

return studentName;

public void setStudentName(String studentName) {

this.studentName = studentName;

public String getCollege() {

return college;

public void setCollege(String college) {

this.college = college;

public void getDetails() {

System.out.println("Student ID: " + studentId);

System.out.println("Student Name: " + studentName);

System.out.println("College: " + college);

class EngineeringStudent extends Student {

private String stream;

public EngineeringStudent(int studentId, String studentName, String college, String stream) {


super(studentId, studentName, college);

this.stream = stream;

public String getStream() {

return stream;

public void setStream(String stream) {

this.stream = stream;

public void getDetails() {

super.getDetails();

System.out.println("Stream: " + stream);

public class Source {

public static void main(String args[]) {

Scanner scanner = new Scanner(System.in);

String object = scanner.nextLine();

Student Student = null;

if (object.equals("EngineeringStudent")) {

int studentId = scanner.nextInt();

scanner.nextLine();

String studentName = scanner.next();

scanner.nextLine();

String college = scanner.nextLine();

String stream = scanner.nextLine();

Student=new EngineeringStudent(studentId, studentName, college, stream);

Student.getDetails();

} else if (object.equals("Student")){
int studentId = scanner.nextInt();

scanner.nextLine();

String studentName = scanner.next();

scanner.nextLine();

String college = scanner.nextLine();

Student = new Student(studentId, studentName, college);

Student.getDetails();

}else {

System.out.println("Invalid Input");

Q5.RollNumber Validator

Write code in given class Student which has private attributes:

studentId : int

studentName : String

college: String

with the method getDetails() to display the attributes.

Write code in another given class EngineeringStudent which should inherit Student class and have
to override getDetails() with additional information stream to be displayed.

stream : String

Accept the input from the user to create Student or EngineeringStudent object and display the
details using getDetails method.

Other then "Student " or "EngineeringStudent" input, it must display "Invalid Input".

Example

Sample Input:
Student
111
Ram
National College
Expected output:
Student ID: 111
Student Name: Ram
College: National College

Sample Input:
EngineeringStudent
123
Ananya
IIT
Computer

Expected output:
Student ID: 123
Student Name: Ananya
College: IIT
Stream: Computer

Sample Input:
Trainer

Expected output:
Invalid Input

import java.util.Scanner;

class Student {

private int studentId;

private String studentName;

private String college;

public Student(int studentId, String studentName, String college) {

super();

this.studentId = studentId;

this.studentName = studentName;

this.college = college;

public int getStudentId() {

return studentId;
}

public void setStudentId(int studentId) {

this.studentId = studentId;

public String getStudentName() {

return studentName;

public void setStudentName(String studentName) {

this.studentName = studentName;

public String getCollege() {

return college;

public void setCollege(String college) {

this.college = college;

public void getDetails() {

System.out.println("Student ID: " + studentId);

System.out.println("Student Name: " + studentName);

System.out.println("College: " + college);

class EngineeringStudent extends Student {

private String stream;

public EngineeringStudent(int studentId, String studentName, String college, String stream) {

super(studentId, studentName, college);

this.stream = stream;
}

public String getStream() {

return stream;

public void setStream(String stream) {

this.stream = stream;

public void getDetails() {

super.getDetails();

System.out.println("Stream: " + stream);

public class Source {

public static void main(String args[]) {

Scanner scanner = new Scanner(System.in);

String object = scanner.nextLine();

Student Student = null;

if (object.equals("EngineeringStudent")) {

int studentId = scanner.nextInt();

scanner.nextLine();

String studentName = scanner.next();

scanner.nextLine();

String college = scanner.nextLine();

String stream = scanner.nextLine();

Student=new EngineeringStudent(studentId, studentName, college, stream);

Student.getDetails();

} else if (object.equals("Student")){

int studentId = scanner.nextInt();

scanner.nextLine();
String studentName = scanner.next();

scanner.nextLine();

String college = scanner.nextLine();

Student = new Student(studentId, studentName, college);

Student.getDetails();

}else {

System.out.println("Invalid Input");

Q6. Coach Player

Create a java class Coach.Coach's job is to coach the Batsman and Bowler.
Implement loose coupling by introducing an Abstract class Player.
Create both the Batsman and Bowler classes, they must extend Player class.
Player class must have abstract method play() and returns void.
play() : void
Coach class has one private attribute:
player : Player

and two methods :-

setPlayer(Player player) : void - will set Player

coach() : void - will call play() using player object

will print “Batsman is batting”, if Batsman object is passed and “Bowler is bowling”, if Bowler Object
is passed to the setPlayer method.Print "Invalid Input" if other then Batsman or Bowler is given as

Sample Input .
Pass the Batsman object or Bowler object to the setPlayer method and call the coach() method to
print the information.

Example

Sample Input:
Batsman

Expected output:
Batsman is batting

Sample Input:
Bowler

Expected output:
Bowler is bowling

Sample Input:
Umpire

Expected output:
Invalid Input

Solution:

import java.util.Scanner;

class Coach {

private IPlayer worker;

public void setWorker(IPlayer worker){

this.worker = worker;

public void coach() {

worker.play();

interface IPlayer

void play();

class Batsman implements IPlayer{

@Override
public void play() {

System.out.println("Batsman is batting");

class Bowler implements IPlayer{

@Override

public void play() {

System.out.println("Bowler is bowling");

public class Source {

public static void main(String[] args) {

// TODO Auto-generated method stub

Coach Coach = new Coach();

Scanner scanner = new Scanner(System.in);

String type = scanner.next();

if(type.equals("Batsman")) {

Coach.setWorker(new Batsman());

Coach.coach();

}else if(type.equals("Bowler")) {

Coach.setWorker(new Bowler());

Coach.coach();

} else {

System.out.println("Invalid Input");

}
Q7. Search Doctor

Complete the application as per the below design to search for doctors based on speciality/years of
experience.The application consists of 3 classes : Doctor, DoctorService and SearchDoctorApp.
Complete the given classes as below.

class Doctor This pre-written class contains the instance variables: name, speciality and experience,
Getters/Setters, Constructors and overridden toString method. This class may need some changes
based on the requirement.

class DoctorService - Contains an instance variable doctorsRepository of type List<Doctor>, which


can be initialized using the constructor provided. Create the below methods in this class, for
searching doctors from the doctorsRepository List

getExperiencedDoctors(int):List<Doctor>

- This method takes years of experience as input parameter and


returns a List of Doctors, who have experience equal to or more
than the input parameter
- The returned List should be sorted in ascending order of
speciality and descending order of experience for a speciality.
(This should be natural sorting order of Doctor class)

getSpecialityDoctor(String):Set<Doctor>
- This method takes speciality(case insensitive) as input
parameter and returns a Set of Doctors who have this speciality
- The returned Set should be sorted in ascending order of name of
Doctor

class SearchDoctorApp This class contains a static variable doctorsData which is initialized with
details of 9 doctors in the below format.

name-speciality-experience;name-speciality-experience;...

Note: Do not change the data provided in static block

Do the following in the main method

1. Create Doctor objects using the data present in doctorsData variable and add these objects
to a ArrayList of Doctors
2. Initialize the doctorsRepository variable of DoctorService with the above ArrayList
3. Accept 1 or 2 as choice from the user through Console.
4. If choice is 1, accept years of experience as second input. Invoke appropriate method of
DoctorService and display the doctors as per the below format
5. If choice is 2, accept speciality as second input. Invoke appropriate method of DoctorService
and display the doctors as per the below format
6. Display "No Doctors Found", if there are no doctors matching the search criteria
7. Display "Invalid Choice", if the first input is not 1 or 2

Example
Sample Input:
1 10

Expected Output:
Jim Cardiology 25
David Dermatology 15
John Dermatology 10
Amy Pediatrics 16
Mavis Pediatrics 11
Sample Input:
1 30

Expected Output:
No Doctors Found
Sample Input:
2 Cardiology

Expected Output:
Jim Cardiology 25

Solution:

import java.util.Iterator;

import java.util.List;

import java.util.Scanner;

import java.util.Set;

import java.util.TreeSet;

import java.util.ArrayList;

import java.util.Comparator;

import java.util.Collections;

class Doctor implements Comparable {


private String name;

private String speciality;

private int experience;

public Doctor() {

super();

public Doctor(String name, String speciality, int experience) {

super();

this.name = name;

this.speciality = speciality;

this.experience = experience;

@Override

public String toString() {

return String.format("%15s %15s %5d",name,speciality,experience) ;

public String getName() {

return name;

public void setName(String name) {

this.name = name;

public String getSpeciality() {


return speciality;

public void setSpeciality(String speciality) {

this.speciality = speciality;

public int getExperience() {

return experience;

public void setExperience(int experience) {

this.experience = experience;

@Override

public int compareTo(Object o) {

Doctor doc = (Doctor)o;

return name.compareToIgnoreCase(doc.name);

class DoctorService {

//DONT MODIFY THIS

private List<Doctor> doctorsRepository;


//DONT MODIFY THIS

public DoctorService(List<Doctor> doctorsRepository) {

this.doctorsRepository = doctorsRepository;

List<Doctor> getExperiencedDoctors(int exp)

if(doctorsRepository==null||doctorsRepository.isEmpty())

return null;

List<Doctor> res =null;

res= new ArrayList<>();

Iterator itr=doctorsRepository.iterator();

while(itr.hasNext())

Doctor docs=(Doctor)itr.next();

int exp1 = docs.getExperience();

if(exp1>=exp)

res.add(docs);

Collections.sort(res, new Comparator<Doctor>(){

@Override

public int compare(Doctor o1, Doctor o2) {


if(o1.getExperience()>o2.getExperience())

return -1;

else

return 1;

});

Collections.sort(res, new Comparator<Doctor>(){

@Override

public int compare(Doctor o1, Doctor o2) {

return o1.getSpeciality().compareToIgnoreCase(o2.getSpeciality());

});

return res;

Set<Doctor> getSpecialityDoctor(String spec)

if(doctorsRepository==null||doctorsRepository.isEmpty())

return null;

Set <Doctor> res= null;

res= new TreeSet<>();


List<Doctor> res1 =null;

res1= new ArrayList<>();

Iterator itr=doctorsRepository.iterator();

while(itr.hasNext())

Doctor docs=(Doctor)itr.next();

String spec1 = docs.getSpeciality();

if(spec1.equalsIgnoreCase(spec))

res1.add(docs);

Collections.sort(res1);

res.addAll(res1);

return res;

public class Source {

//DON'T MODIFY THIS

private static String doctorsData;

//DON'T MODIFY THIS

static {

StringBuilder doctors = new StringBuilder();


doctors.append("Amy-Pediatrics-16;");

doctors.append("John-Dermatology-10;");

doctors.append("David-Dermatology-15;");

doctors.append("Bob-Pediatrics-6;");

doctors.append("Cathy-Dermatology-5;");

doctors.append("Mavis-Pediatrics-11;");

doctors.append("Robin-Pediatrics-7;");

doctors.append("Minty-Dermatology-9;");

doctors.append("Jim-Cardiology-25;");

doctorsData = doctors.toString();

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

List<Doctor> docs;

docs = new ArrayList<>();

docs.add(new Doctor("Yogesh", "Pediatrics", 25));

docs.add(new Doctor("Ravish", "Pediatrics", 15));

docs.add(new Doctor("Amit", "Pediatrics", 9));

docs.add(new Doctor("Shibin", "Dermatology", 6));

docs.add(new Doctor("Mavis", "Dermatology", 22));

docs.add(new Doctor("Shilpa", "Dermatology", 6));

docs.add(new Doctor("Ghouse", "Cardiology", 25));

docs.add(new Doctor("Sunil", "Cardiology", 15));

docs.add(new Doctor("Manzoor", "Cardiology", 15));

docs.add(new Doctor("Vinay", "Orthopaedics", 22));

docs.add(new Doctor("Kumaresh", "Orthopaedics", 15));

docs.add(new Doctor("Pulikeshi", "Orthopaedics", 6));

List<Doctor> docs1= null;

docs = new ArrayList<>();

Set <Doctor> docs2= null;


docs2= new TreeSet<>();

String arr[]=doctorsData.split(";");

String arr1[] = null;

int n = 3*arr.length;

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

arr1=arr[i].split("-");

int j =0;

docs.add(new Doctor(arr1[j],arr1[j+1],Integer.parseInt(arr1[j+2])));

DoctorService services = new DoctorService(docs);

int choice = scan.nextInt();

if(choice==1)

int exp = scan.nextInt();

docs1=services.getExperiencedDoctors(exp);

if(docs1==null||docs1.isEmpty())

System.out.println("No Doctors Found");

else

Iterator itr2=docs1.iterator();

while(itr2.hasNext())

Doctor st=(Doctor)itr2.next();

System.out.println(st.getName()+" "+st.getSpeciality()+" "+st.getExperience());

}
}

else if(choice==2)

String spec = scan.next();

docs2=services.getSpecialityDoctor(spec);

if(docs2==null||docs2.isEmpty())

System.out.println("No Doctors Found");

else

Iterator itr2=docs2.iterator();

while(itr2.hasNext())

Doctor st=(Doctor)itr2.next();

System.out.println(st.getName()+" "+st.getSpeciality()+" "+st.getExperience());

else

System.out.println("Invalid Choice");

}
Q8. Email Crawler

Create a code which will allow the user to search and email depending upon the word ,this
application will be at the initial stages of implementation further this application would be enhanced
by some more features.

Currently this application will search and display the message if the given word passed has a input is
available in the email or not,if available/unavailable suitable message would be displayed which can
been seen in the sample output provided below.

Following classes are required to be created.

1.Document
2.Email
3.Source--->This would be already available in the coding editor.
Document class members
private String emailText;
toString() ---> will return emailText;

Email class members

Email(String emailText, String sender, String recipient, String title) --->constructor


private String sender;
private String recipient;
private String title;
provide getter/setter for the above members
public String toString() ----> returns the data for all members as shown in below output
Methods in Source Class
static boolean ContainsKeyword(Document docObject, String keyword)----> if this method returns
true print this message--->Email contains the word:questions
and if it returns false print this message ---->Email does not contain the word:codingtest

Sample Input 1:
Manzoor----> From (Sender)
Jagadish---->To (Recipent)
Webinar---->Subject heading
Kindly discuss codeathon related questions in webinar ----->Detailed email message
questions---->---->Word to search in the email message

Sample output 1:
Email contains the word:questions
From:Manzoor
To:Jagadish
Webinar
Kindly discuss codeathon related questions in webinar
Sample Input 2:
Naveen----> From (Sender)
Jagadish----> To (Recipent)
Review------> Subject heading
Kindly re-review the questions for codeathontest----->Detailed email message
codingtest ---->Word to search in the email message

Sample output 2:
Email does not contain the word:codingtest
From:Naveen
To:Jagadish
Review
Kindly re-review the questions for codeathontest

Solution:

import java.util.*;

class Document

private String text;

public Document(String text)

this.text=text;

public String toString()

return text;

class Email extends Document

private String sender;


private String recipient;

private String title;

public Email(String textDoc, String sender, String recipient, String title)

super(textDoc);

this.sender = sender;

this.recipient = recipient;

this.title = title;

public String getSender()

return sender;

public String getRecipient()

return recipient;

public String getTitle()

return title;

public String gettext()

return super.toString();

}
public void setSender(String sender)

this.sender = sender;

public void setRecipient(String recipient)

this.recipient = recipient;

public void setTitle(String title)

this.title =title;

public String toString()

return "From:"+sender+"\nTo:" + recipient+"\n"+title+"\n" + super.toString();

public class Source

public static boolean ContainsKeyword(Document docObject, String keyword)

if (docObject.toString().indexOf(keyword, 0) >= 0)

return true;
return false;

public static void main(String args[])

Scanner s=new Scanner(System.in);

String from=s.next();

String to=s.next();

String subject=s.next();

s.nextLine();

String message=s.nextLine();

String searchword=s.next();

Document email1 = new Email(message,from,to,subject);

if (ContainsKeyword(email1,searchword))

System.out.println("Email contains the word:"+searchword);

else

System.out.println("Email does not contain the word:"+searchword);

System.out.println(email1.toString());

}
Q9. Payments App

Define a abstract class named Payment that contains a method named paymentDetails
which should be declared abstract in this class,that outputs payment details w.r.t to
CreditCardPayment and CashPayment.

Next, define a class named CashPayment that is derived from Payment. This class should
redefine the paymentDetails method to indicate that the payment is in cash. Include
appropriate constructor(s).

Define a class named CreditCardPayment that is derived from Payment. This class should
contain instance variables for the name on the card, expiration date, and credit card number.
Include appropriate constructor(s). Finally, redefine the paymentDetails method to include
all credit card information in the printout.

In the main method create CashPayment and CreditCardPayment objects with different
values and calls paymentDetails for each.

Syntax for the classes required to build this Application

1.CashPayment(double amount,String custname)---> Constructor for CashPayment

2.CreditCardPayment(double amount, String name, String expDate, String cardnumber)---


>Constructor for CreditCardPayment

3.abstract class Payment

Methods of Payment class

public abstract String paymentDetails()---> this method returns the information depending
on the type of Payment (Credit/CashPayment),it has to be redefined or oveririden in
Credit/Cash classes and return the the reuqired sample output data mentioned below.

Note:

1.Payments made by credit card will have 5% discount on the amount

2.Payments made by cash will have 2% discount on the amount

3.Calculate and display the amount after applying discount.


Sample Input 1:
1 ------------> Choice to be entered should be int type
10000 -------->total amount
Ajay -------->Customer Name
12/21 --------->Expiryd Date of the Credit Card
***1234 --------->Credit Card Number

Sample Output 1:
Amount:9500.0CardNo:***1234Validty:12/21Name:Ajay

Sample Input:2
2-------> Choice to be entered should be int type
6500-------> total amount
Ramesh------>customer name

Sample Output 2:
CashPayment:6370.0Customer:Ramesh

Note:
1.6370 is the amount after discount of 2%
2.9500.0 is the amount after discount of 5%
Solution:

mport java.util.*;

abstract class Payment

public abstract String paymentDetails();

class CashPayment extends Payment

String custname;

double amount;

public CashPayment(double amount,String custname)

this.amount=amount;

this.custname=custname;

public double payableAmount()

double tamount=amount*0.02;

return amount-tamount;

public String paymentDetails()

{double totalamount =payableAmount();


return "CashPayment:"+totalamount+"Customer:"+custname;

class CreditCardPayment extends Payment

public String name, expDate, number;

double amount;

public CreditCardPayment(double amount, String name, String expDate, String number)

//super(value);

this.amount=amount;

this.number = number;

this.expDate = expDate;

this.name = name;

public double payableAmount()

double tamount=amount*0.05;

return amount-tamount;

public String paymentDetails()

{
double totalamount =payableAmount();

return"Amount:"+totalamount+"CardNo:"+number+"Validty:"+expDate+"Name:"+name;

public class Source {

public static void main(String[] args) {

// TODO Auto-generated method stub

Scanner s=new Scanner(System.in);

int choice=s.nextInt();

if(choice==1)

double amount=s.nextDouble();

String name=s.next();

String expdate=s.next();

String card=s.next();

CreditCardPayment x = new CreditCardPayment(amount,name,expdate,card);

System.out.println(x.paymentDetails());

else if(choice==2)

double amount=s.nextDouble();

String name=s.next();

CashPayment p = new CashPayment(amount,name);


System.out.println(p.paymentDetails());

Q10. Colour Code Validator

Main class Source should have the functionality to validate the input hexadecimal and decimal
colour codes.

Create two static methods in class ColourCodeValidator as per the below signature

validateHexCode(String):int
validateDecimalCode(String):int

Both the methods return 1 for valid codes and -1 for invalid
codes. Rules for valid codes are given below

Hexadecimal code rules

• Format: #A1BC23
• Must start with "#" symbol
• Must contain six characters after #
• It may contain alphabets from A-F or digits from 0-9

Decimal code rules

• Format: rgb(x,y,z)
• x,y and z are values from 0 to 255 inclusive

In the main method , do the following

• Accept the inputs using Console as shown in the Example section


• First input is choice based on which one of the static methods should be invoked
• choice 1 is for validating the input hexadecimal colour code
• choice 2 is for validating the input decimal colour code
• Display Valid code or Invalid code based on the validation result
• If the choice is neither 1 or 2, display message "Invalid choice"

Example

Sample Input:
1 #ABCDEF
Expected Output:
Valid Code
Sample Input:
2 rgb(9,99,249)

Expected Output:
Valid Code
Sample Input:
9

Expected Output:
Invalid choice

Solution:

import java.util.Scanner;

public class Source {

// CODE HERE

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

// CODE START

int q = sc.nextInt();

if(q==1) {

String n = sc.next();

int u = (Source.validateHexCode(n));

if(u==1)

System.out.println("Valid code");

else

System.out.println("Invalid code");

else if(q==2) {

String j = sc.next();

//System.out.println(j.length());

int y = (Source.validateDecimalCode(j));

if(y==1)
System.out.println("Valid code");

else

System.out.println("Invalid code");

else

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

public static int validateDecimalCode(String r) {

int k = 0,c = 0;

String s2 = r.substring(4, r.length()-1);

char[] chars = s2.toCharArray();

//System.out.println("lenth2: " + s2.length());6

if(r.length()<=16 && r.charAt(0)=='r' && r.charAt(1)=='g' && r.charAt(2)=='b' &&


r.charAt(3)=='(' && r.charAt(r.length()-1)==')' && r.charAt(r.length()-2)!=')'&&
Character.isDigit(r.charAt(4)) )

// Convert char array to String in Java

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

chars[i]= s2.charAt(i);

char a = s2.charAt(i);

if(a ==',') {

int m = i;

String string = s2.substring(k,m);

k=m+1;

//System.out.println(string);

int result = Integer.parseInt(string);

if(result >= 0 && result <= 255)

c++;

}
}

String string1 = s2.substring(k,s2.length());

//System.out.println(string1);

int result = Integer.parseInt(string1);

if(result >= 0 && result <= 255)

c++;

//System.out.println(c);

if(c==3)

return 1;

else

return -1;

public static int validateHexCode(String s){

int c= 0;

// System.out.println(s.length());

if(s.length()== 7 && s.charAt(0) == '#') {

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

if((s.charAt(i)>='A' && s.charAt(i)<='F')||


Character.isDigit(s.charAt(i))) {

c = 1;

break;

if(c==1)

return 1;
else

return -1;

Q11. Code-Exception

1. Create a Custom Exception "DivisionByZeroException" this exception should be thrown if a


number is been divided by zero.

2.The code should also handle InputMismatchException ,if the input is not a numerical value that is
read by the Scanner class.

3.The InputMismatchException is from java.util. package,need not to create this exception,its a


predifined exception

4.If the inputs are right then it should display the result.

Sample Input 1:
10 -----------> Input 1
R -----------> Input 2
Sample Output 1:
ERROR501 ---->Note this message should be issued from the constructor of custom exception class

Sample Input 2:
10 -----------> Input 1
0 -----------> Input 2
Sample Output 2:
ERROR502

Sample Input 3:
10 -----------> Input 1
8 -----------> Input 2
Sample Output 3:
1.25

Solution

import java.util.Scanner;

import java.util.InputMismatchException;

class DivisionByZeroException extends Exception

{
public DivisionByZeroException()

super("ERROR502");

public DivisionByZeroException(String msg)

super(msg);

public class Source

public static void main(String[] args)

Scanner scan = new Scanner(System.in);

int n1, n2;

double r;

try

n1 = scan.nextInt();

n2 = scan.nextInt();

if(n2 == 0)
throw new DivisionByZeroException();

r = (double) n1 / n2;

System.out.println(r);

catch(DivisionByZeroException dbze)

System.err.println(dbze.getMessage());

catch(InputMismatchException imme)

//scan.nextLine();

System.err.println("ERROR501");

You might also like