CC2 Java Programs-Merged
CC2 Java Programs-Merged
CC2 Java Programs-Merged
Casual Employee:
public class CasualEmployee extends Employee{
}
Employee:
public abstract class Employee {
}
User Interface:
import java.util.Scanner;
public class UserInterface {
2.Dominion Cinemas
Gold Ticket:
public class GoldTicket extends BookAMovieTicket {
public GoldTicket(String ticketId, String customerName, long mobileNumber,
String emailId, String movieName) {
super(ticketId, customerName, mobileNumber, emailId, movieName);
}
public boolean validateTicketId(){
int count=0;
if(ticketId.contains("GOLD"));
count++;
char[] cha=ticketId.toCharArray();
for(int i=4;i<7;i++){
if(cha[i]>='1'&& cha[i]<='9')
count++;
}
if(count==4)
return true;
else
return false;
}
public double calculateTicketCost(int numberOfTickets,String ACFacility){
double amount;
if(ACFacility.equals("yes")){
amount=500*numberOfTickets;
}
else{
amount=350*numberOfTickets;
}
return amount;
}
}
Platinum Ticket:
public class PlatinumTicket extends BookAMovieTicket
{
public PlatinumTicket(String ticketId, String customerName, long mobileNumber,String
emailId, String movieName)
{
super(ticketId, customerName, mobileNumber, emailId, movieName);
}
public boolean validateTicketId(){
int count=0;
if(ticketId.contains("PLATINUM"));
count++;
char[] cha=ticketId.toCharArray();
for(int i=8;i<11;i++){
if(cha[i]>='1'&& cha[i]<='9')
count++;
}
if(count==4)
return true;
else
return false;
}
public double calculateTicketCost(int numberOfTickets,String ACFacility){
double amount;
if(ACFacility.equals("yes")){
amount=750*numberOfTickets;
}
else{
amount=600*numberOfTickets;
}
return amount;
}
}
Silver Ticket:
public class SilverTicket extends BookAMovieTicket{
public SilverTicket(String ticketId, String customerName, long mobileNumber,String emailId,
String movieName)
{
super(ticketId, customerName, mobileNumber, emailId, movieName);
}
public boolean validateTicketId(){
int count=0;
if(ticketId.contains("SILVER"));
count++;
char[] cha=ticketId.toCharArray();
for(int i=6;i<9;i++){
if(cha[i]>='1'&& cha[i]<='9')
count++;
}
if(count==4)
return true;
else
return false;
}
public double calculateTicketCost(int numberOfTickets,String ACFacility){
double amount;
if(ACFacility.equals("yes")){
amount=250*numberOfTickets;
}
else{
amount=100*numberOfTickets;
}
return amount;
}
}
User Interface:
import java.util.*;
public class UserInterface {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter Ticket Id");
String tid=sc.next();
System.out.println("Enter Customer Name");
String cnm=sc.next();
System.out.println("Enter Mobile Number");
long mno=sc.nextLong();
System.out.println("Enter Email id");
String email=sc.next();
System.out.println("Enter Movie Name");
String mnm=sc.next();
System.out.println("Enter number of tickets");
int tno=sc.nextInt();
System.out.println("Do you want AC or not");
String choice =sc.next();
if(tid.contains("PLATINUM")){
PlatinumTicket PT=new PlatinumTicket(tid,cnm,mno,email,mnm);
boolean b1=PT.validateTicketId();
if(b1==true){
double cost =PT.calculateTicketCost(tno, choice);
System.out.println("Ticket cost is "+ cost);
}
else if(b1==false){
System.out.println("Provide valid Ticket Id");
System.exit(0);
}
}
else if(tid.contains("GOLD")){
GoldTicket GT=new GoldTicket(tid,cnm,mno,email,mnm);
boolean b2=GT.validateTicketId();
if(b2==true){
double cost=GT.calculateTicketCost(tno, choice);
System.out.println("Ticket cost is "+cost);
}
else if (b2==false){
System.out.println("Provide valid Ticket Id");
System.exit(0);
}
}
else if(tid.contains("SILVER")){
SilverTicket ST=new SilverTicket(tid,cnm,mno,email,mnm);
boolean b3=ST.validateTicketId();
if(b3==true){
double cost=ST.calculateTicketCost(tno, choice);
System.out.println("Ticket cost is "+cost);
}
else if(b3==false){
System.out.println("Provide valid Ticket Id");
System.exit(0);
}
}
}
}
3.Little Innovators
Main:
import java.util.*;
public class Main {
Air Conditioner:
public class AirConditioner extends ElectronicProducts {
private String airConditionerType;
private double capacity;
public AirConditioner(String productId, String productName, String batchId, String
dispatchDate, int warrantyYears, String airConditionerType, double capacity) {
super(productId, productName, batchId, dispatchDate, warrantyYears);
this.airConditionerType = airConditionerType;
this.capacity = capacity;
}
public String getAirConditionerType() {
return airConditionerType;
}
public void setAirConditionerType(String airConditionerType) {
this.airConditionerType = airConditionerType;
}
public double getCapacity() {
return capacity;
}
public void setCapacity(double capacity) {
this.capacity = capacity;
}
public double calculateProductPrice(){
double price = 0;
if(airConditionerType.equalsIgnoreCase("Residential")){
if (capacity == 2.5){
price = 32000;
}
else if(capacity == 4){
price = 40000;
}
else if(capacity == 5.5){
price = 47000;
}
}
else if(airConditionerType.equalsIgnoreCase("Commercial")){
if (capacity == 2.5){
price = 40000;
}
else if(capacity == 4){
price = 55000;
}
else if(capacity == 5.5){
price = 67000;
}
}
else if(airConditionerType.equalsIgnoreCase("Industrial")){
if (capacity == 2.5){
price = 47000;
}
else if(capacity == 4){
price = 60000;
}
else if(capacity == 5.5){
price = 70000;
}
}
return price;
}
}
Electronic Products:
public class ElectronicProducts {
protected String productId;
protected String productName;
protected String batchId;
protected String dispatchDate;
protected int warrantyYears;
public ElectronicProducts(String productId, String productName, String batchId,
String dispatchDate, int warrantyYears) {
this.productId = productId;
this.productName = productName;
this.batchId = batchId;
this.dispatchDate = dispatchDate;
this.warrantyYears = warrantyYears;
}
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getBatchId() {
return batchId;
}
public void setBatchId(String batchId) {
this.batchId = batchId;
}
public String getDispatchDate() {
return dispatchDate;
}
public void setDispatchDate(String dispatchDate) {
this.dispatchDate = dispatchDate;
}
public int getWarrantyYears() {
return warrantyYears;
}
public void setWarrantyYears(int warrantyYears) {
this.warrantyYears = warrantyYears;
}
}
LED TV:
public class LEDTV extends ElectronicProducts {
private int size;
private String quality;
public LEDTV(String productId, String productName, String batchId, String
dispatchDate, int warrantyYears, int size, String quality) {
super(productId, productName, batchId, dispatchDate, warrantyYears);
this.size = size;
this.quality = quality;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public String getQuality() {
return quality;
}
public void setQuality(String quality) {
this.quality = quality;
}
public double calculateProductPrice(){
double price = 0;
if(quality.equalsIgnoreCase("Low")){
price = size * 850;
}
else if(quality.equalsIgnoreCase("Medium")){
price = size * 1250;
}
else if(quality.equalsIgnoreCase("High")){
price = size * 1550;
}
return price;
}
}
Microwave Oven:
public class MicrowaveOven extends ElectronicProducts{
private int quantity;
private String quality;
public MicrowaveOven(String productId, String productName, String batchId, String
dispatchDate, int warrantyYears, int quantity, String quality) {
super(productId, productName, batchId, dispatchDate, warrantyYears);
this.quantity = quantity;
this.quality = quality;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public String getQuality() {
return quality;
}
public void setQuality(String quality) {
this.quality = quality;
}
public double calculateProductPrice(){
double price = 0;
if(quality.equalsIgnoreCase("Low")){
price = quantity * 1250;
}
else if(quality.equalsIgnoreCase("Medium")){
price = quantity * 1750;
}
else if(quality.equalsIgnoreCase("High")){
price = quantity * 2000;
}
return price;
}
}
User Interface:
import java.util.Scanner;
public class UserInterface {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Product Id");
String productId = sc.next();
System.out.println("Enter Product Name");
String productName = sc.next();
System.out.println("Enter Batch Id");
String batchId = sc.next();
System.out.println("Enter Dispatch Date");
String dispatchDate = sc.next();
System.out.println("Enter Warranty Years");
int warrantyYears = sc.nextInt();
double price;
String quality;
switch(productName){
case "AirConditioner":
System.out.println("Enter type of Air Conditioner");
String type = sc.next();
System.out.println("Enter quantity");
double capacity = sc.nextDouble();
AirConditioner ac = new AirConditioner(productId, productName, batchId,
dispatchDate, warrantyYears, type, capacity);
price = ac.calculateProductPrice();
System.out.printf("Price of the product is %.2f", price);
break;
case "LEDTV":
System.out.println("Enter size in inches");
int size = sc.nextInt();
System.out.println("Enter quality");
quality = sc.next();
LEDTV l = new LEDTV(productId, productName, batchId, dispatchDate,
warrantyYears, size, quality);
price = l.calculateProductPrice();
System.out.printf("Price of the product is %.2f", price);
break;
case "MicrowaveOven":
System.out.println("Enter quantity");
int quantity = sc.nextInt();
System.out.println("Enter quality");
quality = sc.next();
MicrowaveOven m = new MicrowaveOven(productId, productName, batchId,
dispatchDate, warrantyYears, quantity, quality);
price = m.calculateProductPrice();
System.out.printf("Price of the product is %.2f", price);
break;
default:
System.out.println("Provide a valid Product name");
System.exit(0);
}
}
}
5. Reverse a word
import java.util.*;
class HelloWorld {
public static void main(String[] args) {
String[] words ;
Scanner myObj = new Scanner(System.in);
input1.append(words[words.length-1]);
// reverse StringBuilder input1
input1= input1.reverse();
input1.append(words[0]);
System.out.println(input1);
}
else {
input1.append(words[0]);
// reverse StringBuilder input1
input1= input1.reverse();
input1.append(words[words.length-1]);
System.out.println(input1);
}
}
}
}
Group -1
1. AirVoice - Registration
SmartBuy is a leading mobile shop in the town. After buying a product, the customer needs to
provide a few personal details for the invoice to be generated.
You being their software consultant have been approached to develop software to retrieve the
personal details of the customers, which will help them to generate the invoice faster.
String emailId
int age
Get the details as shown in the sample input and assign the value for its attributes using the
setters.
Display the details as shown in the sample output using the getters method.
In the Sample Input / Output provided, the highlighted text in bold corresponds to the input
given by the user and the rest of the text represents the output.
Ensure to provide the names for classes, attributes and methods as specified in the question.
Sample Input 1:
john
9874561230
32
Sample Output 1:
Name:john
ContactNumber:9874561230
EmailId:[email protected]
Age:32
Automatic evaluation[+]
Customer.java
Main.java
1 import java.util.Scanner;
2
3 public class Main {
4
5 public static void main(String[] args) {
6 // TODO Auto-generated method stub
7 Scanner sc=new Scanner(System.in);
8 Customer c=new Customer();
9 System.out.println("Enter the Name:");
10 String name=(sc.nextLine());
11 System.out.println("Enter the ContactNumber:");
12 long no=sc.nextLong();
13 sc.nextLine();
14 System.out.println("Enter the EmailId:");
15 String mail=sc.nextLine();
16
17 System.out.println("Enter the Age:");
18 int age=sc.nextInt();
19 c.setCustomerName(name);
20 c.setContactNumber(no);
21 c.setEmailId(mail);
22 c.setAge(age);
23 System.out.println("Name:"+c.getCustomerName());
24 System.out.println("ContactNumber:"+c.getContactNumber());
25 System.out.println("EmailId:"+c.getEmailId());
26 System.out.println("Age:"+c.getAge());
27
28
29
30 }
31
32 }
Grade
Reviewed on Monday, 7 February 2022, 4:45 PM by Automatic grade
Grade 100 / 100
Assessment report
[+]Grading and Feedback
=================================================================================
2. Payment - Inheritance
Grade settings: Maximum grade: 100
Run: Yes Evaluate: Yes
Automatic grade: Yes Maximum execution time: 16 s
Payment Status
Roy is a wholesale cloth dealer who sells cloth material to the local tailors on monthly
installments. At the end of each month, he collects the installment amount from all his customers.
Some of his customers pay by Cheque, some pay by Cash and some by Credit Card. He wants
to automate this payment process.
The application needs to verify the payment process and display the status report of payment by
getting the inputs like due amount, payment mode and data specific to the payment mode from
the user and calculate the balance amount.
Note:
Date
dateOfIssue
Make payment Cheque public boolean This is an overridden method
for EMI payAmount() of the parent class. It should
amount return true if the cheque is
valid and the amount is valid.
Else return false.
Note:
int
creditCardAmount
Make Credit public boolean This is an overridden method of
payment for payAmount() the parent class. It should deduct
EMI amount the dueAmount and service tax
from the creditCardAmount and
return true if the credit card
payment was done successfully.
Else return false.
Note:
· The payment can be done if the credit card amount is greater than or equal to the sum of
due amount and service tax. Else payment cannot be made.
· The cardType can be “silver” or “gold” or “platinum”. Set the creditCardAmount based on
the cardType.
· The boolean payAmount() method should deduct the due amount and the service tax
amount from a credit card. If the creditCardAmount is less than the dueAmount+serviceTax, then
the payment cannot be made.
· The balance in credit card amount after a successful payment should be updated in the
creditCardAmount by deducting the sum of dueAmount and serviceTax from creditCardAmount
itself.
Note:
· If the payment is successful, processPayment method should return a message “Payment
done successfully via cash” or “Payment done successfully via cheque” or “Payment done
successfully via creditcard. Remaining amount in your <<cardType>> card is <<balance in
CreditCardAmount>>”
· If the payment is a failure, then return a message “Payment not done and your due amount
is <<dueAmount>>”
Create a public class Main with the main method to test the application.
Note:
· In the Sample Input / Output provided, the highlighted text in bold corresponds to the input
given by the user and the rest of the text represents the output.
· Ensure to provide the names for classes, attributes and methods as specified in the
question.
Sample Input 1:
3000
Enter the mode of payment(cheque/cash/credit):
cash
Enter the cash amount:
2000
Sample Output 1:
Sample Input 2:
3000
Enter the mode of payment(cheque/cash/credit):
cash
Enter the cash amount:
3000
Sample Output 2:
Sample Input 3:
3000
Enter the mode of payment(cheque/cash/credit):
cheque
Enter the cheque number:
123
Enter the cheque amount:
3000
Enter the date of issue:
21-08-2019
Sample Output 3:
Sample Input 4:
3000
Enter the mode of payment(cheque/cash/credit):
credit
Enter the credit card number:
234
Enter the card type(silver,gold,platinum):
silver
Sample Output 4:
Payment done successfully via credit card. Remaining amount in your silver card is 6940
Automatic evaluation[+]
Main.java
1 import java.text.ParseException;
2 import java.text.SimpleDateFormat;
3 import java.util.Date;
4 import java.util.Scanner;
5 public class Main {
6
7 public static void main(String[] args) {
8
9 Scanner sc=new Scanner(System.in);
10 System.out.println("Enter the due amount:");
11 int dueAmount=sc.nextInt();
12
13 System.out.println("Enter the mode of payment(cheque/cash/credit):");
14 String mode=sc.next();
15 Bill b = new Bill();
16 if(mode.equals("cheque"))
17 {
18 System.out.println("enter the cheque number:");
19 String chequeNumber=sc.next();
20 System.out.println("enter the cheque amount:");
21 int chequeAmount=sc.nextInt();
22 System.out.println("enter the date of issue:");
23 String date=sc.next();
24 SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
25 Date dateOfIssue=null;
26 try
27 {
28 dateOfIssue = dateFormat.parse(date);
29 }
30 catch (ParseException e)
31 {
32
33 }
34 Cheque cheque= new Cheque();
35 cheque.setChequeNo(chequeNumber);
36 cheque.setChequeAmount(chequeAmount);
37 cheque.setDateOfIssue(dateOfIssue);
38 cheque.setDueAmount(dueAmount);
39 System.out.println(b.processPayment(cheque));
40 }
41 else if(mode.equals("cash"))
42 {
43 System.out.println("enter the cash amount:");
44 int CashAmount=sc.nextInt();
45 Cash cash=new Cash();
46 cash.setCashAmount(CashAmount);
47 cash.setDueAmount(dueAmount);
48 System.out.println(b.processPayment(cash));
49 }
50 else if(mode.equals("credit"))
51 {
52 System.out.println("enter the credit card number:");
53 int creditCardNumber=sc.nextInt();
54 System.out.println("enter the card type:");
55 String cardType=sc.next();
56
57 Credit credit=new Credit();
58 credit.setCreditCardNo(creditCardNumber);
59 credit.setCardType(cardType);
60 credit.setDueAmount(dueAmount);
61 System.out.println(b.processPayment(credit));
62 }
63 }
64 }
Payment.java
1 public class Payment {
2 private int dueAmount;
3
4 public boolean payAmount()
5 {
6 if(dueAmount == 0)
7 return true;
8 else
9 return false;
10 }
11
12 public int getDueAmount() {
13 return dueAmount;
14 }
15
16 public void setDueAmount(int dueAmount) {
17 this.dueAmount = dueAmount;
18 }
19 }
Cheque.java
1 import java.text.ParseException;
2 import java.text.SimpleDateFormat;
3 import java.util.Date;
4 public class Cheque extends Payment {
5 String chequeNo;
6 int chequeAmount;
7 Date dateOfIssue;
8 public String getChequeNo() {
9 return chequeNo;
10 }
11 public void setChequeNo(String chequeNo) {
12 this.chequeNo = chequeNo;
13 }
14 public int getChequeAmount() {
15 return chequeAmount;
16 }
17 public void setChequeAmount(int chequeAmount) {
18 this.chequeAmount = chequeAmount;
19 }
20 public Date getDateOfIssue() {
21 return dateOfIssue;
22 }
23 public void setDateOfIssue(Date dateOfIssue) {
24 this.dateOfIssue = dateOfIssue;
25 }
26
27 @Override
28 public boolean payAmount()
29 {
30 SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
31 Date today = new Date();
32 try
33 {
34 today = format.parse("01-01-2020");
35 }
36 catch (ParseException e)
37 {
38 return false;
39 }
40 long diff = today.getTime()-dateOfIssue.getTime();
41 int day = (int) Math.abs(diff/(1000*60*60*24));
42 int month = day/30;
43 if(month <=6)
44 {
45
46 if(chequeAmount>=getDueAmount())
47 {
48 return true;
49 }
50 else
51 return false;
52
53 }
54 else
55 return false;
56 }
57
58
59 }
Cash.java
1 public class Cash extends Payment {
2 int cashAmount;
3
4 public int getCashAmount() {
5 return cashAmount;
6 }
7
8 public void setCashAmount(int cashAmount) {
9 this.cashAmount = cashAmount;
10 }
11
12 @Override
13 public boolean payAmount()
14 {
15 if(cashAmount>=getDueAmount())
16 return true;
17 else
18 return false;
19 }
20
21
22 }
Credit.java
1 public class Credit extends Payment {
2 int creditCardNo;
3 String cardType;
4 int creditCardAmount;
5 public int getCreditCardNo() {
6 return creditCardNo;
7 }
8 public void setCreditCardNo(int creditCardNo) {
9 this.creditCardNo = creditCardNo;
10 }
11 public String getCardType() {
12 return cardType;
13 }
14 public void setCardType(String cardType) {
15 this.cardType = cardType;
16 }
17 public int getCreditCardAmount() {
18 return creditCardAmount;
19 }
20 public void setCreditCardAmount(int creditCardAmount) {
21 this.creditCardAmount = creditCardAmount;
22 }
23
24
25 @Override
26 public boolean payAmount()
27 {
28 int netAmount = 0;
29 if(cardType.equals("silver"))
30 {
31 netAmount = (int) (getDueAmount()*1.02);
32 creditCardAmount = 10000;
33 }
34 else if(cardType.equals("gold"))
35 {
36 netAmount = (int) (getDueAmount()*1.05);
37 creditCardAmount = 50000;
38 }
39 else if(cardType.equals("platinum"))
40 {
41 netAmount = (int) (int) (getDueAmount()*1.1);
42 creditCardAmount = 100000;
43 }
44
45 if(creditCardAmount>=netAmount)
46 {
47 creditCardAmount = creditCardAmount - netAmount;
48 return true;
49 }
50 else
51 return false;
52 }
53
54
55 }
Bill.java
1 public class Bill {
2 public String processPayment(Payment obj)
3{
4 String res="";
5 if(obj instanceof Cheque)
6 {
7 if(obj.payAmount())
8 res = "Payment done successfully via cheque";
9 else
10 res = "Payment not done and your due amount is
"+obj.getDueAmount();
11 }
12 else if(obj instanceof Cash)
13 {
14 if(obj.payAmount())
15 res = "Payment done successfully via cash";
16 else
17 res = "Payment not done and your due amount is
"+obj.getDueAmount();
18 }
19 else if(obj instanceof Credit)
20 {
21 Credit c = (Credit) obj;
22 if(obj.payAmount())
23 res = "Payment done successfully via credit card. Remaining
amount in your "+c.getCardType()+" card is "+c.getCreditCardAmount();
24 else
25 res = "Payment not done and your due amount is
"+obj.getDueAmount();
26 }
27 return res;
28 }
29 }
Grade
Reviewed on Wednesday, 1 December 2021, 10:08 PM by Automatic grade
Grade 100 / 100
Assessment report
TEST CASE PASSED
[+]Grading and Feedback
3.Power Progress
Grade settings: Maximum grade: 100
Run: Yes Evaluate: Yes
Automatic grade: Yes
Andrews taught exponential multiplication to his daughter and gave her two inputs.
Assume, the first input as M and the second input as N. He asked her to find the sequential
power of M until N times. For Instance, consider M as 3 and N as 5. Therefore, 5 times the power
is incremented gradually from 1 to 5 such that, 3^1=3, 3^2=9,3^3=27,3^4=81,3^5=243. The input
numbers should be greater than zero Else print “<Input> is an invalid”. The first Input must be
less than the second Input, Else print "<first input> is not less than <second input>".
Write a Java program to implement this process programmatically and display the output in
sequential order. ( 3^3 means 3*3*3 ).
Note:
In the Sample Input / Output provided, the highlighted text in bold corresponds to the input given
by the user and the rest of the text represents the output.
Sample Input 1:
3
5
Sample Output 1:
3 9 27 81 243
Explanation: Assume the first input as 3 and second input as 5. The output is to be displayed
are based on the sequential power incrementation. i.e., 3(3) 9(3*3) 27(3*3*3) 81(3*3*3*3)
243(3*3*3*3*3)
Sample Input 2:
-3
Sample Output 2:
-3 is an invalid
Sample Input 3:
3
0
Sample Output 3:
0 is an invalid
Sample Input 4:
4
2
Sample Output 4:
4 is not less than 2
Automatic evaluation[+]
Main.java
1 import java.util.*;
2 public class Main
3{
4 public static void main(String[] args)
5 {
6 Scanner sc=new Scanner(System.in);
7 //Fill the code
8 int m=sc.nextInt();
9 if(m<=0){
10 System.out.println(""+m+" is an invalid");
11 return;
12 }
13 int n=sc.nextInt();
14 if(n<=0){
15 System.out.println(""+n+" is an invalid");
16 return;
17 }
18 if(m>=n){
19 System.out.println(""+m+" is not less than "+n);
20 return;
21 }
22 for(int i=1;i<=n;i++){
23 System.out.print((int)Math.pow(m,i)+"");
24 }
25 }
26 }
Grade
Reviewed on Monday, 7 February 2022, 4:46 PM by Automatic grade
Grade 100 / 100
Assessment report
TEST CASE PASSED
[+]Grading and Feedback
4. ZeeZee bank
Grade settings: Maximum grade: 100
Run: Yes Evaluate: Yes
Automatic grade: Yes Maximum execution time: 16 s
ZeeZee is a leading private sector bank. In the last Annual meeting, they decided to give their
customer a 24/7 banking facility. As an initiative, the bank outlined to develop a stand-alone
device that would offer deposit and withdrawal of money to the customers anytime.
You being their software consultant have been approached to develop software to implement
the functionality of deposit and withdrawal anytime.
As per this requirement, the customer should be able to deposit money into his account at any
time and the deposited amount should reflect in his account balance.
Deposit amount to Account public void deposit(double This method takes the
an account depositAmt) amount to be deposited as
an argument
As per this requirement, the customer should be able to withdraw money from his account
anytime he wants. The amount to be withdrawn should be less than or equal to the balance in
the account. After the withdrawal, the account should reflect the balance amount
In the Main class, Get the details as shown in the sample input.
Create an object for the Account class and invoke the deposit method to deposit the amount
and withdraw method to withdraw the amount from the account.
Note:
If the balance amount is insufficient then display the message as shown in the Sample Input /
Output.
In the Sample Input / Output provided, the highlighted text in bold corresponds to the input
given by the user and the rest of the text represents the output.
Ensure to provide the names for classes, attributes, and methods as specified in the question.
Sample Input/Output 1:
1234567890
15000
1500
500
Sample Input/Output 2:
1234567890
15000
Enter the amount to be deposited:
1500
18500
Insufficient balance
Automatic evaluation[+]
Main.java
1 import java.text.DecimalFormat;
2 import java.util.Scanner;
3 import java.util.Scanner;
4
5
6 public class Main{
7 static Account ac=new Account(0, 0);
8 public static void main (String[] args) {
9 Scanner sc=new Scanner(System.in);
10 System.out.println("Enter the account number:");
11 ac.setAccountNumber(sc.nextLong());
12 System.out.println("Enter the available amount in the account:");
13 ac.setBalanceAmount(sc.nextDouble());
14 System.out.println("Enter the amount to be deposited:");
15 ac.deposit(sc.nextDouble());
16 System.out.printf("Available balance is:%.2f",ac.getBalanceAmount());
17 System.out.println();
18 System.out.println("Enter the amount to be withdrawn:");
19 ac.withdraw(sc.nextDouble());
20 System.out.printf("Available balance is:%.2f",ac.getBalanceAmount());
21 //Fill the code
22 }
23 }
24
25
26
Account.java
1
2 public class Account {
3 long accountNumber;
4 double balanceAmount;
5
6
7 public Account(long accno, double bal){
8 super();
9 this.accountNumber=accno;
10 this.balanceAmount=bal;
11 }
12 public long getAccountNumber(){
13 return accountNumber;
14 }
15 public void setAccountNumber(long accno){
16 this.accountNumber=accno;
17 }
18 public double getBalanceAmount(){
19 return balanceAmount;
20 }
21 public void setBalanceAmount(double bal) {
22 this.balanceAmount=bal;
23 }
24 public void deposit(double depositAmt){
25 float total=(float)(balanceAmount+depositAmt);
26 balanceAmount=total;
27 }
28 public boolean withdraw(double withdrawAmt){
29 float total;
30 if(withdrawAmt>balanceAmount){
31 System.out.println("Insufficient balance");
32
33 return false;
34 }else{
35 total=(float)(balanceAmount-withdrawAmt);
36 setBalanceAmount(total);
37 return true;
38 }
39 }
40 }
Grade
Reviewed on Monday, 7 February 2022, 4:47 PM by Automatic grade
Grade 100 / 100
Assessment report
[+]Grading and Feedback
5. Reverse a word
Grade settings: Maximum grade: 100
Run: Yes Evaluate: Yes
Automatic grade: Yes
Reverse a word
Rita and Brigitha want to play a game. That game is to check the first letter of each word in a
given sentence (Case Insensitive). If it is equal, then reverse the last word and concatenate the
first word. Else reverse the first word and concatenate the last word. Create a Java application
and help them to play the game
Note:
● Sentence must contain at least 3 words else print "Invalid Sentence" and terminate the
program
● Each word must contain alphabet only else print "Invalid Word" and terminate the
program
● Check the first letter of each word in a given sentence (Case Insensitive). If it is equal,
then reverse the last word and concatenate the first word and print. Else reverse the first
word and concatenate the last word and print.
● Print the output without any space.
Sample Input 1:
Sample Output 1:
sllehsaesSea
Sample Input 2:
Sample Output 2:
maSdays
Sample Input 3:
Welcome home
Sample Output 3:
Invalid Sentence
Sample Input 4:
Friendly fire fighting fr@gs.
Sample Output 4:
Invalid Word
Automatic evaluation[+]
Main.java
1 import java.util.Scanner;
2 import java.lang.String.*;
3 import java.util.*;
4 public class Main{
5 public static void main(String[] args){
6 String[] words;
7 Scanner read =new Scanner(System.in);
8 String sentence=read.nextLine();
9 words=sentence.split(" ");
10 if(words.length<3)
11 System.out.println("Invalid Sentence");
12 else{
13 String a=words[0].substring(0,1);
14 String b=words[1].substring(0,1);
15 String c=words[2].substring(0,1);
16 if(a.equalsIgnoreCase(b)&&b.equalsIgnoreCase(c))
17 {
18 StringBuilder k= new StringBuilder();
19 k.append(words[words.length-1]);
20 k=k.reverse();
21 k.append(words[0]);
22 System.out.println(k);
23 }
24 else{
25 StringBuilder k = new StringBuilder();
26 k.append(words[0]);
27 k=k.reverse();
28 k.append(words[words.length-1]);
29 System.out.println(k);
30 }
31 }
32 }
33 }
Grade
Reviewed on Monday, 7 February 2022, 5:12 PM by Automatic grade
Grade 90 / 100
Assessment report
Fail 1 -- test5_CheckForTheSentenceContainsOtherThanAlphabets::
$Expected output:"[Invalid Word]" Actual output:"[tahWme]"$
[+]Grading and Feedback
6. Dominion cinemas
Grade settings: Maximum grade: 100
Run: Yes Evaluate: Yes
Automatic grade: Yes
Dominion cinema is a famous theatre in the city. It has different types of seat tiers – Platinum,
Gold and Silver. So far the management was manually calculating the ticket cost for all their
customers which proved very hectic and time consuming. Going forward they want to calculate
ticket cost using their main computer. Assist them in calculating and retrieving the amount to be
paid by the Customer.
The application needs to calculate the ticket cost to be paid by the Customer according to the
seat tier.
Note:
Note:
Use a public class UserInterface with the main method to test the application. In the main
method call the validateTicketId() method, if the method returns true display the amount else
display "Provide valid Ticket Id".
Note:
● In the Sample Input / Output provided, the highlighted text in bold corresponds to the
input given by the user and the rest of the text represents the output.
● Ensure to follow the object oriented specifications provided in the question.
● Ensure to provide the names for classes, attributes and methods as specified in the
question.
● Adhere to the code template, if provided.
Sample Input 1:
Enter Ticket Id
SILVER490
Venkat
9012894578
Enter Email Id
Avengers
8
Do you want AC or not
Sample Input 2:
Enter Ticket Id
ACN450
Kamal
9078561093
Enter Email Id
Tangled
Automatic evaluation[+]
BookAMovieTicket.java
1
2 public class BookAMovieTicket {
3
4 protected String ticketId;
5 protected String customerName;
6 protected long mobileNumber;
7 protected String emailId;
8 protected String movieName;
9
10 public String getTicketId() {
11 return ticketId;
12 }
13 public void setTicketId(String ticketId) {
14 this.ticketId = ticketId;
15 }
16 public String getCustomerName() {
17 return customerName;
18 }
19 public void setCustomerName(String customerName) {
20 this.customerName = customerName;
21 }
22 public long getMobileNumber() {
23 return mobileNumber;
24 }
25 public void setMobileNumber(long mobileNumber) {
26 this.mobileNumber = mobileNumber;
27 }
28 public String getEmailId() {
29 return emailId;
30 }
31 public void setEmailId(String emailId) {
32 this.emailId = emailId;
33 }
34 public String getMovieName() {
35 return movieName;
36 }
37 public void setMovieName(String movieName) {
38 this.movieName = movieName;
39 }
40
41 public BookAMovieTicket(String ticketId, String customerName, long mobileNumber, String emailId,
String movieName) {
42 this.ticketId = ticketId;
43 this.customerName = customerName;
44 this.mobileNumber = mobileNumber;
45 this.emailId = emailId;
46 this.movieName = movieName;
47
48 }
49
50
51
52 }
53
GoldTicket.java
1
2 public class GoldTicket extends BookAMovieTicket{
3 public GoldTicket(String ticketId,String customerName, long mobileNumber,
4 String emailId, String movieName){
5 super(ticketId, customerName, mobileNumber, emailId, movieName);
6 }
7
8 public boolean validateTicketId(){
9 int count=0;
10 if(ticketId.contains("GOLD"));
11 count++;
12 char[] cha=ticketId.toCharArray();
13 for(int i=4;i<7;i++){
14 if(cha[i]>='1'&& cha[i]<='9')
15 count++;
16 }
17 if(count==4)
18 return true;
19 else
20 return false;
21 }
22
23
24 // Include Constructor
25
26 public double calculateTicketCost(int numberOfTickets, String ACFacility){
27 double amount;
28 if(ACFacility.equals("yes")){
29 amount=500*numberOfTickets;
30 }
31 else{
32 amount=350*numberOfTickets;
33 }
34
35 return amount;
36 }
37
38 }
PlatinumTicket.java
SilverTicket.java
1
2 public class SilverTicket extends BookAMovieTicket{
3 public SilverTicket(String ticketId, String customerName, long mobileNumber,
4 String emailId, String movieName){
5 super(ticketId, customerName, mobileNumber, emailId, movieName);
6 }
7
8 public boolean validateTicketId(){
9 int count=0;
10 if(ticketId.contains("SILVER"));
11 count++;
12 char[] cha=ticketId.toCharArray();
13 for(int i=6;i<9;i++){
14 if(cha[i]>='1'&& cha[i]<='9')
15 count++;
16 }
17 if(count==4)
18 return true;
19 else
20 return false;
21 }
22
23 // Include Constructor
24
25 public double calculateTicketCost(int numberOfTickets, String ACFacility){
26 double amount;
27 if(ACFacility.equals("yes")){
28 amount=250*numberOfTickets;
29 }
30 else{
31 amount=100*numberOfTickets;
32 }
33
34 return amount;
35 }
36
37 }
38
UserInterface.java
1 import java.util.*;
2
3 public class UserInterface {
4
5 public static void main(String[] args){
6 Scanner sc=new Scanner(System.in);
7 System.out.println("Enter Ticket Id");
8 String tid=sc.next();
9 System.out.println("Enter Customer name");
10 String cnm=sc.next();
11 System.out.println("Enter Mobile number");
12 long mno=sc.nextLong();
13 System.out.println("Enter Email id");
14 String email=sc.next();
15 System.out.println("Enter Movie name");
16 String mnm=sc.next();
17 System.out.println("Enter number of tickets");
18 int tno=sc.nextInt();
19 System.out.println("Do you want AC or not");
20 String choice =sc.next();
21 if(tid.contains("PLATINUM")){
22 PlatinumTicket PT= new PlatinumTicket(tid,cnm,mno,email,mnm);
23 boolean b1=PT.validateTicketId();
24 if(b1==true){
25 double cost=PT.calculateTicketCost(tno, choice);
26 System.out.println("Ticket cost is "+String.format("%.2f",cost));
27 }
28 else if(b1==false){
29 System.out.println("Provide valid Ticket Id");
30 System.exit(0);
31 }
32 }
33 else if(tid.contains("GOLD")){
34 GoldTicket GT= new GoldTicket(tid,cnm,mno,email,mnm);
35 boolean b2=GT.validateTicketId();
36 if(b2==true){
37 double cost=GT.calculateTicketCost(tno,choice);
38 System.out.println("Ticket cost is "+String.format("%.2f",cost));
39 }
40 else if (b2==false){
41 System.out.println("Provide valid Ticket Id");
42 System.exit(0);
43 }
44 }
45 else if(tid.contains("SILVER")){
46 SilverTicket ST= new SilverTicket(tid,cnm,mno,email,mnm);
47 boolean b3=ST.validateTicketId();
48 if(b3==true){
49 double cost=ST.calculateTicketCost(tno,choice);
50 System.out.println("Ticket cost is "+String.format("%.2f",cost));
51 }
52 else if (b3==false){
53 System.out.println("Provide valid Ticket Id");
54 System.exit(0);
55 }
56 }
57 }
58 }
59
60
Grade
Reviewed on Monday, 7 February 2022, 4:18 PM by Automatic grade
Grade 100 / 100
Assessment report
[+]Grading and Feedback
============================================================================
Group-2
1. Flight record retrieval
Grade settings: Maximum grade: 100
Based on: JAVA CC JDBC - MetaData V1 - ORACLE (w/o Proj Struc)
Run: Yes Evaluate: Yes
Automatic grade: Yes Maximum execution time: 32 s
You being their software consultant have been approached by them to develop an application
which can be used for managing their business. You need to implement a java program to view
all the flight based on source and destination.
int
noOfSeats
double
flightFare
Note: The class and methods should be declared as public and all the attributes should be
declared as private.
Requirement 1: Retrieve all the flights with the given source and destination
The customer should have the facility to view flights which are from a particular source to
destination. Hence the system should fetch all the flight details for the given source and
destination from the database. Those flight details should be added to a ArrayList and return the
same.
The flight table is already created at the backend. The structure of flight table is:
To connect to the database you are provided with database.properties file and DB.java file. (Do
not change any values in database.properties file)
Create a class called Main with the main method and get the inputs
like source and destination from the user.
Display the details of flight such as flightId, noofseats and flightfare for all the flights returned
as ArrayList<Flight> from the
method viewFlightBySourceDestination in FlightManagementSystem class.
If no flight is available in the list, the output should be “No flights available for the given source
and destination”.
Note:
In the Sample Input / Output provided, the highlighted text in bold corresponds to the input given
by the user and the remaining text represents the output.
Malaysia
Singapore
18221 50 5000.0
Malaysia
Dubai
Automatic evaluation[+]
Flight.java
1
2 public class Flight {
3
4 private int flightId;
5 private String source;
6 private String destination;
7 private int noOfSeats;
8 private double flightFare;
9 public int getFlightId() {
10 return flightId;
11 }
12 public void setFlightId(int flightId) {
13 this.flightId = flightId;
14 }
15 public String getSource() {
16 return source;
17 }
18 public void setSource(String source) {
19 this.source = source;
20 }
21 public String getDestination() {
22 return destination;
23 }
24 public void setDestination(String destination) {
25 this.destination = destination;
26 }
27 public int getNoOfSeats() {
28 return noOfSeats;
29 }
30 public void setNoOfSeats(int noOfSeats) {
31 this.noOfSeats = noOfSeats;
32 }
33 public double getFlightFare() {
34 return flightFare;
35 }
36 public void setFlightFare(double flightFare) {
37 this.flightFare = flightFare;
38 }
39 public Flight(int flightId, String source, String destination,
40 int noOfSeats, double flightFare) {
41 super();
42 this.flightId = flightId;
43 this.source = source;
44 this.destination = destination;
45 this.noOfSeats = noOfSeats;
46 this.flightFare = flightFare;
47 }
48
49
50
51 }
52
FlightManagementSystem.java
1 import java.util.ArrayList;
2 import java.sql.*;
3
4
5 public class FlightManagementSystem {
6
7 public ArrayList<Flight> viewFlightBySourceDestination(String source, String destination){
8 ArrayList<Flight> flightList = new ArrayList<Flight>();
9 try{
10 Connection con = DB.getConnection();
11
12 String query="SELECT * FROM flight WHERE source= '" + source + "' AND destination= '" +
destination + "' ";
13
14 Statement st=con.createStatement();
15
16 ResultSet rst= st.executeQuery(query);
17
18 while(rst.next()){
19 int flightId= rst.getInt(1);
20 String src=rst.getString(2);
21 String dst=rst.getString(3);
22 int noofseats=rst.getInt(4);
23 double flightfare=rst.getDouble(5);
24
25 flightList.add(new Flight(flightId, src, dst, noofseats, flightfare));
26 }
27 }catch(ClassNotFoundException | SQLException e){
28 e.printStackTrace();
29 }
30 return flightList;
31 }
32
33 }
Main.java
1 import java.util.Scanner;
2 import java.util.ArrayList;
3
4 public class Main{
5 public static void main(String[] args){
6 Scanner sc=new Scanner(System.in);
7 System.out.println("Enter the source");
8 String source=sc.next();
9 System.out.println("Enter the destination");
10 String destination=sc.next();
11
12 FlightManagementSystem fms= new FlightManagementSystem();
13 ArrayList<Flight> flightList=fms.viewFlightBySourceDestination(source,destination);
14 if(flightList.isEmpty()){
15 System.out.println("No flights available for the given source and destination");
16 return;
17 }
18 System.out.println("Flightid Noofseats Flightfare");
19 for(Flight flight : flightList){
20 System.out.println(flight.getFlightId()+" "+flight.getNoOfSeats()+" "+flight.getFlightFare());
21 }
22
23 }
24 }
DB.java
1 import java.io.FileInputStream;
2 import java.io.IOException;
3 import java.sql.Connection;
4 import java.sql.DriverManager;
5 import java.sql.SQLException;
6 import java.util.Properties;
7
8 public class DB {
9
10 private static Connection con = null;
11 private static Properties props = new Properties();
12
13
14 //ENSURE YOU DON'T CHANGE THE BELOW CODE WHEN YOU SUBMIT
15 public static Connection getConnection() throws ClassNotFoundException, SQLException {
16 try{
17
18 FileInputStream fis = null;
19 fis = new FileInputStream("database.properties");
20 props.load(fis);
21
22 // load the Driver Class
23 Class.forName(props.getProperty("DB_DRIVER_CLASS"));
24
25 // create the connection now
26 con =
DriverManager.getConnection(props.getProperty("DB_URL"),props.getProperty("DB_USERNAME"),props.getPr
operty("DB_PASSWORD"));
27 }
28 catch(IOException e){
29 e.printStackTrace();
30 }
31 return con;
32 }
33 }
34
database.properties
1 #IF NEEDED, YOU CAN MODIFY THIS PROPERTY FILE
2 #ENSURE YOU ARE NOT CHANGING THE NAME OF THE PROPERTY
3 #YOU CAN CHANGE THE VALUE OF THE PROPERTY
4 #LOAD THE DETAILS OF DRIVER CLASS, URL, USERNAME AND PASSWORD IN DB.java using this
properties file only.
5 #Do not hard code the values in DB.java.
6
7 DB_DRIVER_CLASS=oracle.jdbc.driver.OracleDriver
8 DB_URL=jdbc:oracle:thin:@127.0.0.1:1521:XE
9 DB_USERNAME=${sys:db_username}
10 DB_PASSWORD=${sys:db_password}
11
Grade
Reviewed on Monday, 7 February 2022, 6:33 PM by Automatic grade
Grade 100 / 100
Assessment report
Assessment Completed Successfully
[+]Grading and Feedback
=============================================
2. Get Text and Display Welcome Message
Grade settings: Maximum grade: 100
Run: Yes Evaluate: Yes
Automatic grade: Yes Maximum execution time: 16 s
Amir owns “Bouncing Babies” an exclusive online store for baby toys.
He desires to display a welcome message whenever a customer visits his online store and
makes a purchase.
Help him do this by incorporating the customer name using the Lambda expression.
In the Main class write the main method and perform the given steps :
Note :
In the Sample Input / Output provided, the highlighted text in bold corresponds to the input given
by the user and the rest of the text represents the output.
Ensure to provide the name for classes, interfaces and methods as specified in the question.
Watson
Sample Output 1 :
Welcome Watson
Automatic evaluation[+]
DisplayText.java
1 import java.util.*;
2 @FunctionalInterface
3 public interface DisplayText
4{
5 public void displayText(String text);
6 public default String getInput()
7 {
8 Scanner read = new Scanner(System.in);
9 String str = read.next();
10 return str;
11 //return null;
12 }
13 }
Main.java
1 public class Main
2{
3 public static DisplayText welcomeMessage()
4 {
5
6 DisplayText dis = (str)->{
7
8 System.out.println("Welcome "+str);
9 };
10 return dis;
11 }
12 public static void main(String args[])
13 {
14 DisplayText dis=welcomeMessage();
15 String text = dis.getInput();
16 dis.displayText(text);
17
18 }
19 }
Grade
Reviewed on Wednesday, 1 December 2021, 10:14 PM by Automatic grade
Grade 100 / 100
Assessment report
[+]Grading and Feedback
=============================================
3. Generate Password
Grade settings: Maximum grade: 100
Run: Yes Evaluate: Yes
Automatic grade: Yes
Important Instructions:
· Do not change the Skeleton code or the package structure, method names, variable
names, return types, exception clauses, access specifiers etc.
· You can create any number of private methods inside the given class.
· You can test your code from main() method of the program
The system administrator of an organization wants to set password for all the computers for
security purpose. To generate a strong password, he wants to combine the username of each
user of the system with the reverse of their respective usernames. Help them by using Lambda
expressions that caters to their requirement.
Requirement 1: PasswordInfo
The Administrator wants to generate password for each system by making use
of the passwordGeneration method based on the username which is passed as a string.
In the Computer class write the main method and perform the given steps:
Note:
In the Sample Input / Output provided, the highlighted text in bold corresponds to the
input given by the user and the rest of the text represents the output.
Ensure to use the lambda expression.
Ensure to follow the object oriented specifications provided in the question.
Ensure to provide the name for classes, interfaces and methods as specified in the
question.
Adhere to the code template, if provided.
Sample Input 1:
Enter system no
Tek/1234
Enter username
Manoj Kumar
Sample Output 1:
Password Info
=========================================================================
· Do not change the Skeleton code or the package structure, method names, variable
names, return types, exception clauses, access specifiers etc.
· You can create any number of private methods inside the given class.
· You can test your code from the main() method of the program.
Watican Museum is one of the famous museums, they have collections of houses paintings, and
sculptures from artists. The Museum management stores their visitor's details in a text file. Now,
they need an application to analyze and manipulate the visitor details based on the visitor visit
date and the visitor address.
You are provided with a text file – VisitorDetails.txt, which contains all the visitor details
like the visitor Id, visitor name, mobile number, date of visiting and address. Your
application should satisfy the following requirements.
2. View visitor details which are above a particular mentioned visitor address.
You are provided with a code template which includes the following:
Note:
The Visitor class and the Main class will be provided with all the necessary codes. Please
do not edit or delete any line of the code in these two classes.
Fill your code in the InvalidVisitorIdException class to create a constructor as described
in the functional requirements below.
Fill your code in the respective methods of VisitorUtility class to fulfil all the functional
requirements.
In the VisitorDetails.txt file, each visitor detail has information separated by a comma,
and it is given as one customer detail per line.
Functional Requirements:
Fill your code in the respective class and method declarations based on the required
functionalities as given below.
Note:
Validation Rules:
Example.
WM_A23
InvalidVisitorIdException Create a constructor with a This class Should inherit the Exception
single String argument and class. The constructor should pass the
pass it to the parent class String message which is thrown to it by
constructor. calling the parent class constructor.
Requirement 2: View visitor details which are above a particular mentioned address
1. All inputs/ outputs for processing the functional requirements should be case sensitive.
2. Adhere to the Sample Inputs/ Outputs
3. In the Sample Inputs/ Outputs provided, the highlighted text in bold corresponds to the
input given by the user and the rest of the text represents the output.
4. All the Date values used in this application must be in “dd-MM-yyyy” format.
5. Adhere to the code template.
6. Fill all your required codes in the respective blocks. Do not edit or delete the codes
provided in the code template.
7. The Sample Inputs/ Outputs given below are generated based on the Sample data given
in the VisitorDetails.txt file.
8. Please do not hard code the output.
1. ViewVisitorDetailsByDateOfVisiting
2. ViewVisitorDetailsByAddress
07-04-2012
1. viewVisitorDetailsByDateOfVisiting
2. viewVisitorDetailsByAddress
Eastbourne
Requirements:
3. Retrieve the patient details which are from a particular area (address).
String
patientName
String
contactNumber
String dateOfVisit
String
patientAddress
You are provided with a text file –PatientRegister.txt, which contains all the patient details like the
patient Id, patient name, contact number, date of visit, and patient address. You can add any
number of records in the text file to test your code.
Note:
· In the Sample Input / Output provided, the highlighted text in bold corresponds to the input
given by the user, and the rest of the text represents the output.
· Ensure to provide the names for classes, attributes, and methods as specified in the
question description.
Sample Input/Output 1:
1. By Date of Visit
2. By Address
Enter your choice:
02-03-2003
02-12-2005
Sample Input/Output 2:
1. By Date of Visit
2. By Address
Carolina
1. By Date of Visit
2. By Address
03-02-2020
02-02-2021
Sample Input/Output 4:
1. By Date of Visit
2. By Address
Enter your choice:
Invalid Option
Automatic evaluation[+]
HospitalManagement/PatientRegister.txt
1 WM_J82,Jacey,8734909012,07-08-2001,Colorado
2 WM_L01,Bella,9435678631,21-09-1992,Connecticut
3 WM_52E,Berey,8754321256,20-03-1999,Indiana
4 WM_B83,Cappi,6709543276,13-02-2006,Pennsylvania
5 WM_C23,Anya,7656548798,23-11-2002,Carolina
6 WM_X26,Beatrice,6789567687,18-07-2004,Texas
7 WM_H72,Elise,9809908765,02-12-2005,Washington
8 WM_P10,Fanny,7835627189,02-05-2001,Virginia
9 WM_Q12,Felicity,6792637810,21-05-1997,Colorado
10 WM_K7K,Abigail,8934562718,02-05-2016,Indiana
11 WM_U82,Alice,8352617181,11-05-2012,Indiana
12 WN_P23,Amber,9876567898,12-09-1998,Pennsylvania
13 LM_V20,Gabriella,8302927382,02-05-2006,Connecticut
14 WM_Z05,Hadley,7823919273,02-06-2007,Connecticut
15 WM_T83,Harper,7391027349,08-07-1999,Carolina
16 WM_M03,Iris,9102638491,27-05-2001,Texas
17 WM_N32,Finley,8729196472,12-08-2003,Pennsylvania
18 WM_WQ0,Fiona,7201982219,09-09-2014,Washington
19 WM_Q91,Carny,8976509871,30-12-2003,Virginia
20 WM_P21,Eleanor,8954321378,24-11-2007,Carolina
HospitalManagement/src/InvalidPatientIdException.java
1
2 //public class InvalidPatientIdException{
3 //FILL THE CODE HERE
4 public class InvalidPatientIdException extends Exception{
5 public InvalidPatientIdException(String message){
6 super(message);
7 }
8 }
9
10
11
12
HospitalManagement/src/Main.java
1 public class Main {
2
3 public static void main(String[] args){
4
5 // CODE SKELETON - VALIDATION STARTS
6 // DO NOT CHANGE THIS CODE
7
8 new SkeletonValidator();
9 // CODE SKELETON - VALIDATION ENDS
10
11 // FILL THE CODE HERE
12
13 }
14
15 }
16
17
HospitalManagement/src/Patient.java
1 //DO NOT ADD/EDIT THE CODE
2 public class Patient {
3
4 private String patientId;
5 private String patientName;
6 private String contactNumber;
7 private String dateOfVisit;
8 private String patientAddress;
9
10 //Setters and Getters
11
12 public String getPatientId() {
13 return patientId;
14 }
15 public void setPatientId(String patientId) {
16 this.patientId = patientId;
17 }
18 public String getPatientName() {
19 return patientName;
20 }
21 public void setPatientName(String patientName) {
22 this.patientName = patientName;
23 }
24 public String getContactNumber() {
25 return contactNumber;
26 }
27 public void setContactNumber(String contactNumber) {
28 this.contactNumber = contactNumber;
29 }
30 public String getDateOfVisit() {
31 return dateOfVisit;
32 }
33 public void setDateOfVisit(String dateOfVisit) {
34 this.dateOfVisit = dateOfVisit;
35 }
36 public String getPatientAddress() {
37 return patientAddress;
38 }
39 public void setPatientAddress(String patientAddress) {
40 this.patientAddress = patientAddress;
41 }
42
43
44
45
46 }
47
HospitalManagement/src/PatientUtility.java
1 import java.util.List;
2 import java.util.stream.Stream;
3 import java.util.ArrayList;
4 import java.io.File;
5 import java.io.FileNotFoundException;
6 import java.util.Scanner;
7 import java.util.regex.*;
8 import java.util.stream.Collectors;
9 import java.text.ParseException;
10 import java.text.SimpleDateFormat;
11 import java.util.Date;
12
13
14 public class PatientUtility {
15
16 public List <Patient> fetchPatient(String filePath) {
17
18
19 //FILL THE CODE HERE
20 List <Patient> patients =new ArrayList<>();
21 try{
22 File register =new File(filePath);
23 Scanner reader=new Scanner(register);
24 while(reader.hasNextLine()){
25 Patient p = new Patient();
26 String[] infos=reader.nextLine().split(",");
27 try{
28 if(isValidPatientId(infos[0])){
29 p.setPatientId(infos[0]);
30 p.setPatientName(infos[1]);
31 p.setContactNumber(infos[2]);
32 p.setDateOfVisit(infos[3]);
33 p.setPatientAddress(infos[4]);
34 patients.add(p);
35 }
36 }
37 catch(InvalidPatientIdException e1){
38 System.out.println(e1.getMessage());
39 }
40 }
41 reader.close();
42 }
43 catch(FileNotFoundException e){}
44 return patients;
45
46 //return null;
47 }
48
49
50 public boolean isValidPatientId (String patientId)throws InvalidPatientIdException
51 {
52
53 //FILL THE CODE HERE
54 Pattern p =Pattern.compile("WM_[A-Z][0-9]{2}$");
55 Matcher m=p.matcher(patientId);
56 boolean ne =m.matches();
57 if(!ne){
58 throw new InvalidPatientIdException(patientId+"is an Invalid Patient Id.");
59
60 }
61 //return inValid;
62 return ne;
63 }
64
65
66 public List<Patient> retrievePatientRecords_ByDateOfVisit(Stream<Patient> patientStream, String
fromDate, String toDate)
67 {
68 //FILL THE CODE HERE
69 SimpleDateFormat simpleDateFormat=new SimpleDateFormat("dd-MM-yyyy");
70 return patientStream
71 .filter((p)->{
72 try{
73 Date start=simpleDateFormat.parse(fromDate);
74 Date end= simpleDateFormat.parse(toDate);
75 Date current =simpleDateFormat.parse(p.getDateOfVisit());
76 return start.compareTo(current)*current.compareTo(end)>=0;
77 }
78 catch(ParseException e){}
79 return false;
80 }).collect(Collectors.toList());
81 // return null;
82 }
83
84
85
86 public Stream<Patient> retrievePatientRecords_ByAddress(Stream<Patient> patientStream, String
address)
87 {
88
89 //FILL THE CODE HERE
90 return patientStream.filter(p->address.equals(p.getPatientAddress()));
91 //return null;
92
93
94
95 }
96
97 }
98
HospitalManagement/src/SkeletonValidator.java
1 import java.lang.reflect.Method;
2 import java.util.List;
3 import java.util.logging.Level;
4 import java.util.logging.Logger;
5 import java.util.stream.Stream;
6
7 /**
8 * @author TJ
9 *
10 * This class is used to verify if the Code Skeleton is intact and not modified by participants thereby ensuring
smooth auto evaluation
11 *
12 */
13 public class SkeletonValidator {
14
15 public SkeletonValidator() {
16
17
18 validateClassName("Patient");
19 validateClassName("PatientUtility");
20 validateClassName("InvalidPatientIdException");
21 validateMethodSignature(
22
"fetchPatient:java.util.List,isValidPatientId:boolean,retrievePatientRecords_ByDateOfVisit:java.util.List
,retrievePatientRecords_ByAddress:java.util.stream.Stream",
23 "PatientUtility");
24
25 }
26
27 private static final Logger LOG = Logger.getLogger("SkeletonValidator");
28
29 protected final boolean validateClassName(String className) {
30
31 boolean iscorrect = false;
32 try {
33 Class.forName(className);
34 iscorrect = true;
35 LOG.info("Class Name " + className + " is correct");
36
37 } catch (ClassNotFoundException e) {
38 LOG.log(Level.SEVERE, "You have changed either the " + "class
name/package. Use the correct package "
39 + "and class name as provided in the skeleton");
40
41 } catch (Exception e) {
42 LOG.log(Level.SEVERE,
43 "There is an error in validating the " + "Class Name.
Please manually verify that the "
44 + "Class name is same as
skeleton before uploading");
45 }
46 return iscorrect;
47
48 }
49
50 protected final void validateMethodSignature(String methodWithExcptn, String className) {
51 Class cls = null;
52 try {
53
54 String[] actualmethods = methodWithExcptn.split(",");
55 boolean errorFlag = false;
56 String[] methodSignature;
57 String methodName = null;
58 String returnType = null;
59
60 for (String singleMethod : actualmethods) {
61 boolean foundMethod = false;
62 methodSignature = singleMethod.split(":");
63
64 methodName = methodSignature[0];
65 returnType = methodSignature[1];
66 cls = Class.forName(className);
67 Method[] methods = cls.getMethods();
68 for (Method findMethod : methods) {
69 if (methodName.equals(findMethod.getName())) {
70 foundMethod = true;
71 if
(!(findMethod.getReturnType().getName().equals(returnType))) {
72 errorFlag = true;
73 LOG.log(Level.SEVERE, " You
have changed the " + "return type in '" + methodName
74 + "'
method. Please stick to the " + "skeleton provided");
75
76 } else {
77 LOG.info("Method signature of "
+ methodName + " is valid");
78 }
79
80 }
81 }
82 if (!foundMethod) {
83 errorFlag = true;
84 LOG.log(Level.SEVERE, " Unable to find the given
public method " + methodName
85 + ". Do not change the " + "given
public method name. " + "Verify it with the skeleton");
86 }
87
88 }
89 if (!errorFlag) {
90 LOG.info("Method signature is valid");
91 }
92
93 } catch (Exception e) {
94 LOG.log(Level.SEVERE,
95 " There is an error in validating the " + "method
structure. Please manually verify that the "
96 + "Method signature is same as
the skeleton before uploading");
97 }
98 }
99
100 }
Grade
Reviewed on Monday, 7 February 2022, 6:04 PM by Automatic grade
Grade 100 / 100
Assessment report
Assessment Completed Successfully
[+]Grading and Feedback
=========================================================================
6. Technology Fest
Grade settings: Maximum grade: 100
Run: Yes Evaluate: Yes
Automatic grade: Yes
String collegeName
String eventName
double registrationFee
Requirements:
· To calculate the registration fee of the participant based on the event name.
int counter
EventManagement public void Calculate the registration
calculateRegistrationFee(List fee of the participant
<Participant> list) based on the event name.
If the event name doesn’t
exist, throw an
InvalidEventException
with an error message
“Event Name is invalid”.
EventManagement public void run() Calculate the number of
participants registered for
a particular event.
Increment the counter
attribute based on the
search.
Note: The class and methods should be declared as public and all the attributes should be
declared as private.
Create a class called Main with the main method and perform the tasks are given below:
· Get the event type to search to find the number of the participants registered for that
particular event.
· In the Sample Input / Output provided, the highlighted text in bold corresponds to the input
given by the user and the remaining text represent the output.
· Ensure to provide the names for classes, attributes, and methods as specified in the
question description.
Sample Input/Output 1:
rinu/4/EEE/mnm/robocar
fina/3/EEE/psg/papertalk
rachel/4/civil/kcg/quiz
robocar
Sample Input/Output 2:
rinu/4/EEE/mnm/robocar
fina/3/EEE/psg/papertalk
rachel/4/civil/kcg/quiz
games
No participant found
Sample Input/Output 3:
vishal/4/mech/vjc/flyingrobo
vivek/3/mech/hdl/games
Automatic evaluation[+]
TechnologyFest/src/EventManagement.java
1 import java.util.List;
2
3 public class EventManagement implements Runnable {
4 private List<Participant> TechList;
5 private String searchEvent;
6 private int counter=0;
7 public List<Participant>getTechList()
8 {
9 return TechList;
10
11 }
12 public void setTechList(List<Participant>techList)
13 {
14 TechList=techList;
15 }
16 public String getSearchEvent()
17 {
18 return searchEvent;
19 }
20 public void setSearchEvent(String searchEvent)
21 {
22 this.searchEvent=searchEvent;
23 }
24 public int getCounter()
25 {
26 return counter;
27 }
28 public void setCounter(int counter)
29 {
30 this.counter=counter;
31 }
32 //FILL THE CODE HERE
33
34 public void calculateRegistrationFee(List<Participant> list) throws InvalidEventException
35
36 {
37 for(Participant p:list)
38 {
39 if(p.getEventName().equalsIgnoreCase("robocar"))
40 {
41 p.setRegistrationFee(1000);
42 }
43 else if(p.getEventName().equalsIgnoreCase("papertalk")){
44 p.setRegistrationFee(500);
45
46 }
47
48 else if(p.getEventName().equalsIgnoreCase("quiz")){
49 p.setRegistrationFee(300);
50 }
51 else if(p.getEventName().equalsIgnoreCase("games")){
52 p.setRegistrationFee(100);
53 }
54 else{
55 throw new InvalidEventException("Event Name is Invalid");
56 }
57 }
58 //FILL THE CODE HERE
59 setTechList(list);
60 }
61
62 public void run()
63 {
64 String str="robocarpapertalkquizgames";
65 if(str.contains(this.getSearchEvent())){
66 for(Participant P:this.getTechList()){
67 if(this.getSearchEvent().equals(P.getEventName())){
68 counter++;
69 }
70 }
71 }
72 setCounter(counter);
73
74 //FILL THE CODE HERE
75
76 }
77 }
78
TechnologyFest/src/InvalidEventException.java
1 public class InvalidEventException extends Exception{
2 //FILL THE CODE HERE
3 public InvalidEventException(String str){
4 super(str);
5
6}
7
8}
9
TechnologyFest/src/Main.java
1
2 import java.util.Scanner;
3 import java.util.*;
4 public class Main {
5 public static void main(String [] args)
6 {
7 // CODE SKELETON - VALIDATION STARTS
8 // DO NOT CHANGE THIS CODE
9
10 new SkeletonValidator();
11
12 // CODE SKELETON - VALIDATION ENDS
13
14 Scanner sc=new Scanner(System.in);
15 System.out.println("Enter the number of entries");
16 int n=sc.nextInt();
17 System.out.println("Enter the Participant
Name/Yearofstudy/Department/CollegeName/EventName");
18 List<Participant> list=new ArrayList<Participant>();
19 String strlist[]=new String[n];
20 for(int i=0;i<n;i++)
21 {
22 strlist[i]=sc.next();
23 String a[]=strlist[i].split("/");
24 Participant pt=new Participant(a[0],a[1],a[2],a[3],a[4]);
25 list.add(pt);
26 }
27 EventManagement em=new EventManagement();
28 try {
29 em.calculateRegistrationFee(list);
30 }
31 catch(InvalidEventException e)
32 {
33 e.printStackTrace();
34
35 }
36 System.out.println("Print participant details");
37 for(Participant p:list)
38 {
39 System.out.println(p);
40 }
41 System.out.println("Enter the event to search");
42 String srch=sc.nextLine();
43 em.setSearchEvent(srch);
44 em.run();
45 int count=em.getCounter();
46 if(count<=0){
47 System.out.println("No participant found");
48
49 }
50 else{
51 System.out.println("Number of participants for"+srch+"event is "+count); }
52 }
53 }
54
55
56
57
TechnologyFest/src/Participant.java
1 public class Participant {
2 private String name;
3 private String yearofstudy;
4 private String department;
5 private String collegeName;
6 private String eventName;
7 private double registrationFee;
8
9 //5 argument Constructor
10 public Participant(String name, String yearofstudy, String department, String collegeName, String
eventName) {
11 super();
12 this.name = name;
13 this.yearofstudy = yearofstudy;
14 this.department = department;
15 this.collegeName = collegeName;
16 this.eventName = eventName;
17 }
18
19 public String getName() {
20 return name;
21 }
22 public void setName(String name) {
23 this.name = name;
24 }
25 public String getYearofstudy() {
26 return yearofstudy;
27 }
28 public void setYearofstudy(String yearofstudy) {
29 this.yearofstudy = yearofstudy;
30 }
31 public String getDepartment() {
32 return department;
33 }
34 public void setDepartment(String department) {
35 this.department = department;
36 }
37 public String getCollegeName() {
38 return collegeName;
39 }
40 public void setCollegeName(String collegeName) {
41 this.collegeName = collegeName;
42 }
43 public String getEventName() {
44 return eventName;
45 }
46 public void setEventName(String eventName) {
47 this.eventName = eventName;
48 }
49 public double getRegistrationFee() {
50 return registrationFee;
51 }
52 public void setRegistrationFee(double registrationFee) {
53 this.registrationFee = registrationFee;
54 }
55
56 @Override
57 public String toString() {
58 return "Participant [name=" + name + ", yearofstudy=" + yearofstudy + ", department=" +
department
59 + ", collegeName=" + collegeName + ", eventName=" +
eventName + ", registrationFee=" + registrationFee
60 + "]";
61 }
62
63
64
65
66 }
67
TechnologyFest/src/SkeletonValidator.java
1
2 import java.lang.reflect.Method;
3 import java.util.List;
4 import java.util.logging.Level;
5 import java.util.logging.Logger;
6 import java.util.stream.Stream;
7
8 /**
9 * @author TJ
10 *
11 * This class is used to verify if the Code Skeleton is intact and not modified by participants thereby ensuring
smooth auto evaluation
12 *
13 */
14 public class SkeletonValidator {
15
16 public SkeletonValidator() {
17
18 //classes
19 validateClassName("Main");
20 validateClassName("EventManagement");
21 validateClassName("Participant");
22 validateClassName("InvalidEventException");
23 //functional methods
24 validateMethodSignature(
25 "calculateRegistrationFee:void","EventManagement");
26 validateMethodSignature(
27 "run:void","EventManagement");
28
29 //setters and getters of HallHandler
30 validateMethodSignature(
31 "getTechList:List","EventManagement");
32 validateMethodSignature(
33 "setTechList:void","EventManagement");
34
35 validateMethodSignature(
36 "getCounter:int","EventManagement");
37 validateMethodSignature(
38 "setCounter:void","EventManagement");
39
40 validateMethodSignature(
41 "getSearchEvent:String","EventManagement");
42 validateMethodSignature(
43 "setSearchEvent:void","EventManagement");
44
45 //setters and getters of Hall
46 validateMethodSignature(
47 "getName:String","Participant");
48 validateMethodSignature(
49 "setName:void","Participant");
50
51 validateMethodSignature(
52 "getYearofstudy:String","Participant");
53 validateMethodSignature(
54 "setYearofstudy:void","Participant");
55
56 validateMethodSignature(
57 "getDepartment:String","Participant");
58 validateMethodSignature(
59 "setDepartment:void","Participant");
60
61 validateMethodSignature(
62 "getCollegeName:String","Participant");
63 validateMethodSignature(
64 "setCollegeName:void","Participant");
65
66 validateMethodSignature(
67 "getEventName:String","Participant");
68 validateMethodSignature(
69 "setEventName:void","Participant");
70
71 validateMethodSignature(
72 "getRegistrationFee:double","Participant");
73 validateMethodSignature(
74 "setRegistrationFee:void","Participant");
75
76 }
77
78 private static final Logger LOG = Logger.getLogger("SkeletonValidator");
79
80 protected final boolean validateClassName(String className) {
81
82 boolean iscorrect = false;
83 try {
84 Class.forName(className);
85 iscorrect = true;
86 LOG.info("Class Name " + className + " is correct");
87
88 } catch (ClassNotFoundException e) {
89 LOG.log(Level.SEVERE, "You have changed either the " + "class
name/package. Use the correct package "
90 + "and class name as provided in the skeleton");
91
92 } catch (Exception e) {
93 LOG.log(Level.SEVERE,
94 "There is an error in validating the " + "Class Name.
Please manually verify that the "
95 + "Class name is same as
skeleton before uploading");
96 }
97 return iscorrect;
98
99 }
100
101 protected final void validateMethodSignature(String methodWithExcptn, String className) {
102 Class cls = null;
103 try {
104
105 String[] actualmethods = methodWithExcptn.split(",");
106 boolean errorFlag = false;
107 String[] methodSignature;
108 String methodName = null;
109 String returnType = null;
110
111 for (String singleMethod : actualmethods) {
112 boolean foundMethod = false;
113 methodSignature = singleMethod.split(":");
114
115 methodName = methodSignature[0];
116 returnType = methodSignature[1];
117 cls = Class.forName(className);
118 Method[] methods = cls.getMethods();
119 for (Method findMethod : methods) {
120 if (methodName.equals(findMethod.getName())) {
121 foundMethod = true;
122 if
(!(findMethod.getReturnType().getName().contains(returnType))) {
123 errorFlag = true;
124 LOG.log(Level.SEVERE, " You
have changed the " + "return type in '" + methodName
125 + "'
method. Please stick to the " + "skeleton provided");
126
127 } else {
128 LOG.info("Method signature of "
+ methodName + " is valid");
129 }
130
131 }
132 }
133 if (!foundMethod) {
134 errorFlag = true;
135 LOG.log(Level.SEVERE, " Unable to find the given
public method " + methodName
136 + ". Do not change the " + "given
public method name. " + "Verify it with the skeleton");
137 }
138
139 }
140 if (!errorFlag) {
141 LOG.info("Method signature is valid");
142 }
143
144 } catch (Exception e) {
145 LOG.log(Level.SEVERE,
146 " There is an error in validating the " + "method
structure. Please manually verify that the "
147 + "Method signature is same as
the skeleton before uploading");
148 }
149 }
150
151 }
Grade
Reviewed on Monday, 7 February 2022, 6:34 PM by Automatic grade
Grade 74 / 100
Assessment report
Fail 1 -- test4CheckTheOutput::
$Expected output:"[Print participant details
ParticipantName=Weni
Yearofstudy=3
Department=civil
CollegeName=vjc
EventName=robocar
RegistrationFee=1000.0
ParticipantName=gina
Yearofstudy=2
Department=mech
CollegeName=vjc
EventName=quiz
RegistrationFee=300.0
ParticipantName=jos
Yearofstudy=4
Department=ece
CollegeName=vjec
EventName=games
RegistrationFee=100.0
ParticipantName=fida
Yearofstudy=1
Department=eee
CollegeName=vjec
EventName=papertalk
RegistrationFee=500.0
Enter the event to search
Number of participants for PAPERTALK event is 1]" Actual output:"[Enter the number of
entries
Enter the Participant Name/Yearofstudy/Department/CollegeName/EventName
Print participant details
Participant [name=Weni
yearofstudy=3
department=civil
collegeName=vjc
eventName=robocar
registrationFee=1000.0]
Participant [name=gina
yearofstudy=2
department=mech
collegeName=vjc
eventName=quiz
registrationFee=300.0]
Participant [name=jos
yearofstudy=4
department=ece
collegeName=vjec
eventName=games
registrationFee=100.0]
Participant [name=fida
yearofstudy=1
department=eee
collegeName=vjec
eventName=papertalk
registrationFee=500.0]
Enter the event to search
No participant found]"$
Check your code with the input :Weni/3/civil/vjc/robocar
gina/2/mech/vjc/quiz
jos/4/ece/vjec/games
fida/1/eee/vjec/papertalk
Fail 2 -- test6CheckTheOutputfor_NCount::
$Expected output:"[Print participant details
ParticipantName=philip
Yearofstudy=4
Department=eee
CollegeName=mvc
EventName=robocar
RegistrationFee=1000.0
ParticipantName=susan
Yearofstudy=4
Department=eee
CollegeName=mvc
EventName=robocar
RegistrationFee=1000.0
ParticipantName=vivek
Yearofstudy=3
Department=civil
CollegeName=mvc
EventName=quiz
RegistrationFee=300.0
ParticipantName=vishal
Yearofstudy=3
Department=civil
CollegeName=mvc
EventName=papertalk
RegistrationFee=500.0
Enter the event to search
Number of participants for ROBOCAR event is 2]" Actual output:"[Enter the number of
entries
Enter the Participant Name/Yearofstudy/Department/CollegeName/EventName
Print participant details
Participant [name=philip
yearofstudy=4
department=eee
collegeName=mvc
eventName=robocar
registrationFee=1000.0]
Participant [name=susan
yearofstudy=4
department=eee
collegeName=mvc
eventName=robocar
registrationFee=1000.0]
Participant [name=vivek
yearofstudy=3
department=civil
collegeName=mvc
eventName=quiz
registrationFee=300.0]
Participant [name=vishal
yearofstudy=3
department=civil
collegeName=mvc
eventName=papertalk
registrationFee=500.0]
Enter the event to search
No participant found]"$
Check your code with the input :philip/4/eee/mvc/robocar
susan/4/eee/mvc/robocar
vivek/3/civil/mvc/quiz
vishal/3/civil/mvc/papertalk
robocar
Obtained Pass Percentage. Still few testcases failed . Kindly revisit the Solution
[+]Grading and Feedback
Powered by
====================================================================
ZeeZee Bank
Account.java
public class Account {
private long accountNumber;
private double balanceAmount;
return false;
}
}
Main.java
import java.text.DecimalFormat;
import java.util.Scanner;
if (!isWithdrawn) {
System.out.println("Insufficient balance");
}
Numerology number
Main.java
import java.util.Scanner;
return sum;
}
while (string.length() != 1) {
string = String.valueOf(getSum(Long.parseLong(string)));
}
return Integer.parseInt(string);
}
return oddCount;
}
return evenCount;
}
System.out.println("Sum of digits");
System.out.println(getSum(num));
System.out.println("Numerology number");
System.out.println(getNumerology(num));
if (Character.isLowerCase(ch)) {
int sub = (int) ch - 7;
stringBuilder.append(ch);
} else if (Character.isWhitespace(ch)) {
stringBuilder.append(ch);
}
}
if (flag) {
System.out.println("Decrypted text:");
System.out.println(stringBuilder.toString());
} else {
System.out.println("No hidden message");
}
}
}
CurrentAccount.java
public class CurrentAccount extends Account implements MaintenanceCharge {
public CurrentAccount(String accountNumber, String customerName, double balance) {
super(accountNumber, customerName, balance);
}
@Override
public float calculateMaintenanceCharge(float noOfYears) {
return (100.0f + noOfYears) + 200.0f;
}
}
MaintenanceCharge.java
public interface MaintenanceCharge {
float calculateMaintenanceCharge(float noOfYears);
}
SavingsAccount.java
public class SavingsAccount extends Account implements MaintenanceCharge {
public SavingsAccount(String accountNumber, String customerName, double balance) {
super(accountNumber, customerName, balance);
}
@Override
public float calculateMaintenanceCharge(float noOfYears) {
return (50.0f * noOfYears) + 50.0f;
}
}
UserInterface.java
import java.text.DecimalFormat;
import java.util.Scanner;
switch (choice) {
case 1: {
SavingsAccount savingsAccount = new SavingsAccount(accountNumber,
customerName, balance);
System.out.println("Maintenance Charge for Savings Account is Rs " +
decimalFormat.format(savingsAccount.calculateMaintenanceCharge(noOfYears)));
break;
}
case 2: {
CurrentAccount currentAccount = new CurrentAccount(accountNumber,
customerName, balance);
System.out.println("Maintenance Charge for Current Account is Rs " +
decimalFormat.format(currentAccount.calculateMaintenanceCharge(noOfYears)));
}
}
}
}
Batting Average
UserInterface.java
package com.ui;
import com.utility.Player;
import java.util.ArrayList;
import java.util.Scanner;
while (flag) {
System.out.println("1. Add Runs Scored");
System.out.println("2. Calculate average runs scored");
System.out.println("3. Exit");
System.out.println("Enter your choice");
int choice = scanner.nextInt();
switch (choice) {
case 1: {
System.out.println("Enter the runs scored");
int score = scanner.nextInt();
player.addScoreDetails(score);
break;
}
case 2: {
System.out.println("Average runs secured");
System.out.println(player.getAverageRunScored());
break;
}
case 3: {
System.out.println("Thank you for use the application");
flag = false;
break;
}
}
}
}
}
Player.java
package com.utility;
import java.util.List;
Grade Calculation
Main.java
import java.util.Scanner;
@Override
public void run() {
int totalMarks = 0;
@Override
public String toString() {
return id;
}
@Override
public int compareTo(Employee employee) {
return this.id.compareTo(employee.getId());
}
}
try {
LocalDate joiningDate = LocalDate.parse(joiningDateStr, dateTimeFormatter);
Employee employee = new Employee(id, joiningDate);
employee.setIsEligible(now);
employees.add(employee);
} catch (Exception ignore) {
System.out.println("Invalid date format");
System.exit(0);
}
});
List<Employee> filteredEmployees =
employees.stream().filter(Employee::getIsEligible).collect(Collectors.toList());
if (filteredEmployees.isEmpty()) {
System.out.println("No one is eligible");
} else {
Collections.sort(filteredEmployees);
filteredEmployees.forEach(System.out::println);
}
}
}
NumberTypeUtility.java
import java.util.Scanner;
if (idOdd().checkNumber(num)) {
System.out.println(num + " is odd");
} else {
System.out.println(num + " is not odd");
}
}
}
DB.java
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class DB {
//ENSURE YOU DON'T CHANGE THE BELOW CODE WHEN YOU SUBMIT
public static Connection getConnection() throws ClassNotFoundException,
SQLException {
try{
FlightManagementSystem.java
import java.util.*;
import java.sql.*;
public class FlightManagementSystem{
public ArrayList<Flight> viewFlightsBySourceDestination(String source, String destination){
DB db=new DB();
ArrayList<Flight> list=new ArrayList<Flight>();
try{
int f=0;
Connection con=db.getConnection();
Statement st=con.createStatement();
String sql= "select * from Flight where source= '"+source+"' and destination=
'"+destination+"'";
ResultSet rs=st.executeQuery(sql);
while(rs.next()){
f=1;
Flight x=new Flight(rs.getInt(1), rs.getString(2),rs.getString(3), rs.getInt(4),
rs.getDouble(5));
list.add(x);
}
con.close();
if(f==1)
return list;
else
return null;
}
catch(SQLException e){
System.out.println("SQL Error. Contact Administrator.");
return null;
}
catch(Exception e){
System.out.println("Exception. Contact Administrator.");
return null;
}
}
}
Flight.java
Perform Calculation
import java.util.Scanner;
int a = sc.nextInt();
int b= sc.nextInt();
System.out.println("The difference is
"+Perform_subtraction.performCalculation(a,b));
return Perform_calculation;
}
return Perform_calculation;
return Perform_calculation;
float c = (float)a;
float d = (float)b;
return (c/d);
};
return Perform_calculation;
GD HOSPITAL
Payment Inheritance
Bill.java
public class Bill {
String message = "Payment not done and your due amount is "+obj.getDueAmount();
if(obj instanceof Cheque ) {
if(cheque.payAmount())
if(cash.payAmount())
if(card.payAmount())
return message;
Cash.java
public class Cash extends Payment{
this.cashAmount = cashAmount;
@Override
Cheque.java
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
this.dateOfIssue = dateOfIssue;
@Override
try {
Date issueDate = new SimpleDateFormat("dd-MM-yyyy").parse(date);
setDateOfIssue(issueDate);
}
catch (ParseException e) {
e.printStackTrace();
}
}
}
Credit.java
public class Credit extends Payment {
return creditCardNo;
this.creditCardNo = creditCardNo;
return cardType;
this.cardType = cardType;
return creditCardAmount;
@Override
int tax = 0;
switch(cardType) {
case "silver":
setCreditCardAmount(10000);
setCreditCardAmount(getCreditCardAmount()-tax);
isDeducted = true;
break;
case "gold":
setCreditCardAmount(50000);
setCreditCardAmount(getCreditCardAmount()-tax);
isDeducted = true;
}
break;
case "platinum":
setCreditCardAmount(100000);
setCreditCardAmount(getCreditCardAmount()-tax);
isDeducted = true;
break;
return isDeducted;
Main.java
import java.util.Scanner;
switch (mode) {
case "cash":
cash.setCashAmount(cashAmount);
cash.setDueAmount(dueAmount);
System.out.println(bill.processPayment(cash));
break;
case "cheque":
cheque.setChequeAmount(chequeAmount);
cheque.setChequeNo(number);
cheque.generateDate(date);
cheque.setDueAmount(dueAmount);
System.out.println(bill.processPayment(cheque));
break;
case "credit":
credit.setCardType(cardType);
credit.setCreditCardNo(creditNumber);
credit.setDueAmount(dueAmount);
System.out.println(bill.processPayment(credit));
default:
break;
sc.close();
Payment.java
public class Payment {
return dueAmount;
}
this.dueAmount = dueAmount;
return false;
HUNGER EATS
package com.utility;
import java.util.*;
import com.bean.FoodProduct;
public class Order{
private double discountPercentage;
private List<FoodProduct> foodList=new ArrayList<FoodProduct>();
}
// System.out.println(bill);
// System.out.println(dis);
bill=bill-((bill*discountPercentage)/100);
return bill;
}
}
package com.ui;
import java.util.Scanner;
import com.utility.Order;
import com.bean.FoodProduct;
for(int i=0;i<itemno;i++)
{
FoodProduct fd=new FoodProduct();
System.out.println("Enter the item id");
fd.setFoodId(sc.nextInt());
System.out.println("Enter the item name");
fd.setFoodName(sc.next());
System.out.println("Enter the cost per unit");
fd.setCostPerUnit(sc.nextDouble());
System.out.println("Enter the quantity");
fd.setQuantity(sc.nextInt());
o.addToCart(fd);
}
}
package com.bean;
Singapore
import java.util.*;
public class tourism {
static String name;
static String place;
static int days;
static int tickets;
static double price = 0.00;
static double total = 0.00;
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Enter the passenger name");
name = in.nextLine();
System.out.println("Enter the place name");
place=in.nextLine();
if(place.equalsIgnoreCase("beach")
||place.equalsIgnoreCase("pilgrimage")||place.equalsIgnoreCase("heritage")||place.equalsIgno
reCase("Hills")||place.equalsIgnoreCase("palls")||place.equalsIgnoreCase("adventure")){
System.out.println("Enter the number of days");
days = in.nextInt();
if(days>0){
System.out.println("Enter the number of Tickets");
tickets = in.nextInt();
if(tickets>0){
if(place.equalsIgnoreCase("beach")){
price = tickets*270;
if(price>1000){
total = 85*price/100;
System.out.printf("Price:%.2f",total);
}
else {
System.out.printf("Price:%.2f",price);
}
}
else if(place.equalsIgnoreCase("prilgrimage")){
price = tickets*350;
if(price>1000){
total = 85*price/100;
System.out.printf("Price:%.2f",total);
}
else {
System.out.printf("Price:%.2f",price);
}
}
else if(place.equalsIgnoreCase("heritage")){
price = tickets*430;
if(price>1000){
total = 85*price/100;
System.out.printf("Price:%.2f",total);
}
else {
System.out.printf("Price:%.2f",price);
}
}
else if(place.equalsIgnoreCase("hills")){
price = tickets*780;
if(price>1000){
total = 85*price/100;
System.out.printf("Price:%.2f",total);
}
else {
System.out.printf("Price:%.2f",price);
}
}
else if(place.equalsIgnoreCase("palls")){
price = tickets*1200;
if(price>1000){
total = 85*price/100;
System.out.printf("Price:%.2f",total);
}
else {
System.out.printf("Price:%.2f",price);
}
}
else {
price = tickets*4500;
if(price>1000){
total = 85*price/100;
System.out.printf("Price:%.2f",total);
}
else {
System.out.printf("Price:%.2f",price);
}
}
}
else{
System.out.println(tickets+" is an Invalid no. of tickets");
}
}
else{
System.out.println(days+" is an Invalid no. of days");
}
}
else {
System.out.println(place+" is an Invalid place");
}
}
}
Prime no ending
import java.util.*;
public class Main
{
public static void main (String[] args) {
int flag=0, k=0, z=0;
Scanner sc =new Scanner(System.in );
System.out.println("Enter the first number");
int f=sc.nextInt();
System.out.println("Enter the last number");
int l=sc.nextInt();
for(int i=f; i<=l; i++)
{
for(int j=2; j<i; j++)// this loop increments flag if i is divisible by j
{
if(i%j==0)
{
flag++;
}
}
if(i==l && (flag!=0 || i%10!=1))//when last number is not a prime
{
while(z==0)
{
for(int a=2; a<i; a++)
{
if(i%a==0)
{
flag++;
}
}
if(i%10==1 && flag==0)
{
System.out.print(","+i);
z++;
}
flag=0;
i++;
}
}
if(i%10==1 && flag==0)//to check for last digit 1 and prime
{
if(k==0)
{
System.out.print(i);
k++;
}
else
{
System.out.print(","+i);
}
}
flag=0;
}
}
}
Query Set
public class Query {
import java.util.Scanner;
public class TestApplication {
public static void main(String[] args) {
Query query = new Query();
Scanner sc = new Scanner(System.in);
Query.DataSet primary = query.new DataSet();
Query.DataSet secondary = query.new DataSet();
System.out.println("Enter the Details of primary data set");
System.out.println("Enter the theatre id");
String theatreid = sc.next();
primary.setTheatreId(theatreid);
sc.nextLine();
System.out.println("Enter the theatre name");
String theatrename = sc.next();
primary.setTheatreName(theatrename);
sc.nextLine();
System.out.println("Enter the location");
String location = sc.next();
primary.setLocation(location);
sc.nextLine();
System.out.println("Entrer the no of screens");
int screens = sc.nextInt();
primary.setNoOfScreen(screens);
System.out.println("Ente the ticket cost");
double cost = sc.nextDouble();
primary.setTicketCost(cost);
System.out.println("ENter the details of secondary data set");
System.out.println("Enter the theatre id");
theatreid = sc.next();
secondary.setTheatreId(theatreid);
sc.nextLine();
System.out.println("Enter the theatre name");
theatrename = sc.next();
secondary.setTheatreName(theatrename);
sc.nextLine();
System.out.println("Enter the location");
location = sc.next();
secondary.setLocation(location);
sc.nextLine();
System.out.println("Entrer the no of screens");
screens = sc.nextInt();
secondary.setNoOfScreen(screens);
System.out.println("Ente the ticket cost");
cost = sc.nextDouble();
secondary.setTicketCost(cost);
System.out.println("Enter the query id");
String queryid = sc.next();
query.setQueryId(queryid);
sc.nextLine();
System.out.println("Enter the query category");
String querycategory = sc.next();
query.setQueryCategory(querycategory);
sc.nextLine();
query.setPrimaryDataset(primary);
query.setSecondaryDataSet(secondary);
System.out.println(query);
}
}
Extract book
import java.util.Scanner;
class ExtractBook {
switch (code) {
case 101:
return "Accounting";
case 102:
return "Economics";
case 103:
return "Engineering";
}
try {
int dCode = extractDepartmentCode(str);
String dString = extractDepartmentName(dCode);
int year = extractDate(str);
int pages = extractNumberOfPages(str);
String bookId = extractBookId(str);
} catch (Error e) {
System.out.println(e.getMessage());
}
}
Fixed deposit
import java.util.*;
class FDScheme {
Annual Salary
import java.io.*;
public class Main
{
public static void main(String[] args)throws IOException
{
// Scanner sc=new Scanner(System.in);
//Fill the code
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Employee Name");
String name=br.readLine();
System.out.println("Enter percentage of salary");
double percent=Double.parseDouble(br.readLine());
if(percent>0&&percent<20)
{
System.out.println("Enter the Year of Experience");
int time=Integer.parseInt(br.readLine());
if(time>0&&time<15)
{
double permonth=12000+(2000*(time));
double dayshift=permonth*6;
double nightshift=(((permonth*percent)/100)+permonth)*6;
double annualIncome=dayshift+nightshift;
}
else{
System.out.println((int)time+" is an invalid year of experience");}
}
else
System.out.println((int)percent+" is an invalid percentage");
}
}
Amity Passenger
import java.util.*;
public class PassengerAmenity {
if(no>0)
{
String name[]=new String[no];
String seat[]=new String[no];
String arr[]=new String[no];
for(int i=0;i<no;i++)
{
System.out.println("Enter the name of the passenger "+(i+1));
String str=sc.nextLine();
name[i]=str.toUpperCase();
int r=Integer.parseInt(seat[i].substring(1,seat[i].length()));
else
{
System.out.println(r+" is invalid seat number");
break;
}
}
else
{
System.out.println(seat[i].charAt(0)+" is invalid coach");
break;
}
arr[i]=name[i]+" "+seat[i];
}
if(count==seat.length)
{
Arrays.sort(seat);
for(int i=seat.length-1;i>=0;i--)
{
for(int j=0;j<arr.length;j++)
{
if(arr[j].contains(seat[i]))
{
System.out.println(arr[j]);
}
}
}
}
}
else
{
System.out.println(no+" is invalid input");
}
}
Club Member
import java.util.Scanner;
this.membershipFees=(double) 50000.0;
}
else if(!(memberType=="Premium"))
{
this.membershipFees=(double) 75000.0;
}
System.out.println("Member Id is "+this.memberId);
System.out.println("Member Name is "+this.memberName);
System.out.println("Member Type is "+this.memberType);
System.out.println("Membership Fees is "+this.membershipFees);
}
}
1. AirVoice - Registration
SmartBuy is a leading mobile shop in the town. After buying a product, the customer needs to
provide a few personal details for the invoice to be generated.
You being their software consultant have been approached to develop software to retrieve the
personal details of the customers, which will help them to generate the invoice faster.
String emailId
int age
Get the details as shown in the sample input and assign the value for its attributes using the
setters.
Display the details as shown in the sample output using the getters method.
In the Sample Input / Output provided, the highlighted text in bold corresponds to the input
given by the user and the rest of the text represents the output.
Ensure to provide the names for classes, attributes and methods as specified in the question.
Sample Input 1:
john
9874561230
32
Sample Output 1:
Name:john
ContactNumber:9874561230
EmailId:[email protected]
Age:32
Automatic evaluation[+]
Customer.java
Main.java
1 import java.util.Scanner;
2
3 public class Main {
4
5 public static void main(String[] args) {
6 // TODO Auto-generated method stub
7 Scanner sc=new Scanner(System.in);
8 Customer c=new Customer();
9 System.out.println("Enter the Name:");
10 String name=(sc.nextLine());
11 System.out.println("Enter the ContactNumber:");
12 long no=sc.nextLong();
13 sc.nextLine();
14 System.out.println("Enter the EmailId:");
15 String mail=sc.nextLine();
16
17 System.out.println("Enter the Age:");
18 int age=sc.nextInt();
19 c.setCustomerName(name);
20 c.setContactNumber(no);
21 c.setEmailId(mail);
22 c.setAge(age);
23 System.out.println("Name:"+c.getCustomerName());
24 System.out.println("ContactNumber:"+c.getContactNumber());
25 System.out.println("EmailId:"+c.getEmailId());
26 System.out.println("Age:"+c.getAge());
27
28
29
30 }
31
32 }
Grade
Reviewed on Monday, 7 February 2022, 4:45 PM by Automatic grade
Grade 100 / 100
Assessment report
[+]Grading and Feedback
=================================================================================
2. Payment - Inheritance
Grade settings: Maximum grade: 100
Run: Yes Evaluate: Yes
Automatic grade: Yes Maximum execution time: 16 s
Payment Status
Roy is a wholesale cloth dealer who sells cloth material to the local tailors on monthly
installments. At the end of each month, he collects the installment amount from all his customers.
Some of his customers pay by Cheque, some pay by Cash and some by Credit Card. He wants
to automate this payment process.
The application needs to verify the payment process and display the status report of payment by
getting the inputs like due amount, payment mode and data specific to the payment mode from
the user and calculate the balance amount.
Note:
Date
dateOfIssue
Make payment Cheque public boolean This is an overridden method
for EMI payAmount() of the parent class. It should
amount return true if the cheque is
valid and the amount is valid.
Else return false.
Note:
int
creditCardAmount
Make Credit public boolean This is an overridden method of
payment for payAmount() the parent class. It should deduct
EMI amount the dueAmount and service tax
from the creditCardAmount and
return true if the credit card
payment was done successfully.
Else return false.
Note:
· The payment can be done if the credit card amount is greater than or equal to the sum of
due amount and service tax. Else payment cannot be made.
· The cardType can be “silver” or “gold” or “platinum”. Set the creditCardAmount based on
the cardType.
· The boolean payAmount() method should deduct the due amount and the service tax
amount from a credit card. If the creditCardAmount is less than the dueAmount+serviceTax, then
the payment cannot be made.
· The balance in credit card amount after a successful payment should be updated in the
creditCardAmount by deducting the sum of dueAmount and serviceTax from creditCardAmount
itself.
Note:
· If the payment is successful, processPayment method should return a message “Payment
done successfully via cash” or “Payment done successfully via cheque” or “Payment done
successfully via creditcard. Remaining amount in your <<cardType>> card is <<balance in
CreditCardAmount>>”
· If the payment is a failure, then return a message “Payment not done and your due amount
is <<dueAmount>>”
Create a public class Main with the main method to test the application.
Note:
· In the Sample Input / Output provided, the highlighted text in bold corresponds to the input
given by the user and the rest of the text represents the output.
· Ensure to provide the names for classes, attributes and methods as specified in the
question.
Sample Input 1:
3000
Enter the mode of payment(cheque/cash/credit):
cash
Enter the cash amount:
2000
Sample Output 1:
Sample Input 2:
3000
Enter the mode of payment(cheque/cash/credit):
cash
Enter the cash amount:
3000
Sample Output 2:
Sample Input 3:
3000
Enter the mode of payment(cheque/cash/credit):
cheque
Enter the cheque number:
123
Enter the cheque amount:
3000
Enter the date of issue:
21-08-2019
Sample Output 3:
Sample Input 4:
3000
Enter the mode of payment(cheque/cash/credit):
credit
Enter the credit card number:
234
Enter the card type(silver,gold,platinum):
silver
Sample Output 4:
Payment done successfully via credit card. Remaining amount in your silver card is 6940
Automatic evaluation[+]
Main.java
1 import java.text.ParseException;
2 import java.text.SimpleDateFormat;
3 import java.util.Date;
4 import java.util.Scanner;
5 public class Main {
6
7 public static void main(String[] args) {
8
9 Scanner sc=new Scanner(System.in);
10 System.out.println("Enter the due amount:");
11 int dueAmount=sc.nextInt();
12
13 System.out.println("Enter the mode of payment(cheque/cash/credit):");
14 String mode=sc.next();
15 Bill b = new Bill();
16 if(mode.equals("cheque"))
17 {
18 System.out.println("enter the cheque number:");
19 String chequeNumber=sc.next();
20 System.out.println("enter the cheque amount:");
21 int chequeAmount=sc.nextInt();
22 System.out.println("enter the date of issue:");
23 String date=sc.next();
24 SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
25 Date dateOfIssue=null;
26 try
27 {
28 dateOfIssue = dateFormat.parse(date);
29 }
30 catch (ParseException e)
31 {
32
33 }
34 Cheque cheque= new Cheque();
35 cheque.setChequeNo(chequeNumber);
36 cheque.setChequeAmount(chequeAmount);
37 cheque.setDateOfIssue(dateOfIssue);
38 cheque.setDueAmount(dueAmount);
39 System.out.println(b.processPayment(cheque));
40 }
41 else if(mode.equals("cash"))
42 {
43 System.out.println("enter the cash amount:");
44 int CashAmount=sc.nextInt();
45 Cash cash=new Cash();
46 cash.setCashAmount(CashAmount);
47 cash.setDueAmount(dueAmount);
48 System.out.println(b.processPayment(cash));
49 }
50 else if(mode.equals("credit"))
51 {
52 System.out.println("enter the credit card number:");
53 int creditCardNumber=sc.nextInt();
54 System.out.println("enter the card type:");
55 String cardType=sc.next();
56
57 Credit credit=new Credit();
58 credit.setCreditCardNo(creditCardNumber);
59 credit.setCardType(cardType);
60 credit.setDueAmount(dueAmount);
61 System.out.println(b.processPayment(credit));
62 }
63 }
64 }
Payment.java
1 public class Payment {
2 private int dueAmount;
3
4 public boolean payAmount()
5 {
6 if(dueAmount == 0)
7 return true;
8 else
9 return false;
10 }
11
12 public int getDueAmount() {
13 return dueAmount;
14 }
15
16 public void setDueAmount(int dueAmount) {
17 this.dueAmount = dueAmount;
18 }
19 }
Cheque.java
1 import java.text.ParseException;
2 import java.text.SimpleDateFormat;
3 import java.util.Date;
4 public class Cheque extends Payment {
5 String chequeNo;
6 int chequeAmount;
7 Date dateOfIssue;
8 public String getChequeNo() {
9 return chequeNo;
10 }
11 public void setChequeNo(String chequeNo) {
12 this.chequeNo = chequeNo;
13 }
14 public int getChequeAmount() {
15 return chequeAmount;
16 }
17 public void setChequeAmount(int chequeAmount) {
18 this.chequeAmount = chequeAmount;
19 }
20 public Date getDateOfIssue() {
21 return dateOfIssue;
22 }
23 public void setDateOfIssue(Date dateOfIssue) {
24 this.dateOfIssue = dateOfIssue;
25 }
26
27 @Override
28 public boolean payAmount()
29 {
30 SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
31 Date today = new Date();
32 try
33 {
34 today = format.parse("01-01-2020");
35 }
36 catch (ParseException e)
37 {
38 return false;
39 }
40 long diff = today.getTime()-dateOfIssue.getTime();
41 int day = (int) Math.abs(diff/(1000*60*60*24));
42 int month = day/30;
43 if(month <=6)
44 {
45
46 if(chequeAmount>=getDueAmount())
47 {
48 return true;
49 }
50 else
51 return false;
52
53 }
54 else
55 return false;
56 }
57
58
59 }
Cash.java
1 public class Cash extends Payment {
2 int cashAmount;
3
4 public int getCashAmount() {
5 return cashAmount;
6 }
7
8 public void setCashAmount(int cashAmount) {
9 this.cashAmount = cashAmount;
10 }
11
12 @Override
13 public boolean payAmount()
14 {
15 if(cashAmount>=getDueAmount())
16 return true;
17 else
18 return false;
19 }
20
21
22 }
Credit.java
1 public class Credit extends Payment {
2 int creditCardNo;
3 String cardType;
4 int creditCardAmount;
5 public int getCreditCardNo() {
6 return creditCardNo;
7 }
8 public void setCreditCardNo(int creditCardNo) {
9 this.creditCardNo = creditCardNo;
10 }
11 public String getCardType() {
12 return cardType;
13 }
14 public void setCardType(String cardType) {
15 this.cardType = cardType;
16 }
17 public int getCreditCardAmount() {
18 return creditCardAmount;
19 }
20 public void setCreditCardAmount(int creditCardAmount) {
21 this.creditCardAmount = creditCardAmount;
22 }
23
24
25 @Override
26 public boolean payAmount()
27 {
28 int netAmount = 0;
29 if(cardType.equals("silver"))
30 {
31 netAmount = (int) (getDueAmount()*1.02);
32 creditCardAmount = 10000;
33 }
34 else if(cardType.equals("gold"))
35 {
36 netAmount = (int) (getDueAmount()*1.05);
37 creditCardAmount = 50000;
38 }
39 else if(cardType.equals("platinum"))
40 {
41 netAmount = (int) (int) (getDueAmount()*1.1);
42 creditCardAmount = 100000;
43 }
44
45 if(creditCardAmount>=netAmount)
46 {
47 creditCardAmount = creditCardAmount - netAmount;
48 return true;
49 }
50 else
51 return false;
52 }
53
54
55 }
Bill.java
1 public class Bill {
2 public String processPayment(Payment obj)
3{
4 String res="";
5 if(obj instanceof Cheque)
6 {
7 if(obj.payAmount())
8 res = "Payment done successfully via cheque";
9 else
10 res = "Payment not done and your due amount is
"+obj.getDueAmount();
11 }
12 else if(obj instanceof Cash)
13 {
14 if(obj.payAmount())
15 res = "Payment done successfully via cash";
16 else
17 res = "Payment not done and your due amount is
"+obj.getDueAmount();
18 }
19 else if(obj instanceof Credit)
20 {
21 Credit c = (Credit) obj;
22 if(obj.payAmount())
23 res = "Payment done successfully via credit card. Remaining
amount in your "+c.getCardType()+" card is "+c.getCreditCardAmount();
24 else
25 res = "Payment not done and your due amount is
"+obj.getDueAmount();
26 }
27 return res;
28 }
29 }
Grade
Reviewed on Wednesday, 1 December 2021, 10:08 PM by Automatic grade
Grade 100 / 100
Assessment report
TEST CASE PASSED
[+]Grading and Feedback
3.Power Progress
Grade settings: Maximum grade: 100
Run: Yes Evaluate: Yes
Automatic grade: Yes
Andrews taught exponential multiplication to his daughter and gave her two inputs.
Assume, the first input as M and the second input as N. He asked her to find the sequential
power of M until N times. For Instance, consider M as 3 and N as 5. Therefore, 5 times the power
is incremented gradually from 1 to 5 such that, 3^1=3, 3^2=9,3^3=27,3^4=81,3^5=243. The input
numbers should be greater than zero Else print “<Input> is an invalid”. The first Input must be
less than the second Input, Else print "<first input> is not less than <second input>".
Write a Java program to implement this process programmatically and display the output in
sequential order. ( 3^3 means 3*3*3 ).
Note:
In the Sample Input / Output provided, the highlighted text in bold corresponds to the input given
by the user and the rest of the text represents the output.
Sample Input 1:
3
5
Sample Output 1:
3 9 27 81 243
Explanation: Assume the first input as 3 and second input as 5. The output is to be displayed
are based on the sequential power incrementation. i.e., 3(3) 9(3*3) 27(3*3*3) 81(3*3*3*3)
243(3*3*3*3*3)
Sample Input 2:
-3
Sample Output 2:
-3 is an invalid
Sample Input 3:
3
0
Sample Output 3:
0 is an invalid
Sample Input 4:
4
2
Sample Output 4:
4 is not less than 2
Automatic evaluation[+]
Main.java
1 import java.util.*;
2 public class Main
3{
4 public static void main(String[] args)
5 {
6 Scanner sc=new Scanner(System.in);
7 //Fill the code
8 int m=sc.nextInt();
9 if(m<=0){
10 System.out.println(""+m+" is an invalid");
11 return;
12 }
13 int n=sc.nextInt();
14 if(n<=0){
15 System.out.println(""+n+" is an invalid");
16 return;
17 }
18 if(m>=n){
19 System.out.println(""+m+" is not less than "+n);
20 return;
21 }
22 for(int i=1;i<=n;i++){
23 System.out.print((int)Math.pow(m,i)+"");
24 }
25 }
26 }
Grade
Reviewed on Monday, 7 February 2022, 4:46 PM by Automatic grade
Grade 100 / 100
Assessment report
TEST CASE PASSED
[+]Grading and Feedback
4. ZeeZee bank
Grade settings: Maximum grade: 100
Run: Yes Evaluate: Yes
Automatic grade: Yes Maximum execution time: 16 s
ZeeZee is a leading private sector bank. In the last Annual meeting, they decided to give their
customer a 24/7 banking facility. As an initiative, the bank outlined to develop a stand-alone
device that would offer deposit and withdrawal of money to the customers anytime.
You being their software consultant have been approached to develop software to implement
the functionality of deposit and withdrawal anytime.
As per this requirement, the customer should be able to deposit money into his account at any
time and the deposited amount should reflect in his account balance.
Deposit amount to Account public void deposit(double This method takes the
an account depositAmt) amount to be deposited as
an argument
As per this requirement, the customer should be able to withdraw money from his account
anytime he wants. The amount to be withdrawn should be less than or equal to the balance in
the account. After the withdrawal, the account should reflect the balance amount
In the Main class, Get the details as shown in the sample input.
Create an object for the Account class and invoke the deposit method to deposit the amount
and withdraw method to withdraw the amount from the account.
Note:
If the balance amount is insufficient then display the message as shown in the Sample Input /
Output.
In the Sample Input / Output provided, the highlighted text in bold corresponds to the input
given by the user and the rest of the text represents the output.
Ensure to provide the names for classes, attributes, and methods as specified in the question.
Sample Input/Output 1:
1234567890
15000
1500
500
Sample Input/Output 2:
1234567890
15000
Enter the amount to be deposited:
1500
18500
Insufficient balance
Automatic evaluation[+]
Main.java
1 import java.text.DecimalFormat;
2 import java.util.Scanner;
3 import java.util.Scanner;
4
5
6 public class Main{
7 static Account ac=new Account(0, 0);
8 public static void main (String[] args) {
9 Scanner sc=new Scanner(System.in);
10 System.out.println("Enter the account number:");
11 ac.setAccountNumber(sc.nextLong());
12 System.out.println("Enter the available amount in the account:");
13 ac.setBalanceAmount(sc.nextDouble());
14 System.out.println("Enter the amount to be deposited:");
15 ac.deposit(sc.nextDouble());
16 System.out.printf("Available balance is:%.2f",ac.getBalanceAmount());
17 System.out.println();
18 System.out.println("Enter the amount to be withdrawn:");
19 ac.withdraw(sc.nextDouble());
20 System.out.printf("Available balance is:%.2f",ac.getBalanceAmount());
21 //Fill the code
22 }
23 }
24
25
26
Account.java
1
2 public class Account {
3 long accountNumber;
4 double balanceAmount;
5
6
7 public Account(long accno, double bal){
8 super();
9 this.accountNumber=accno;
10 this.balanceAmount=bal;
11 }
12 public long getAccountNumber(){
13 return accountNumber;
14 }
15 public void setAccountNumber(long accno){
16 this.accountNumber=accno;
17 }
18 public double getBalanceAmount(){
19 return balanceAmount;
20 }
21 public void setBalanceAmount(double bal) {
22 this.balanceAmount=bal;
23 }
24 public void deposit(double depositAmt){
25 float total=(float)(balanceAmount+depositAmt);
26 balanceAmount=total;
27 }
28 public boolean withdraw(double withdrawAmt){
29 float total;
30 if(withdrawAmt>balanceAmount){
31 System.out.println("Insufficient balance");
32
33 return false;
34 }else{
35 total=(float)(balanceAmount-withdrawAmt);
36 setBalanceAmount(total);
37 return true;
38 }
39 }
40 }
Grade
Reviewed on Monday, 7 February 2022, 4:47 PM by Automatic grade
Grade 100 / 100
Assessment report
[+]Grading and Feedback
5. Reverse a word
Grade settings: Maximum grade: 100
Run: Yes Evaluate: Yes
Automatic grade: Yes
Reverse a word
Rita and Brigitha want to play a game. That game is to check the first letter of each word in a
given sentence (Case Insensitive). If it is equal, then reverse the last word and concatenate the
first word. Else reverse the first word and concatenate the last word. Create a Java application
and help them to play the game
Note:
● Sentence must contain at least 3 words else print "Invalid Sentence" and terminate the
program
● Each word must contain alphabet only else print "Invalid Word" and terminate the
program
● Check the first letter of each word in a given sentence (Case Insensitive). If it is equal,
then reverse the last word and concatenate the first word and print. Else reverse the first
word and concatenate the last word and print.
● Print the output without any space.
Sample Input 1:
Sample Output 1:
sllehsaesSea
Sample Input 2:
Sample Output 2:
maSdays
Sample Input 3:
Welcome home
Sample Output 3:
Invalid Sentence
Sample Input 4:
Friendly fire fighting fr@gs.
Sample Output 4:
Invalid Word
Automatic evaluation[+]
Main.java
1 import java.util.Scanner;
2 import java.lang.String.*;
3 import java.util.*;
4 public class Main{
5 public static void main(String[] args){
6 String[] words;
7 Scanner read =new Scanner(System.in);
8 String sentence=read.nextLine();
9 words=sentence.split(" ");
10 if(words.length<3)
11 System.out.println("Invalid Sentence");
12 else{
13 String a=words[0].substring(0,1);
14 String b=words[1].substring(0,1);
15 String c=words[2].substring(0,1);
16 if(a.equalsIgnoreCase(b)&&b.equalsIgnoreCase(c))
17 {
18 StringBuilder k= new StringBuilder();
19 k.append(words[words.length-1]);
20 k=k.reverse();
21 k.append(words[0]);
22 System.out.println(k);
23 }
24 else{
25 StringBuilder k = new StringBuilder();
26 k.append(words[0]);
27 k=k.reverse();
28 k.append(words[words.length-1]);
29 System.out.println(k);
30 }
31 }
32 }
33 }
Grade
Reviewed on Monday, 7 February 2022, 5:12 PM by Automatic grade
Grade 90 / 100
Assessment report
Fail 1 -- test5_CheckForTheSentenceContainsOtherThanAlphabets::
$Expected output:"[Invalid Word]" Actual output:"[tahWme]"$
[+]Grading and Feedback
6. Dominion cinemas
Grade settings: Maximum grade: 100
Run: Yes Evaluate: Yes
Automatic grade: Yes
Dominion cinema is a famous theatre in the city. It has different types of seat tiers – Platinum,
Gold and Silver. So far the management was manually calculating the ticket cost for all their
customers which proved very hectic and time consuming. Going forward they want to calculate
ticket cost using their main computer. Assist them in calculating and retrieving the amount to be
paid by the Customer.
The application needs to calculate the ticket cost to be paid by the Customer according to the
seat tier.
Note:
Note:
Use a public class UserInterface with the main method to test the application. In the main
method call the validateTicketId() method, if the method returns true display the amount else
display "Provide valid Ticket Id".
Note:
● In the Sample Input / Output provided, the highlighted text in bold corresponds to the
input given by the user and the rest of the text represents the output.
● Ensure to follow the object oriented specifications provided in the question.
● Ensure to provide the names for classes, attributes and methods as specified in the
question.
● Adhere to the code template, if provided.
Sample Input 1:
Enter Ticket Id
SILVER490
Venkat
9012894578
Enter Email Id
Avengers
8
Do you want AC or not
Sample Input 2:
Enter Ticket Id
ACN450
Kamal
9078561093
Enter Email Id
Tangled
Automatic evaluation[+]
BookAMovieTicket.java
1
2 public class BookAMovieTicket {
3
4 protected String ticketId;
5 protected String customerName;
6 protected long mobileNumber;
7 protected String emailId;
8 protected String movieName;
9
10 public String getTicketId() {
11 return ticketId;
12 }
13 public void setTicketId(String ticketId) {
14 this.ticketId = ticketId;
15 }
16 public String getCustomerName() {
17 return customerName;
18 }
19 public void setCustomerName(String customerName) {
20 this.customerName = customerName;
21 }
22 public long getMobileNumber() {
23 return mobileNumber;
24 }
25 public void setMobileNumber(long mobileNumber) {
26 this.mobileNumber = mobileNumber;
27 }
28 public String getEmailId() {
29 return emailId;
30 }
31 public void setEmailId(String emailId) {
32 this.emailId = emailId;
33 }
34 public String getMovieName() {
35 return movieName;
36 }
37 public void setMovieName(String movieName) {
38 this.movieName = movieName;
39 }
40
41 public BookAMovieTicket(String ticketId, String customerName, long mobileNumber, String emailId,
String movieName) {
42 this.ticketId = ticketId;
43 this.customerName = customerName;
44 this.mobileNumber = mobileNumber;
45 this.emailId = emailId;
46 this.movieName = movieName;
47
48 }
49
50
51
52 }
53
GoldTicket.java
1
2 public class GoldTicket extends BookAMovieTicket{
3 public GoldTicket(String ticketId,String customerName, long mobileNumber,
4 String emailId, String movieName){
5 super(ticketId, customerName, mobileNumber, emailId, movieName);
6 }
7
8 public boolean validateTicketId(){
9 int count=0;
10 if(ticketId.contains("GOLD"));
11 count++;
12 char[] cha=ticketId.toCharArray();
13 for(int i=4;i<7;i++){
14 if(cha[i]>='1'&& cha[i]<='9')
15 count++;
16 }
17 if(count==4)
18 return true;
19 else
20 return false;
21 }
22
23
24 // Include Constructor
25
26 public double calculateTicketCost(int numberOfTickets, String ACFacility){
27 double amount;
28 if(ACFacility.equals("yes")){
29 amount=500*numberOfTickets;
30 }
31 else{
32 amount=350*numberOfTickets;
33 }
34
35 return amount;
36 }
37
38 }
PlatinumTicket.java
SilverTicket.java
1
2 public class SilverTicket extends BookAMovieTicket{
3 public SilverTicket(String ticketId, String customerName, long mobileNumber,
4 String emailId, String movieName){
5 super(ticketId, customerName, mobileNumber, emailId, movieName);
6 }
7
8 public boolean validateTicketId(){
9 int count=0;
10 if(ticketId.contains("SILVER"));
11 count++;
12 char[] cha=ticketId.toCharArray();
13 for(int i=6;i<9;i++){
14 if(cha[i]>='1'&& cha[i]<='9')
15 count++;
16 }
17 if(count==4)
18 return true;
19 else
20 return false;
21 }
22
23 // Include Constructor
24
25 public double calculateTicketCost(int numberOfTickets, String ACFacility){
26 double amount;
27 if(ACFacility.equals("yes")){
28 amount=250*numberOfTickets;
29 }
30 else{
31 amount=100*numberOfTickets;
32 }
33
34 return amount;
35 }
36
37 }
38
UserInterface.java
1 import java.util.*;
2
3 public class UserInterface {
4
5 public static void main(String[] args){
6 Scanner sc=new Scanner(System.in);
7 System.out.println("Enter Ticket Id");
8 String tid=sc.next();
9 System.out.println("Enter Customer name");
10 String cnm=sc.next();
11 System.out.println("Enter Mobile number");
12 long mno=sc.nextLong();
13 System.out.println("Enter Email id");
14 String email=sc.next();
15 System.out.println("Enter Movie name");
16 String mnm=sc.next();
17 System.out.println("Enter number of tickets");
18 int tno=sc.nextInt();
19 System.out.println("Do you want AC or not");
20 String choice =sc.next();
21 if(tid.contains("PLATINUM")){
22 PlatinumTicket PT= new PlatinumTicket(tid,cnm,mno,email,mnm);
23 boolean b1=PT.validateTicketId();
24 if(b1==true){
25 double cost=PT.calculateTicketCost(tno, choice);
26 System.out.println("Ticket cost is "+String.format("%.2f",cost));
27 }
28 else if(b1==false){
29 System.out.println("Provide valid Ticket Id");
30 System.exit(0);
31 }
32 }
33 else if(tid.contains("GOLD")){
34 GoldTicket GT= new GoldTicket(tid,cnm,mno,email,mnm);
35 boolean b2=GT.validateTicketId();
36 if(b2==true){
37 double cost=GT.calculateTicketCost(tno,choice);
38 System.out.println("Ticket cost is "+String.format("%.2f",cost));
39 }
40 else if (b2==false){
41 System.out.println("Provide valid Ticket Id");
42 System.exit(0);
43 }
44 }
45 else if(tid.contains("SILVER")){
46 SilverTicket ST= new SilverTicket(tid,cnm,mno,email,mnm);
47 boolean b3=ST.validateTicketId();
48 if(b3==true){
49 double cost=ST.calculateTicketCost(tno,choice);
50 System.out.println("Ticket cost is "+String.format("%.2f",cost));
51 }
52 else if (b3==false){
53 System.out.println("Provide valid Ticket Id");
54 System.exit(0);
55 }
56 }
57 }
58 }
59
60
Grade
Reviewed on Monday, 7 February 2022, 4:18 PM by Automatic grade
Grade 100 / 100
Assessment report
[+]Grading and Feedback
============================================================================
Group-2
1. Flight record retrieval
Grade settings: Maximum grade: 100
Based on: JAVA CC JDBC - MetaData V1 - ORACLE (w/o Proj Struc)
Run: Yes Evaluate: Yes
Automatic grade: Yes Maximum execution time: 32 s
You being their software consultant have been approached by them to develop an application
which can be used for managing their business. You need to implement a java program to view
all the flight based on source and destination.
int
noOfSeats
double
flightFare
Note: The class and methods should be declared as public and all the attributes should be
declared as private.
Requirement 1: Retrieve all the flights with the given source and destination
The customer should have the facility to view flights which are from a particular source to
destination. Hence the system should fetch all the flight details for the given source and
destination from the database. Those flight details should be added to a ArrayList and return the
same.
The flight table is already created at the backend. The structure of flight table is:
To connect to the database you are provided with database.properties file and DB.java file. (Do
not change any values in database.properties file)
Create a class called Main with the main method and get the inputs
like source and destination from the user.
Display the details of flight such as flightId, noofseats and flightfare for all the flights returned
as ArrayList<Flight> from the
method viewFlightBySourceDestination in FlightManagementSystem class.
If no flight is available in the list, the output should be “No flights available for the given source
and destination”.
Note:
In the Sample Input / Output provided, the highlighted text in bold corresponds to the input given
by the user and the remaining text represents the output.
Malaysia
Singapore
18221 50 5000.0
Malaysia
Dubai
Automatic evaluation[+]
Flight.java
1
2 public class Flight {
3
4 private int flightId;
5 private String source;
6 private String destination;
7 private int noOfSeats;
8 private double flightFare;
9 public int getFlightId() {
10 return flightId;
11 }
12 public void setFlightId(int flightId) {
13 this.flightId = flightId;
14 }
15 public String getSource() {
16 return source;
17 }
18 public void setSource(String source) {
19 this.source = source;
20 }
21 public String getDestination() {
22 return destination;
23 }
24 public void setDestination(String destination) {
25 this.destination = destination;
26 }
27 public int getNoOfSeats() {
28 return noOfSeats;
29 }
30 public void setNoOfSeats(int noOfSeats) {
31 this.noOfSeats = noOfSeats;
32 }
33 public double getFlightFare() {
34 return flightFare;
35 }
36 public void setFlightFare(double flightFare) {
37 this.flightFare = flightFare;
38 }
39 public Flight(int flightId, String source, String destination,
40 int noOfSeats, double flightFare) {
41 super();
42 this.flightId = flightId;
43 this.source = source;
44 this.destination = destination;
45 this.noOfSeats = noOfSeats;
46 this.flightFare = flightFare;
47 }
48
49
50
51 }
52
FlightManagementSystem.java
1 import java.util.ArrayList;
2 import java.sql.*;
3
4
5 public class FlightManagementSystem {
6
7 public ArrayList<Flight> viewFlightBySourceDestination(String source, String destination){
8 ArrayList<Flight> flightList = new ArrayList<Flight>();
9 try{
10 Connection con = DB.getConnection();
11
12 String query="SELECT * FROM flight WHERE source= '" + source + "' AND destination= '" +
destination + "' ";
13
14 Statement st=con.createStatement();
15
16 ResultSet rst= st.executeQuery(query);
17
18 while(rst.next()){
19 int flightId= rst.getInt(1);
20 String src=rst.getString(2);
21 String dst=rst.getString(3);
22 int noofseats=rst.getInt(4);
23 double flightfare=rst.getDouble(5);
24
25 flightList.add(new Flight(flightId, src, dst, noofseats, flightfare));
26 }
27 }catch(ClassNotFoundException | SQLException e){
28 e.printStackTrace();
29 }
30 return flightList;
31 }
32
33 }
Main.java
1 import java.util.Scanner;
2 import java.util.ArrayList;
3
4 public class Main{
5 public static void main(String[] args){
6 Scanner sc=new Scanner(System.in);
7 System.out.println("Enter the source");
8 String source=sc.next();
9 System.out.println("Enter the destination");
10 String destination=sc.next();
11
12 FlightManagementSystem fms= new FlightManagementSystem();
13 ArrayList<Flight> flightList=fms.viewFlightBySourceDestination(source,destination);
14 if(flightList.isEmpty()){
15 System.out.println("No flights available for the given source and destination");
16 return;
17 }
18 System.out.println("Flightid Noofseats Flightfare");
19 for(Flight flight : flightList){
20 System.out.println(flight.getFlightId()+" "+flight.getNoOfSeats()+" "+flight.getFlightFare());
21 }
22
23 }
24 }
DB.java
1 import java.io.FileInputStream;
2 import java.io.IOException;
3 import java.sql.Connection;
4 import java.sql.DriverManager;
5 import java.sql.SQLException;
6 import java.util.Properties;
7
8 public class DB {
9
10 private static Connection con = null;
11 private static Properties props = new Properties();
12
13
14 //ENSURE YOU DON'T CHANGE THE BELOW CODE WHEN YOU SUBMIT
15 public static Connection getConnection() throws ClassNotFoundException, SQLException {
16 try{
17
18 FileInputStream fis = null;
19 fis = new FileInputStream("database.properties");
20 props.load(fis);
21
22 // load the Driver Class
23 Class.forName(props.getProperty("DB_DRIVER_CLASS"));
24
25 // create the connection now
26 con =
DriverManager.getConnection(props.getProperty("DB_URL"),props.getProperty("DB_USERNAME"),props.getPr
operty("DB_PASSWORD"));
27 }
28 catch(IOException e){
29 e.printStackTrace();
30 }
31 return con;
32 }
33 }
34
database.properties
1 #IF NEEDED, YOU CAN MODIFY THIS PROPERTY FILE
2 #ENSURE YOU ARE NOT CHANGING THE NAME OF THE PROPERTY
3 #YOU CAN CHANGE THE VALUE OF THE PROPERTY
4 #LOAD THE DETAILS OF DRIVER CLASS, URL, USERNAME AND PASSWORD IN DB.java using this
properties file only.
5 #Do not hard code the values in DB.java.
6
7 DB_DRIVER_CLASS=oracle.jdbc.driver.OracleDriver
8 DB_URL=jdbc:oracle:thin:@127.0.0.1:1521:XE
9 DB_USERNAME=${sys:db_username}
10 DB_PASSWORD=${sys:db_password}
11
Grade
Reviewed on Monday, 7 February 2022, 6:33 PM by Automatic grade
Grade 100 / 100
Assessment report
Assessment Completed Successfully
[+]Grading and Feedback
=============================================
2. Get Text and Display Welcome Message
Grade settings: Maximum grade: 100
Run: Yes Evaluate: Yes
Automatic grade: Yes Maximum execution time: 16 s
Amir owns “Bouncing Babies” an exclusive online store for baby toys.
He desires to display a welcome message whenever a customer visits his online store and
makes a purchase.
Help him do this by incorporating the customer name using the Lambda expression.
In the Main class write the main method and perform the given steps :
Note :
In the Sample Input / Output provided, the highlighted text in bold corresponds to the input given
by the user and the rest of the text represents the output.
Ensure to provide the name for classes, interfaces and methods as specified in the question.
Watson
Sample Output 1 :
Welcome Watson
Automatic evaluation[+]
DisplayText.java
1 import java.util.*;
2 @FunctionalInterface
3 public interface DisplayText
4{
5 public void displayText(String text);
6 public default String getInput()
7 {
8 Scanner read = new Scanner(System.in);
9 String str = read.next();
10 return str;
11 //return null;
12 }
13 }
Main.java
1 public class Main
2{
3 public static DisplayText welcomeMessage()
4 {
5
6 DisplayText dis = (str)->{
7
8 System.out.println("Welcome "+str);
9 };
10 return dis;
11 }
12 public static void main(String args[])
13 {
14 DisplayText dis=welcomeMessage();
15 String text = dis.getInput();
16 dis.displayText(text);
17
18 }
19 }
Grade
Reviewed on Wednesday, 1 December 2021, 10:14 PM by Automatic grade
Grade 100 / 100
Assessment report
[+]Grading and Feedback
=============================================
3. Generate Password
Grade settings: Maximum grade: 100
Run: Yes Evaluate: Yes
Automatic grade: Yes
Important Instructions:
· Do not change the Skeleton code or the package structure, method names, variable
names, return types, exception clauses, access specifiers etc.
· You can create any number of private methods inside the given class.
· You can test your code from main() method of the program
The system administrator of an organization wants to set password for all the computers for
security purpose. To generate a strong password, he wants to combine the username of each
user of the system with the reverse of their respective usernames. Help them by using Lambda
expressions that caters to their requirement.
Requirement 1: PasswordInfo
The Administrator wants to generate password for each system by making use
of the passwordGeneration method based on the username which is passed as a string.
In the Computer class write the main method and perform the given steps:
Note:
In the Sample Input / Output provided, the highlighted text in bold corresponds to the
input given by the user and the rest of the text represents the output.
Ensure to use the lambda expression.
Ensure to follow the object oriented specifications provided in the question.
Ensure to provide the name for classes, interfaces and methods as specified in the
question.
Adhere to the code template, if provided.
Sample Input 1:
Enter system no
Tek/1234
Enter username
Manoj Kumar
Sample Output 1:
Password Info
=========================================================================
· Do not change the Skeleton code or the package structure, method names, variable
names, return types, exception clauses, access specifiers etc.
· You can create any number of private methods inside the given class.
· You can test your code from the main() method of the program.
Watican Museum is one of the famous museums, they have collections of houses paintings, and
sculptures from artists. The Museum management stores their visitor's details in a text file. Now,
they need an application to analyze and manipulate the visitor details based on the visitor visit
date and the visitor address.
You are provided with a text file – VisitorDetails.txt, which contains all the visitor details
like the visitor Id, visitor name, mobile number, date of visiting and address. Your
application should satisfy the following requirements.
2. View visitor details which are above a particular mentioned visitor address.
You are provided with a code template which includes the following:
Note:
The Visitor class and the Main class will be provided with all the necessary codes. Please
do not edit or delete any line of the code in these two classes.
Fill your code in the InvalidVisitorIdException class to create a constructor as described
in the functional requirements below.
Fill your code in the respective methods of VisitorUtility class to fulfil all the functional
requirements.
In the VisitorDetails.txt file, each visitor detail has information separated by a comma,
and it is given as one customer detail per line.
Functional Requirements:
Fill your code in the respective class and method declarations based on the required
functionalities as given below.
Note:
Validation Rules:
Example.
WM_A23
InvalidVisitorIdException Create a constructor with a This class Should inherit the Exception
single String argument and class. The constructor should pass the
pass it to the parent class String message which is thrown to it by
constructor. calling the parent class constructor.
Requirement 2: View visitor details which are above a particular mentioned address
1. All inputs/ outputs for processing the functional requirements should be case sensitive.
2. Adhere to the Sample Inputs/ Outputs
3. In the Sample Inputs/ Outputs provided, the highlighted text in bold corresponds to the
input given by the user and the rest of the text represents the output.
4. All the Date values used in this application must be in “dd-MM-yyyy” format.
5. Adhere to the code template.
6. Fill all your required codes in the respective blocks. Do not edit or delete the codes
provided in the code template.
7. The Sample Inputs/ Outputs given below are generated based on the Sample data given
in the VisitorDetails.txt file.
8. Please do not hard code the output.
1. ViewVisitorDetailsByDateOfVisiting
2. ViewVisitorDetailsByAddress
07-04-2012
1. viewVisitorDetailsByDateOfVisiting
2. viewVisitorDetailsByAddress
Eastbourne
Requirements:
3. Retrieve the patient details which are from a particular area (address).
String
patientName
String
contactNumber
String dateOfVisit
String
patientAddress
You are provided with a text file –PatientRegister.txt, which contains all the patient details like the
patient Id, patient name, contact number, date of visit, and patient address. You can add any
number of records in the text file to test your code.
Note:
· In the Sample Input / Output provided, the highlighted text in bold corresponds to the input
given by the user, and the rest of the text represents the output.
· Ensure to provide the names for classes, attributes, and methods as specified in the
question description.
Sample Input/Output 1:
1. By Date of Visit
2. By Address
Enter your choice:
02-03-2003
02-12-2005
Sample Input/Output 2:
1. By Date of Visit
2. By Address
Carolina
1. By Date of Visit
2. By Address
03-02-2020
02-02-2021
Sample Input/Output 4:
1. By Date of Visit
2. By Address
Enter your choice:
Invalid Option
Automatic evaluation[+]
HospitalManagement/PatientRegister.txt
1 WM_J82,Jacey,8734909012,07-08-2001,Colorado
2 WM_L01,Bella,9435678631,21-09-1992,Connecticut
3 WM_52E,Berey,8754321256,20-03-1999,Indiana
4 WM_B83,Cappi,6709543276,13-02-2006,Pennsylvania
5 WM_C23,Anya,7656548798,23-11-2002,Carolina
6 WM_X26,Beatrice,6789567687,18-07-2004,Texas
7 WM_H72,Elise,9809908765,02-12-2005,Washington
8 WM_P10,Fanny,7835627189,02-05-2001,Virginia
9 WM_Q12,Felicity,6792637810,21-05-1997,Colorado
10 WM_K7K,Abigail,8934562718,02-05-2016,Indiana
11 WM_U82,Alice,8352617181,11-05-2012,Indiana
12 WN_P23,Amber,9876567898,12-09-1998,Pennsylvania
13 LM_V20,Gabriella,8302927382,02-05-2006,Connecticut
14 WM_Z05,Hadley,7823919273,02-06-2007,Connecticut
15 WM_T83,Harper,7391027349,08-07-1999,Carolina
16 WM_M03,Iris,9102638491,27-05-2001,Texas
17 WM_N32,Finley,8729196472,12-08-2003,Pennsylvania
18 WM_WQ0,Fiona,7201982219,09-09-2014,Washington
19 WM_Q91,Carny,8976509871,30-12-2003,Virginia
20 WM_P21,Eleanor,8954321378,24-11-2007,Carolina
HospitalManagement/src/InvalidPatientIdException.java
1
2 //public class InvalidPatientIdException{
3 //FILL THE CODE HERE
4 public class InvalidPatientIdException extends Exception{
5 public InvalidPatientIdException(String message){
6 super(message);
7 }
8 }
9
10
11
12
HospitalManagement/src/Main.java
1 public class Main {
2
3 public static void main(String[] args){
4
5 // CODE SKELETON - VALIDATION STARTS
6 // DO NOT CHANGE THIS CODE
7
8 new SkeletonValidator();
9 // CODE SKELETON - VALIDATION ENDS
10
11 // FILL THE CODE HERE
12
13 }
14
15 }
16
17
HospitalManagement/src/Patient.java
1 //DO NOT ADD/EDIT THE CODE
2 public class Patient {
3
4 private String patientId;
5 private String patientName;
6 private String contactNumber;
7 private String dateOfVisit;
8 private String patientAddress;
9
10 //Setters and Getters
11
12 public String getPatientId() {
13 return patientId;
14 }
15 public void setPatientId(String patientId) {
16 this.patientId = patientId;
17 }
18 public String getPatientName() {
19 return patientName;
20 }
21 public void setPatientName(String patientName) {
22 this.patientName = patientName;
23 }
24 public String getContactNumber() {
25 return contactNumber;
26 }
27 public void setContactNumber(String contactNumber) {
28 this.contactNumber = contactNumber;
29 }
30 public String getDateOfVisit() {
31 return dateOfVisit;
32 }
33 public void setDateOfVisit(String dateOfVisit) {
34 this.dateOfVisit = dateOfVisit;
35 }
36 public String getPatientAddress() {
37 return patientAddress;
38 }
39 public void setPatientAddress(String patientAddress) {
40 this.patientAddress = patientAddress;
41 }
42
43
44
45
46 }
47
HospitalManagement/src/PatientUtility.java
1 import java.util.List;
2 import java.util.stream.Stream;
3 import java.util.ArrayList;
4 import java.io.File;
5 import java.io.FileNotFoundException;
6 import java.util.Scanner;
7 import java.util.regex.*;
8 import java.util.stream.Collectors;
9 import java.text.ParseException;
10 import java.text.SimpleDateFormat;
11 import java.util.Date;
12
13
14 public class PatientUtility {
15
16 public List <Patient> fetchPatient(String filePath) {
17
18
19 //FILL THE CODE HERE
20 List <Patient> patients =new ArrayList<>();
21 try{
22 File register =new File(filePath);
23 Scanner reader=new Scanner(register);
24 while(reader.hasNextLine()){
25 Patient p = new Patient();
26 String[] infos=reader.nextLine().split(",");
27 try{
28 if(isValidPatientId(infos[0])){
29 p.setPatientId(infos[0]);
30 p.setPatientName(infos[1]);
31 p.setContactNumber(infos[2]);
32 p.setDateOfVisit(infos[3]);
33 p.setPatientAddress(infos[4]);
34 patients.add(p);
35 }
36 }
37 catch(InvalidPatientIdException e1){
38 System.out.println(e1.getMessage());
39 }
40 }
41 reader.close();
42 }
43 catch(FileNotFoundException e){}
44 return patients;
45
46 //return null;
47 }
48
49
50 public boolean isValidPatientId (String patientId)throws InvalidPatientIdException
51 {
52
53 //FILL THE CODE HERE
54 Pattern p =Pattern.compile("WM_[A-Z][0-9]{2}$");
55 Matcher m=p.matcher(patientId);
56 boolean ne =m.matches();
57 if(!ne){
58 throw new InvalidPatientIdException(patientId+"is an Invalid Patient Id.");
59
60 }
61 //return inValid;
62 return ne;
63 }
64
65
66 public List<Patient> retrievePatientRecords_ByDateOfVisit(Stream<Patient> patientStream, String
fromDate, String toDate)
67 {
68 //FILL THE CODE HERE
69 SimpleDateFormat simpleDateFormat=new SimpleDateFormat("dd-MM-yyyy");
70 return patientStream
71 .filter((p)->{
72 try{
73 Date start=simpleDateFormat.parse(fromDate);
74 Date end= simpleDateFormat.parse(toDate);
75 Date current =simpleDateFormat.parse(p.getDateOfVisit());
76 return start.compareTo(current)*current.compareTo(end)>=0;
77 }
78 catch(ParseException e){}
79 return false;
80 }).collect(Collectors.toList());
81 // return null;
82 }
83
84
85
86 public Stream<Patient> retrievePatientRecords_ByAddress(Stream<Patient> patientStream, String
address)
87 {
88
89 //FILL THE CODE HERE
90 return patientStream.filter(p->address.equals(p.getPatientAddress()));
91 //return null;
92
93
94
95 }
96
97 }
98
HospitalManagement/src/SkeletonValidator.java
1 import java.lang.reflect.Method;
2 import java.util.List;
3 import java.util.logging.Level;
4 import java.util.logging.Logger;
5 import java.util.stream.Stream;
6
7 /**
8 * @author TJ
9 *
10 * This class is used to verify if the Code Skeleton is intact and not modified by participants thereby ensuring
smooth auto evaluation
11 *
12 */
13 public class SkeletonValidator {
14
15 public SkeletonValidator() {
16
17
18 validateClassName("Patient");
19 validateClassName("PatientUtility");
20 validateClassName("InvalidPatientIdException");
21 validateMethodSignature(
22
"fetchPatient:java.util.List,isValidPatientId:boolean,retrievePatientRecords_ByDateOfVisit:java.util.List
,retrievePatientRecords_ByAddress:java.util.stream.Stream",
23 "PatientUtility");
24
25 }
26
27 private static final Logger LOG = Logger.getLogger("SkeletonValidator");
28
29 protected final boolean validateClassName(String className) {
30
31 boolean iscorrect = false;
32 try {
33 Class.forName(className);
34 iscorrect = true;
35 LOG.info("Class Name " + className + " is correct");
36
37 } catch (ClassNotFoundException e) {
38 LOG.log(Level.SEVERE, "You have changed either the " + "class
name/package. Use the correct package "
39 + "and class name as provided in the skeleton");
40
41 } catch (Exception e) {
42 LOG.log(Level.SEVERE,
43 "There is an error in validating the " + "Class Name.
Please manually verify that the "
44 + "Class name is same as
skeleton before uploading");
45 }
46 return iscorrect;
47
48 }
49
50 protected final void validateMethodSignature(String methodWithExcptn, String className) {
51 Class cls = null;
52 try {
53
54 String[] actualmethods = methodWithExcptn.split(",");
55 boolean errorFlag = false;
56 String[] methodSignature;
57 String methodName = null;
58 String returnType = null;
59
60 for (String singleMethod : actualmethods) {
61 boolean foundMethod = false;
62 methodSignature = singleMethod.split(":");
63
64 methodName = methodSignature[0];
65 returnType = methodSignature[1];
66 cls = Class.forName(className);
67 Method[] methods = cls.getMethods();
68 for (Method findMethod : methods) {
69 if (methodName.equals(findMethod.getName())) {
70 foundMethod = true;
71 if
(!(findMethod.getReturnType().getName().equals(returnType))) {
72 errorFlag = true;
73 LOG.log(Level.SEVERE, " You
have changed the " + "return type in '" + methodName
74 + "'
method. Please stick to the " + "skeleton provided");
75
76 } else {
77 LOG.info("Method signature of "
+ methodName + " is valid");
78 }
79
80 }
81 }
82 if (!foundMethod) {
83 errorFlag = true;
84 LOG.log(Level.SEVERE, " Unable to find the given
public method " + methodName
85 + ". Do not change the " + "given
public method name. " + "Verify it with the skeleton");
86 }
87
88 }
89 if (!errorFlag) {
90 LOG.info("Method signature is valid");
91 }
92
93 } catch (Exception e) {
94 LOG.log(Level.SEVERE,
95 " There is an error in validating the " + "method
structure. Please manually verify that the "
96 + "Method signature is same as
the skeleton before uploading");
97 }
98 }
99
100 }
Grade
Reviewed on Monday, 7 February 2022, 6:04 PM by Automatic grade
Grade 100 / 100
Assessment report
Assessment Completed Successfully
[+]Grading and Feedback
=========================================================================
6. Technology Fest
Grade settings: Maximum grade: 100
Run: Yes Evaluate: Yes
Automatic grade: Yes
String collegeName
String eventName
double registrationFee
Requirements:
· To calculate the registration fee of the participant based on the event name.
int counter
EventManagement public void Calculate the registration
calculateRegistrationFee(List fee of the participant
<Participant> list) based on the event name.
If the event name doesn’t
exist, throw an
InvalidEventException
with an error message
“Event Name is invalid”.
EventManagement public void run() Calculate the number of
participants registered for
a particular event.
Increment the counter
attribute based on the
search.
Note: The class and methods should be declared as public and all the attributes should be
declared as private.
Create a class called Main with the main method and perform the tasks are given below:
· Get the event type to search to find the number of the participants registered for that
particular event.
· In the Sample Input / Output provided, the highlighted text in bold corresponds to the input
given by the user and the remaining text represent the output.
· Ensure to provide the names for classes, attributes, and methods as specified in the
question description.
Sample Input/Output 1:
rinu/4/EEE/mnm/robocar
fina/3/EEE/psg/papertalk
rachel/4/civil/kcg/quiz
robocar
Sample Input/Output 2:
rinu/4/EEE/mnm/robocar
fina/3/EEE/psg/papertalk
rachel/4/civil/kcg/quiz
games
No participant found
Sample Input/Output 3:
vishal/4/mech/vjc/flyingrobo
vivek/3/mech/hdl/games
Automatic evaluation[+]
TechnologyFest/src/EventManagement.java
1 import java.util.List;
2
3 public class EventManagement implements Runnable {
4 private List<Participant> TechList;
5 private String searchEvent;
6 private int counter=0;
7 public List<Participant>getTechList()
8 {
9 return TechList;
10
11 }
12 public void setTechList(List<Participant>techList)
13 {
14 TechList=techList;
15 }
16 public String getSearchEvent()
17 {
18 return searchEvent;
19 }
20 public void setSearchEvent(String searchEvent)
21 {
22 this.searchEvent=searchEvent;
23 }
24 public int getCounter()
25 {
26 return counter;
27 }
28 public void setCounter(int counter)
29 {
30 this.counter=counter;
31 }
32 //FILL THE CODE HERE
33
34 public void calculateRegistrationFee(List<Participant> list) throws InvalidEventException
35
36 {
37 for(Participant p:list)
38 {
39 if(p.getEventName().equalsIgnoreCase("robocar"))
40 {
41 p.setRegistrationFee(1000);
42 }
43 else if(p.getEventName().equalsIgnoreCase("papertalk")){
44 p.setRegistrationFee(500);
45
46 }
47
48 else if(p.getEventName().equalsIgnoreCase("quiz")){
49 p.setRegistrationFee(300);
50 }
51 else if(p.getEventName().equalsIgnoreCase("games")){
52 p.setRegistrationFee(100);
53 }
54 else{
55 throw new InvalidEventException("Event Name is Invalid");
56 }
57 }
58 //FILL THE CODE HERE
59 setTechList(list);
60 }
61
62 public void run()
63 {
64 String str="robocarpapertalkquizgames";
65 if(str.contains(this.getSearchEvent())){
66 for(Participant P:this.getTechList()){
67 if(this.getSearchEvent().equals(P.getEventName())){
68 counter++;
69 }
70 }
71 }
72 setCounter(counter);
73
74 //FILL THE CODE HERE
75
76 }
77 }
78
TechnologyFest/src/InvalidEventException.java
1 public class InvalidEventException extends Exception{
2 //FILL THE CODE HERE
3 public InvalidEventException(String str){
4 super(str);
5
6}
7
8}
9
TechnologyFest/src/Main.java
1
2 import java.util.Scanner;
3 import java.util.*;
4 public class Main {
5 public static void main(String [] args)
6 {
7 // CODE SKELETON - VALIDATION STARTS
8 // DO NOT CHANGE THIS CODE
9
10 new SkeletonValidator();
11
12 // CODE SKELETON - VALIDATION ENDS
13
14 Scanner sc=new Scanner(System.in);
15 System.out.println("Enter the number of entries");
16 int n=sc.nextInt();
17 System.out.println("Enter the Participant
Name/Yearofstudy/Department/CollegeName/EventName");
18 List<Participant> list=new ArrayList<Participant>();
19 String strlist[]=new String[n];
20 for(int i=0;i<n;i++)
21 {
22 strlist[i]=sc.next();
23 String a[]=strlist[i].split("/");
24 Participant pt=new Participant(a[0],a[1],a[2],a[3],a[4]);
25 list.add(pt);
26 }
27 EventManagement em=new EventManagement();
28 try {
29 em.calculateRegistrationFee(list);
30 }
31 catch(InvalidEventException e)
32 {
33 e.printStackTrace();
34
35 }
36 System.out.println("Print participant details");
37 for(Participant p:list)
38 {
39 System.out.println(p);
40 }
41 System.out.println("Enter the event to search");
42 String srch=sc.nextLine();
43 em.setSearchEvent(srch);
44 em.run();
45 int count=em.getCounter();
46 if(count<=0){
47 System.out.println("No participant found");
48
49 }
50 else{
51 System.out.println("Number of participants for"+srch+"event is "+count); }
52 }
53 }
54
55
56
57
TechnologyFest/src/Participant.java
1 public class Participant {
2 private String name;
3 private String yearofstudy;
4 private String department;
5 private String collegeName;
6 private String eventName;
7 private double registrationFee;
8
9 //5 argument Constructor
10 public Participant(String name, String yearofstudy, String department, String collegeName, String
eventName) {
11 super();
12 this.name = name;
13 this.yearofstudy = yearofstudy;
14 this.department = department;
15 this.collegeName = collegeName;
16 this.eventName = eventName;
17 }
18
19 public String getName() {
20 return name;
21 }
22 public void setName(String name) {
23 this.name = name;
24 }
25 public String getYearofstudy() {
26 return yearofstudy;
27 }
28 public void setYearofstudy(String yearofstudy) {
29 this.yearofstudy = yearofstudy;
30 }
31 public String getDepartment() {
32 return department;
33 }
34 public void setDepartment(String department) {
35 this.department = department;
36 }
37 public String getCollegeName() {
38 return collegeName;
39 }
40 public void setCollegeName(String collegeName) {
41 this.collegeName = collegeName;
42 }
43 public String getEventName() {
44 return eventName;
45 }
46 public void setEventName(String eventName) {
47 this.eventName = eventName;
48 }
49 public double getRegistrationFee() {
50 return registrationFee;
51 }
52 public void setRegistrationFee(double registrationFee) {
53 this.registrationFee = registrationFee;
54 }
55
56 @Override
57 public String toString() {
58 return "Participant [name=" + name + ", yearofstudy=" + yearofstudy + ", department=" +
department
59 + ", collegeName=" + collegeName + ", eventName=" +
eventName + ", registrationFee=" + registrationFee
60 + "]";
61 }
62
63
64
65
66 }
67
TechnologyFest/src/SkeletonValidator.java
1
2 import java.lang.reflect.Method;
3 import java.util.List;
4 import java.util.logging.Level;
5 import java.util.logging.Logger;
6 import java.util.stream.Stream;
7
8 /**
9 * @author TJ
10 *
11 * This class is used to verify if the Code Skeleton is intact and not modified by participants thereby ensuring
smooth auto evaluation
12 *
13 */
14 public class SkeletonValidator {
15
16 public SkeletonValidator() {
17
18 //classes
19 validateClassName("Main");
20 validateClassName("EventManagement");
21 validateClassName("Participant");
22 validateClassName("InvalidEventException");
23 //functional methods
24 validateMethodSignature(
25 "calculateRegistrationFee:void","EventManagement");
26 validateMethodSignature(
27 "run:void","EventManagement");
28
29 //setters and getters of HallHandler
30 validateMethodSignature(
31 "getTechList:List","EventManagement");
32 validateMethodSignature(
33 "setTechList:void","EventManagement");
34
35 validateMethodSignature(
36 "getCounter:int","EventManagement");
37 validateMethodSignature(
38 "setCounter:void","EventManagement");
39
40 validateMethodSignature(
41 "getSearchEvent:String","EventManagement");
42 validateMethodSignature(
43 "setSearchEvent:void","EventManagement");
44
45 //setters and getters of Hall
46 validateMethodSignature(
47 "getName:String","Participant");
48 validateMethodSignature(
49 "setName:void","Participant");
50
51 validateMethodSignature(
52 "getYearofstudy:String","Participant");
53 validateMethodSignature(
54 "setYearofstudy:void","Participant");
55
56 validateMethodSignature(
57 "getDepartment:String","Participant");
58 validateMethodSignature(
59 "setDepartment:void","Participant");
60
61 validateMethodSignature(
62 "getCollegeName:String","Participant");
63 validateMethodSignature(
64 "setCollegeName:void","Participant");
65
66 validateMethodSignature(
67 "getEventName:String","Participant");
68 validateMethodSignature(
69 "setEventName:void","Participant");
70
71 validateMethodSignature(
72 "getRegistrationFee:double","Participant");
73 validateMethodSignature(
74 "setRegistrationFee:void","Participant");
75
76 }
77
78 private static final Logger LOG = Logger.getLogger("SkeletonValidator");
79
80 protected final boolean validateClassName(String className) {
81
82 boolean iscorrect = false;
83 try {
84 Class.forName(className);
85 iscorrect = true;
86 LOG.info("Class Name " + className + " is correct");
87
88 } catch (ClassNotFoundException e) {
89 LOG.log(Level.SEVERE, "You have changed either the " + "class
name/package. Use the correct package "
90 + "and class name as provided in the skeleton");
91
92 } catch (Exception e) {
93 LOG.log(Level.SEVERE,
94 "There is an error in validating the " + "Class Name.
Please manually verify that the "
95 + "Class name is same as
skeleton before uploading");
96 }
97 return iscorrect;
98
99 }
100
101 protected final void validateMethodSignature(String methodWithExcptn, String className) {
102 Class cls = null;
103 try {
104
105 String[] actualmethods = methodWithExcptn.split(",");
106 boolean errorFlag = false;
107 String[] methodSignature;
108 String methodName = null;
109 String returnType = null;
110
111 for (String singleMethod : actualmethods) {
112 boolean foundMethod = false;
113 methodSignature = singleMethod.split(":");
114
115 methodName = methodSignature[0];
116 returnType = methodSignature[1];
117 cls = Class.forName(className);
118 Method[] methods = cls.getMethods();
119 for (Method findMethod : methods) {
120 if (methodName.equals(findMethod.getName())) {
121 foundMethod = true;
122 if
(!(findMethod.getReturnType().getName().contains(returnType))) {
123 errorFlag = true;
124 LOG.log(Level.SEVERE, " You
have changed the " + "return type in '" + methodName
125 + "'
method. Please stick to the " + "skeleton provided");
126
127 } else {
128 LOG.info("Method signature of "
+ methodName + " is valid");
129 }
130
131 }
132 }
133 if (!foundMethod) {
134 errorFlag = true;
135 LOG.log(Level.SEVERE, " Unable to find the given
public method " + methodName
136 + ". Do not change the " + "given
public method name. " + "Verify it with the skeleton");
137 }
138
139 }
140 if (!errorFlag) {
141 LOG.info("Method signature is valid");
142 }
143
144 } catch (Exception e) {
145 LOG.log(Level.SEVERE,
146 " There is an error in validating the " + "method
structure. Please manually verify that the "
147 + "Method signature is same as
the skeleton before uploading");
148 }
149 }
150
151 }
Grade
Reviewed on Monday, 7 February 2022, 6:34 PM by Automatic grade
Grade 74 / 100
Assessment report
Fail 1 -- test4CheckTheOutput::
$Expected output:"[Print participant details
ParticipantName=Weni
Yearofstudy=3
Department=civil
CollegeName=vjc
EventName=robocar
RegistrationFee=1000.0
ParticipantName=gina
Yearofstudy=2
Department=mech
CollegeName=vjc
EventName=quiz
RegistrationFee=300.0
ParticipantName=jos
Yearofstudy=4
Department=ece
CollegeName=vjec
EventName=games
RegistrationFee=100.0
ParticipantName=fida
Yearofstudy=1
Department=eee
CollegeName=vjec
EventName=papertalk
RegistrationFee=500.0
Enter the event to search
Number of participants for PAPERTALK event is 1]" Actual output:"[Enter the number of
entries
Enter the Participant Name/Yearofstudy/Department/CollegeName/EventName
Print participant details
Participant [name=Weni
yearofstudy=3
department=civil
collegeName=vjc
eventName=robocar
registrationFee=1000.0]
Participant [name=gina
yearofstudy=2
department=mech
collegeName=vjc
eventName=quiz
registrationFee=300.0]
Participant [name=jos
yearofstudy=4
department=ece
collegeName=vjec
eventName=games
registrationFee=100.0]
Participant [name=fida
yearofstudy=1
department=eee
collegeName=vjec
eventName=papertalk
registrationFee=500.0]
Enter the event to search
No participant found]"$
Check your code with the input :Weni/3/civil/vjc/robocar
gina/2/mech/vjc/quiz
jos/4/ece/vjec/games
fida/1/eee/vjec/papertalk
Fail 2 -- test6CheckTheOutputfor_NCount::
$Expected output:"[Print participant details
ParticipantName=philip
Yearofstudy=4
Department=eee
CollegeName=mvc
EventName=robocar
RegistrationFee=1000.0
ParticipantName=susan
Yearofstudy=4
Department=eee
CollegeName=mvc
EventName=robocar
RegistrationFee=1000.0
ParticipantName=vivek
Yearofstudy=3
Department=civil
CollegeName=mvc
EventName=quiz
RegistrationFee=300.0
ParticipantName=vishal
Yearofstudy=3
Department=civil
CollegeName=mvc
EventName=papertalk
RegistrationFee=500.0
Enter the event to search
Number of participants for ROBOCAR event is 2]" Actual output:"[Enter the number of
entries
Enter the Participant Name/Yearofstudy/Department/CollegeName/EventName
Print participant details
Participant [name=philip
yearofstudy=4
department=eee
collegeName=mvc
eventName=robocar
registrationFee=1000.0]
Participant [name=susan
yearofstudy=4
department=eee
collegeName=mvc
eventName=robocar
registrationFee=1000.0]
Participant [name=vivek
yearofstudy=3
department=civil
collegeName=mvc
eventName=quiz
registrationFee=300.0]
Participant [name=vishal
yearofstudy=3
department=civil
collegeName=mvc
eventName=papertalk
registrationFee=500.0]
Enter the event to search
No participant found]"$
Check your code with the input :philip/4/eee/mvc/robocar
susan/4/eee/mvc/robocar
vivek/3/civil/mvc/quiz
vishal/3/civil/mvc/papertalk
robocar
Obtained Pass Percentage. Still few testcases failed . Kindly revisit the Solution
[+]Grading and Feedback
Powered by
====================================================================
1.Red code Technology
Casual Employee:
public class CasualEmployee extends Employee{
}
Employee:
public abstract class Employee {
}
User Interface:
import java.util.Scanner;
public class UserInterface {
2.Dominion Cinemas
Gold Ticket:
public class GoldTicket extends BookAMovieTicket {
public GoldTicket(String ticketId, String customerName, long mobileNumber,
String emailId, String movieName) {
super(ticketId, customerName, mobileNumber, emailId, movieName);
}
public boolean validateTicketId(){
int count=0;
if(ticketId.contains("GOLD"));
count++;
char[] cha=ticketId.toCharArray();
for(int i=4;i<7;i++){
if(cha[i]>='1'&& cha[i]<='9')
count++;
}
if(count==4)
return true;
else
return false;
}
public double calculateTicketCost(int numberOfTickets,String ACFacility){
double amount;
if(ACFacility.equals("yes")){
amount=500*numberOfTickets;
}
else{
amount=350*numberOfTickets;
}
return amount;
}
}
Platinum Ticket:
public class PlatinumTicket extends BookAMovieTicket
{
public PlatinumTicket(String ticketId, String customerName, long mobileNumber,String
emailId, String movieName)
{
super(ticketId, customerName, mobileNumber, emailId, movieName);
}
public boolean validateTicketId(){
int count=0;
if(ticketId.contains("PLATINUM"));
count++;
char[] cha=ticketId.toCharArray();
for(int i=8;i<11;i++){
if(cha[i]>='1'&& cha[i]<='9')
count++;
}
if(count==4)
return true;
else
return false;
}
public double calculateTicketCost(int numberOfTickets,String ACFacility){
double amount;
if(ACFacility.equals("yes")){
amount=750*numberOfTickets;
}
else{
amount=600*numberOfTickets;
}
return amount;
}
}
Silver Ticket:
public class SilverTicket extends BookAMovieTicket{
public SilverTicket(String ticketId, String customerName, long mobileNumber,String emailId,
String movieName)
{
super(ticketId, customerName, mobileNumber, emailId, movieName);
}
public boolean validateTicketId(){
int count=0;
if(ticketId.contains("SILVER"));
count++;
char[] cha=ticketId.toCharArray();
for(int i=6;i<9;i++){
if(cha[i]>='1'&& cha[i]<='9')
count++;
}
if(count==4)
return true;
else
return false;
}
public double calculateTicketCost(int numberOfTickets,String ACFacility){
double amount;
if(ACFacility.equals("yes")){
amount=250*numberOfTickets;
}
else{
amount=100*numberOfTickets;
}
return amount;
}
}
User Interface:
import java.util.*;
public class UserInterface {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter Ticket Id");
String tid=sc.next();
System.out.println("Enter Customer Name");
String cnm=sc.next();
System.out.println("Enter Mobile Number");
long mno=sc.nextLong();
System.out.println("Enter Email id");
String email=sc.next();
System.out.println("Enter Movie Name");
String mnm=sc.next();
System.out.println("Enter number of tickets");
int tno=sc.nextInt();
System.out.println("Do you want AC or not");
String choice =sc.next();
if(tid.contains("PLATINUM")){
PlatinumTicket PT=new PlatinumTicket(tid,cnm,mno,email,mnm);
boolean b1=PT.validateTicketId();
if(b1==true){
double cost =PT.calculateTicketCost(tno, choice);
System.out.println("Ticket cost is "+ cost);
}
else if(b1==false){
System.out.println("Provide valid Ticket Id");
System.exit(0);
}
}
else if(tid.contains("GOLD")){
GoldTicket GT=new GoldTicket(tid,cnm,mno,email,mnm);
boolean b2=GT.validateTicketId();
if(b2==true){
double cost=GT.calculateTicketCost(tno, choice);
System.out.println("Ticket cost is "+cost);
}
else if (b2==false){
System.out.println("Provide valid Ticket Id");
System.exit(0);
}
}
else if(tid.contains("SILVER")){
SilverTicket ST=new SilverTicket(tid,cnm,mno,email,mnm);
boolean b3=ST.validateTicketId();
if(b3==true){
double cost=ST.calculateTicketCost(tno, choice);
System.out.println("Ticket cost is "+cost);
}
else if(b3==false){
System.out.println("Provide valid Ticket Id");
System.exit(0);
}
}
}
}
3.Little Innovators
Main:
import java.util.*;
public class Main {
Air Conditioner:
public class AirConditioner extends ElectronicProducts {
private String airConditionerType;
private double capacity;
public AirConditioner(String productId, String productName, String batchId, String
dispatchDate, int warrantyYears, String airConditionerType, double capacity) {
super(productId, productName, batchId, dispatchDate, warrantyYears);
this.airConditionerType = airConditionerType;
this.capacity = capacity;
}
public String getAirConditionerType() {
return airConditionerType;
}
public void setAirConditionerType(String airConditionerType) {
this.airConditionerType = airConditionerType;
}
public double getCapacity() {
return capacity;
}
public void setCapacity(double capacity) {
this.capacity = capacity;
}
public double calculateProductPrice(){
double price = 0;
if(airConditionerType.equalsIgnoreCase("Residential")){
if (capacity == 2.5){
price = 32000;
}
else if(capacity == 4){
price = 40000;
}
else if(capacity == 5.5){
price = 47000;
}
}
else if(airConditionerType.equalsIgnoreCase("Commercial")){
if (capacity == 2.5){
price = 40000;
}
else if(capacity == 4){
price = 55000;
}
else if(capacity == 5.5){
price = 67000;
}
}
else if(airConditionerType.equalsIgnoreCase("Industrial")){
if (capacity == 2.5){
price = 47000;
}
else if(capacity == 4){
price = 60000;
}
else if(capacity == 5.5){
price = 70000;
}
}
return price;
}
}
Electronic Products:
public class ElectronicProducts {
protected String productId;
protected String productName;
protected String batchId;
protected String dispatchDate;
protected int warrantyYears;
public ElectronicProducts(String productId, String productName, String batchId,
String dispatchDate, int warrantyYears) {
this.productId = productId;
this.productName = productName;
this.batchId = batchId;
this.dispatchDate = dispatchDate;
this.warrantyYears = warrantyYears;
}
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getBatchId() {
return batchId;
}
public void setBatchId(String batchId) {
this.batchId = batchId;
}
public String getDispatchDate() {
return dispatchDate;
}
public void setDispatchDate(String dispatchDate) {
this.dispatchDate = dispatchDate;
}
public int getWarrantyYears() {
return warrantyYears;
}
public void setWarrantyYears(int warrantyYears) {
this.warrantyYears = warrantyYears;
}
}
LED TV:
public class LEDTV extends ElectronicProducts {
private int size;
private String quality;
public LEDTV(String productId, String productName, String batchId, String
dispatchDate, int warrantyYears, int size, String quality) {
super(productId, productName, batchId, dispatchDate, warrantyYears);
this.size = size;
this.quality = quality;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public String getQuality() {
return quality;
}
public void setQuality(String quality) {
this.quality = quality;
}
public double calculateProductPrice(){
double price = 0;
if(quality.equalsIgnoreCase("Low")){
price = size * 850;
}
else if(quality.equalsIgnoreCase("Medium")){
price = size * 1250;
}
else if(quality.equalsIgnoreCase("High")){
price = size * 1550;
}
return price;
}
}
Microwave Oven:
public class MicrowaveOven extends ElectronicProducts{
private int quantity;
private String quality;
public MicrowaveOven(String productId, String productName, String batchId, String
dispatchDate, int warrantyYears, int quantity, String quality) {
super(productId, productName, batchId, dispatchDate, warrantyYears);
this.quantity = quantity;
this.quality = quality;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public String getQuality() {
return quality;
}
public void setQuality(String quality) {
this.quality = quality;
}
public double calculateProductPrice(){
double price = 0;
if(quality.equalsIgnoreCase("Low")){
price = quantity * 1250;
}
else if(quality.equalsIgnoreCase("Medium")){
price = quantity * 1750;
}
else if(quality.equalsIgnoreCase("High")){
price = quantity * 2000;
}
return price;
}
}
User Interface:
import java.util.Scanner;
public class UserInterface {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Product Id");
String productId = sc.next();
System.out.println("Enter Product Name");
String productName = sc.next();
System.out.println("Enter Batch Id");
String batchId = sc.next();
System.out.println("Enter Dispatch Date");
String dispatchDate = sc.next();
System.out.println("Enter Warranty Years");
int warrantyYears = sc.nextInt();
double price;
String quality;
switch(productName){
case "AirConditioner":
System.out.println("Enter type of Air Conditioner");
String type = sc.next();
System.out.println("Enter quantity");
double capacity = sc.nextDouble();
AirConditioner ac = new AirConditioner(productId, productName, batchId,
dispatchDate, warrantyYears, type, capacity);
price = ac.calculateProductPrice();
System.out.printf("Price of the product is %.2f", price);
break;
case "LEDTV":
System.out.println("Enter size in inches");
int size = sc.nextInt();
System.out.println("Enter quality");
quality = sc.next();
LEDTV l = new LEDTV(productId, productName, batchId, dispatchDate,
warrantyYears, size, quality);
price = l.calculateProductPrice();
System.out.printf("Price of the product is %.2f", price);
break;
case "MicrowaveOven":
System.out.println("Enter quantity");
int quantity = sc.nextInt();
System.out.println("Enter quality");
quality = sc.next();
MicrowaveOven m = new MicrowaveOven(productId, productName, batchId,
dispatchDate, warrantyYears, quantity, quality);
price = m.calculateProductPrice();
System.out.printf("Price of the product is %.2f", price);
break;
default:
System.out.println("Provide a valid Product name");
System.exit(0);
}
}
}
5. Reverse a word
import java.util.*;
class HelloWorld {
public static void main(String[] args) {
String[] words ;
Scanner myObj = new Scanner(System.in);
input1.append(words[words.length-1]);
// reverse StringBuilder input1
input1= input1.reverse();
input1.append(words[0]);
System.out.println(input1);
}
else {
input1.append(words[0]);
// reverse StringBuilder input1
input1= input1.reverse();
input1.append(words[words.length-1]);
System.out.println(input1);
}
}
}
}
i
mpor
tjav
a.ut
il
.Scanner
;
publ
i
cclassMai n{
pri
vatestat
icintget
Sum(longnum){
char
[]chars=Long.
toStr
ing(
num).
toChar
Arr
ay(
);
i
ntsum =0;
f
or(
charch:
chars){
sum +=Char
acter
.di
git
(ch,
10)
;
}
r
etur
nsum;
}
pr
ivatestat
icintget
Numerol
ogy(
longnum){
Str
ingstr
ing=Stri
ng.
val
ueOf
(num);
whi
l
e(str
ing.
length(
)!=1){
st
ri
ng=St ri
ng.v
alueOf
(get
Sum(
Long.
par
seLong(
str
ing)
));
}
r
etur
nInt
eger
.par
seI
nt(
str
ing)
;
}
pr
ivat
estati
cintget
OddCount
(l
ongnum){
i
ntoddCount=0;
f
or(
charch:Long.t
oStri
ng(num)
.t
oChar
Arr
ay(
)){
if(
Character
.di
git
(ch,10)%2!=0){
++oddCount;
}
}
r
etur
noddCount
;
}
pr
ivat
estati
cintget
EvenCount
(l
ongnum){
i
ntev
enCount=0;
f
or(
charch:Long.t
oStri
ng(num)
.t
oChar
Arr
ay(
)){
if(
Character
.di
git
(ch,10)%2==0){
++evenCount;
}
}
r
etur
nev
enCount
;
}
publ
i
cstati
cv oi
dmai n(
Str
ing[
]ar
gs){
Scannerscanner=newScanner(
Syst
em.
i
n);
Syst
em.
out.
pri
ntl
n("
Enterthenumber
");
l
ongnum =scanner
.next
Long();
Sy
stem.
out
.pr
int
ln(
"Sum ofdi
git
s")
;
Sy
stem.
out
.pr
int
ln(
getSum(num));
Sy
stem.
out
.pr
int
ln(
"Numerol
ogynumber
");
Sy
stem.
out
.pr
int
ln(
getNumerol
ogy(
num)
);
Sy
stem.
out
.pr
int
ln(
"Numberofoddnumber
s")
;
Sy
stem.
out
.pr
int
ln(
getOddCount
(num)
);
Sy
stem.
out
.pr
int
ln(
"Numberofev
ennumber
s")
;
Sy
stem.
out
.pr
int
ln(
getEv
enCount
(num)
);
}
}
import java.util.*;
public class tourism {
static String name;
static String place;
static int days;
static int tickets;
static double price = 0.00;
static double total = 0.00;
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Enter the passenger name");
name = in.nextLine();
System.out.println("Enter the place name");
place=in.nextLine();
if(place.equalsIgnoreCase("beach")
||place.equalsIgnoreCase("pilgrimage")||
place.equalsIgnoreCase("heritage")||place.equalsIgnoreCase("Hills")||
place.equalsIgnoreCase("palls")||place.equalsIgnoreCase("adventure")){
System.out.println("Enter the number of days");
days = in.nextInt();
if(days>0){
System.out.println("Enter the number of Tickets");
tickets = in.nextInt();
if(tickets>0){
if(place.equalsIgnoreCase("beach")){
price = tickets*270;
if(price>1000){
total = 85*price/100;
System.out.printf("Price:%.2f",total);
}
else {
System.out.printf("Price:%.2f",price);
}
}
else if(place.equalsIgnoreCase("prilgrimage")){
price = tickets*350;
if(price>1000){
total = 85*price/100;
System.out.printf("Price:%.2f",total);
}
else {
System.out.printf("Price:%.2f",price);
}
}
else if(place.equalsIgnoreCase("heritage")){
price = tickets*430;
if(price>1000){
total = 85*price/100;
System.out.printf("Price:%.2f",total);
}
else {
System.out.printf("Price:%.2f",price);
}
}
else if(place.equalsIgnoreCase("hills")){
price = tickets*780;
if(price>1000){
total = 85*price/100;
System.out.printf("Price:%.2f",total);
}
else {
System.out.printf("Price:%.2f",price);
}
}
This study source was downloaded by 100000841384095 from CourseHero.com on 02-15-2022 03:25:30 GMT -06:00
https://www.coursehero.com/file/79032946/singapore-tourismtxt/
else if(place.equalsIgnoreCase("palls")){
price = tickets*1200;
if(price>1000){
total = 85*price/100;
System.out.printf("Price:%.2f",total);
}
else {
System.out.printf("Price:%.2f",price);
}
}
else {
price = tickets*4500;
if(price>1000){
total = 85*price/100;
System.out.printf("Price:%.2f",total);
}
else {
System.out.printf("Price:%.2f",price);
}
}
}
else{
System.out.println(tickets+" is an Invalid no. of tickets");
}
}
else{
System.out.println(days+" is an Invalid no. of days");
}
}
else {
System.out.println(place+" is an Invalid place");
}
}
}
This study source was downloaded by 100000841384095 from CourseHero.com on 02-15-2022 03:25:30 GMT -06:00
https://www.coursehero.com/file/79032946/singapore-tourismtxt/
Powered by TCPDF (www.tcpdf.org)
publ
i
cclassAccount{
pri
vatel
ongaccountNumber;
pri
vatedoubl
ebalanceAmount
;
publ
i
cAccount (
longaccount
Number,doubl
ebal
anceAmount
){
thi
s.account Number=account
Number;
thi
s.balanceAmount=balanceAmount;
}
publ
i
clonggetAccount
Number
(){
ret
urnaccount
Number;
}
publ
i
cv oidsetAccount
Number(l
ongaccountNumber
){
thi
s.accountNumber=account
Number ;
}
publ
i
cdoublegetBal
anceAmount
(){
ret
urnbal
anceAmount;
}
publ
i
cv oidset
BalanceAmount
(doubl
ebalanceAmount
){
thi
s.bal
anceAmount=balanceAmount;
}
publ
i
cvoiddeposi
t(
doubl
edeposi
tAmount
){
bal
anceAmount+=deposi
tAmount
;
}
publ
i
cbool eanwi t
hdr
aw(doubl
ewithdr
awAmount
){
if(
withdrawAmount<=balanceAmount){
balanceAmount-=wit
hdrawAmount;
retur
nt r
ue;
}
r
etur
nfal
se;
}
}
i
mpor
tjav
a.text.Deci
malFor
mat
;
i
mpor
tjav
a.util
.Scanner
;
publ
i
cclassMai n{
publ
icstati
cv oi
dmai n(
Str
ing[
]args){
Scannerscanner=newScanner (
Syst
em.
i
n);
DecimalFor
matdecimalFormat=newDecimal
For
mat
("
0.00"
);
Syst
em.out
.pri
ntl
n("
Ent
ert
heaccountnumber:
")
;
l
ongaccountNumber=scanner
.next
Long(
);
Syst
em.out.
pri
ntl
n("
Ent
eri
niti
albal
ance:
")
;
doubl
ebalanceAmount=scanner.
next
Doubl
e()
;
Accountaccount=newAccount
(account
Number
,bal
anceAmount
);
Sy
stem.
out
.pr
int
ln(
"Ent
ert
heamountt
obedeposi
ted:
")
;
doubledeposit
Amount=scanner.next
Double()
;
account.
deposit
(deposi
tAmount)
;
doubleavai
labl
eBalance=account.
get
BalanceAmount
();
Sy
stem.out
.pr
int
ln(
"Av
ail
abl
e bal
ance i
s:" +
deci
mal
For
mat.f
ormat(
avail
abl
eBal
ance)
);
Syst
em.out.pri
ntl
n("
Ent
ertheamounttobewithdrawn:
")
;
doublewit
hdrawAmount=scanner .
next
Doubl
e();
bool
eanisWi t
hdrawn=account.
withdr
aw(wi
thdrawAmount
);
avai
labl
eBalance=account.
get
BalanceAmount(
);
i
f(!
isWithdr
awn){
Sy
stem.out
.pr
int
ln(
"I
nsuf
fi
cientbal
ance"
);
}
Sy
stem.out
.pr
int
ln(
"Av
ail
abl
e bal
ance i
s:" +
deci
mal
For
mat.f
ormat(
avail
abl
eBal
ance)
);
}
}
Software License Details
index.html
<!--Do not make any change in this code template -->
<html>
<head>
<script src="script.js" type="text/javascript"> </script>
</head>
<body>
<h2>Software License Details</h2>
<table>
<tr>
<td> Software Name</td>
<td><input type="text" id="softwareName" placeholder="Enter the software
name" required></td>
</tr>
<tr>
<td> Serial Key </td>
<td> <input type="text" id="serialKey" placeholder="Enter 12 digit alphanumeric
serial key" required></td>
</tr>
<tr>
<td> </td>
<td> <button id="validate" onclick=validate()>Validate</button> </td>
</tr>
</table>
<div id="result"></div>
</body>
</html>
script.js
// Fill the code wherever necessary
function validate()
{
var softwareName=document.getElementById("softwareName").value;
var serialKey = document.getElementById("serialKey").value;
//var serialKey= //Fill your code here to get the value of element by using id "serialKey" and
store it in a variable "serialKey"
//HINT: use the above "softwareName" as a sample to get "serialKey"
function validateSerialKey(serialKey)
{
var pattern=/^[0-9a-zA-Z]{12}$/;
var isSerialKey = serialKey.match(pattern);
return Boolean(isSerialKey);
// Fill your code here
// find if the serialKey is valid by checking if it matches the given pattern
// return true or false
<tr>
<td> </td>
<td> <button id="submit" onclick=validate()>Submit</button> </td>
</tr>
</table>
<div id="result"></div>
</body>
</html>
script.js
// Fill the code wherever necessary
function validate()
{
var policyNumber=document.getElementById("policyNumber").value;
amount=document.getElementById("amount").value;
//var amount= //Fill your code here to get the value of element by using id "amount" and
store it in a variable "amount"
//HINT: use the above "policyNumber" as a sample to get "amount"
function validatePolicyNumber(policyNumber)
{
var pattern=/^[0-9]{7}$/;
if(!(policyNumber.match(pattern)))
return false
else
return true;
}
Email Validation
index.html
<!--Do not make any change in this code template -->
<html>
<head>
<script src="script.js" type="text/javascript"> </script>
</head>
<body>
<h2>Registration form</h2>
<table>
<tr>
<td> Trainee Name</td>
<td><input type="text" id="traineeName" placeholder="Enter the trainee name"
required></td>
</tr>
<tr>
<td> Email ID </td>
<td> <input type="text" id="emailId" placeholder="Enter the email id"
required></td>
</tr>
<tr>
<td> </td>
<td> <button id="register" onclick=validate()>Register</button> </td>
</tr>
</table>
<div id="result"></div>
</body>
</html>
script.js
// Fill the code wherever necessary
function validate()
{
var traineeName=document.getElementById("traineeName").value;
//var emailId= //Fill your code here to get the value of element by using id "emailId" and
store it in a variable "emailId"
//HINT: use the above "traineeName" as a sample to get "emailId"
var emailId = document.getElementById("emailId").value;
if(traineeName && emailId)
{
if(validateEmailId(emailId))
document.getElementById("result").innerHTML = "The email id : "+emailId+" is validated
successfully for the trainee "+traineeName;
else
document.getElementById("result").innerHTML = "Please, provide a valid email id";
}
else
document.getElementById("result").innerHTML = "Trainee name (or) email id missing";
}
function validateEmailId(emailId)
{
// Fill your code here to check whether the 'email' has '@' symbol and '.' symbol
// HINT : emailId.includes("@") will return true, if the emailId has '@' symbol.
// find whether email has both '@' and '.'
// Return true or false
if(emailId.includes('@') && emailId.includes('.')){
return true;
}
return false;
Number Of Days
index.html
<!--Do not make any change in this code template -->
<html>
<head>
<script src="script.js" type="text/javascript"> </script>
</head>
<body>
<h2>Recharge Pack Validity</h2>
<table>
<tr>
<td> Recharge Pack Name</td>
<td><input type="text" id="rechargePackName" placeholder="Enter the recharge
pack name" required></td>
</tr>
<tr>
<td> Validity (in days) </td>
<td> <input type="number" id="validity" min="1" placeholder="Enter the validity
in days" required></td>
</tr>
<tr>
<td> </td>
<td> <button id="validate" onclick=validate()>Submit</button> </td>
</tr>
</table>
<div id="result"></div>
</body>
</html>
script.js
// Fill the code wherever necessary
function validate()
{
var rechargePackName=document.getElementById("rechargePackName").value;
var validity=document.getElementById("validity").value;//Fill your code here to get the value
of element by using id "validity" and store it in a variable "validity"
//HINT: use the above "rechargePackName" as a sample to get "validity"
function validateRechargePackName(rechargePackName)
{
var pattern=/^[A-Z]{2}[0-9]{3}$/;
// Fill your code here
// find if the rechargePackName is valid by checking if it matches the given pattern
// return true or false
if(rechargePackName.match(pattern))
{
return true;
}
else
{
return false;
}
Frequency Calculation
index.html
<!--Do not make any change in this code template -->
<html>
<head>
<script src="script.js" type="text/javascript"> </script>
</head>
<body>
<h2>Frequency Calculator</h2>
<table>
<tr>
<td> Frequency Band</td>
<td><input type="text" id="band" placeholder="Enter the frequency band"
required></td>
</tr>
<tr>
<td> Wavelength in mm </td>
<td> <input type="number" id="wavelength" placeholder="0.1-1000" min="0.1"
max="1000" step="0.1" required></td>
</tr>
<tr>
<td> </td>
<td> <button id="submit" onclick=validate()>Submit</button> </td>
</tr>
<tr>
<td colspan="2">
* Acceptable frequency bands are H, M, L, U, S, C, X, K.
</td>
</tr>
</table>
<div id="result"></div>
</body>
</html>
script.js
// Fill the code wherever necessary
function validate()
{
var band=document.getElementById("band").value;
var wavelength=document.getElementById("wavelength").value //Fill your code here to get
the value of element by using id "wavelength" and store it in a variable "wavelength"
//HINT: use the above "band" as a sample to get "wavelength"
function validateFrequencyBand(band)
{
var pattern=/^[H|M|L|U|S|C|X|K]$/;
// Fill your code here
// find if the band is valid by checking if it matches the given pattern
// return true or false
if(band.match(pattern))
{
return true;
}
else
{
return false;
}
AC Maintenance Service-V1
AcMaintenanceService.html
<!DOCTYPE html>
<html>
<head>
#submit, #reset {
/* Fill attributes and values */
font-weight: bold;
font-family: Candara;
background-color: #556B2F;
width:10em;
height:35px;
border-radius: 10px;
}
input {
width:13.6em;
}
#appointment {
font-family:sans-serif;
width:80%;
border-collapse:collapse;
text-align:left;
}
#acType, textarea{
width:13.6em;
}
select {
width:14em;
}
td{
padding:3px;
}
#male, #female, #yearlyMaintenance {
width:10pt;
}
.checkboxes label {
display: inline-block;
padding-right: 10px;
white-space: nowrap;
}
.checkboxes input {
vertical-align: middle;
}
.checkboxes label span {
vertical-align: middle;
}
</style>
</head>
<body>
<table id="appointment">
<tr>
<td> <label for = 'customerName'>Customer Name</label></td>
<td><input type='text' id = 'customerName' placeholder="Enter your name" required> </td>
</tr>
<tr>
<td> <label for = 'mobileNumber'>Mobile Number</label> </td>
<td> <input type ='tel' id ='mobileNumber' name ='Mobile Number' placeholder="Enter your
mobile number" pattern="^[7-9][0-9]{9}$" maxlength="10" minLength = '10' required> </td>
</tr>
<tr>
<td> <label for = 'address'>Address</label></td>
<td> <textarea id= 'address' name = 'address' placeholder="Enter your address" rows = '5' cols
='25' required></textarea> </td>
</tr>
<tr>
<td> <label for = 'acType'>AC Type</label> </td>
<td>
<select id="acType">
<option id="Split" value ="Split">Split</option>
<option id="Window" value ="Window">Window</option>
<option id = "Centralized" value = "Centralized">Centralized</option>
<option id='Portable' value ='Portable'>Portable</option>
</select>
</td>
</tr>
<tr>
<td> <label for ='serviceType'>Service Type</label> </td>
<td>
<input type="checkbox" name="serviceType" id="Cleaning" value="Cleaning" ><label for =
'Cleaning'> Cleaning</label>
<input type="checkbox" name="serviceType" id="Repair" value="Repair" ><label for =
'Repair'> Repair</label>
<input type="checkbox" name="serviceType" id="Gas Refill" value="Gas Refill" ><label for =
'Gas Refill'> Gas Refill</label>
<input type="checkbox" name="serviceType" id="Relocation" value="Relocation" ><label for
= 'Relocation'> Relocation</label>
<input type="checkbox" name="serviceType" id="Filter" value="Filter" ><label for = 'Filter'>
Filter</label>
</td>
</tr>
<tr>
<td> <label for = 'dateForAppointment'>Date for Appointment</label> </td>
<td> <input type ='date' id = 'dateForAppointment' required> </td>
</tr>
<tr>
<td> <label for ='yearlyMaintenance'>Yearly Maintenance</label> </td>
<td> <input type = 'checkbox' id = 'yearlyMaintenance' name = 'yearlyMaintenance'> <label
for = 'yearlyMaintenance'>Select if required</label></td>
</tr>
<tr>
<td> <!-- empty cell --></td>
<td>
<input type = 'submit' value = 'Submit' id = 'submit'>
<input type ='reset' value ='Clear' id = 'reset' >
</td>
</tr>
<tr>
<td colspan="2">
<div id="result"></div>
</td>
</tr>
</table>
</form>
</body>
</html>
script.js
function getTotalService() {
var totalServices = document.getElementsByName("serviceType");
var count = 0;
for(var i=0; i<totalServices.length; i++) {
if(totalServices[i].checked) {
count++
}
}
return count;
}
function getServiceCost() {
var totalServices = document.getElementsByName("serviceType");
var totalCost = 0;
for(var i=0; i<totalServices.length; i++) {
if(totalServices[i].checked) {
switch(totalServices[i].value) {
case "Cleaning":
totalCost += 500;
break;
case "Repair":
totalCost += 2500;
break;
case "Gas Refill":
totalCost += 750;
break;
case "Relocation":
totalCost += 1500;
break;
case "Filter":
totalCost += 250;
break;
default:
break;
}
}
}
return totalCost;
}
function calculateDiscount(serviceCost) {
serviceCost = serviceCost*0.85;
return serviceCost;
}
function getYearlyMaintenanceCost() {
var yearlyMaintenance = document.getElementsByName("yearlyMaintenance");
if(yearlyMaintenance[0].checked)
return 1500;
else
return 0;
}
function bookAppointment() {
var totalNumberOfServices = getTotalService();
var serviceCost = 0;
if(totalNumberOfServices > 2) {
serviceCost = calculateDiscount(getServiceCost());
} else {
serviceCost = getServiceCost();
}
if(yearlyMaintenanceCost) {
document.getElementById("result").innerHTML = "Your booking for " + acType +
" AC service is successful!<br>The estimated service cost with maintenance is Rs." +
Math.round(totalCost);
} else {
document.getElementById("result").innerHTML = "Your booking for " + acType +
" AC service is successful!<br>The estimated service cost is Rs." + Math.round(totalCost);
}
input[type="text"] {
width: 97%;}
input[type="number"] {
width: 97%;}
input[type="tel"] {
width: 97%;}
body{
background-image:url('WEHOST.jpg');
background-size: 100%;
font-weight: bold;
}
div{
font-size: 20px;
text-align: center;
color:#FFFFFF;
margin-left: auto;
margin-right: auto;
}
h3{
width: 50%;
color: #FFFFFF;
background-color: #000080;
margin-left: 25%;
margin-right: auto;
text-align: center;
font-family: Verdana;
padding: 5px;
border-radius: 6px;
}
::-webkit-input-placeholder {
color: #808080; }
#submit{
width: 50%;
color: #FFFFFF;
background-color: #000080;
margin-left: 25%;
margin-right: auto;
padding: 5px;
font-family: Verdana;
font-weight: bold;
border-radius: 6px;
}
</style>
</head>
<body>
<table>
<tr>
<td>Purchase Date</td>
<td><input type="text" id="pdate" onfocus="today()" required/></td>
</tr>
<tr>
<td>Customer Name</td>
<td><input type="text" id="cname" placeholder="Enter the customer name" pattern="[a-zA-
Z\s]+" required></td>
</tr>
<tr>
<td>Address</td>
<td><textarea placeholder="Enter the address" rows="4" cols="50" id="address"
required></textarea></td>
</tr>
<tr>
<td>Phone Number</td>
<td><input type="tel" id="phno" placeholder="Phone number" pattern="[7|8|9]+[0-9]{9}"
required></td>
</tr>
<tr>
<td>Server Type</td>
<td><select id="stype" required>
<option value="Select Server Type..">Select Server Type..</option>
<option id= "Dedicated Server" value="Dedicated Server">Dedicated Server</option>
<option id="VPS" value="VPS">VPS</option>
<option id= "Storage Server" value="Storage Server">Storage
Server</option>
<option id="Database Server" value="Database Server">Database Server</option>
</select>
</td>
</tr>
<tr>
<td>CPU(Core)</td>
<td><select id="core" required>
<option value="Select no of cores..">Select no of cores..</option>
<option id="2 cores" value="2 cores">2 cores</option>
<option id="4 cores" value="4 cores">4 cores</option>
<option id="6 cores" value="6 cores">6 cores</option>
<option id="8 cores" value="8 cores">8 cores</option>
</select>
</td>
</tr>
<tr>
<td>Configuration</td>
<td><select id="configuration" required>
<option value="Select configuration..">Select configuration..</option>
<option id="4 GB RAM , 300 GB SSD-boosted Disk Storage" value="4 GB RAM , 300 GB SSD-
boosted Disk Storage">4 GB RAM , 300 GB SSD-boosted Disk Storage</option>
<option id="8 GB RAM , 700 GB SSD-boosted Disk Storage" value="8 GB RAM , 700 GB SSD-
boosted Disk Storage">8 GB RAM , 700 GB SSD-boosted Disk Storage</option>
<option id= "12 GB RAM , 1 TB SSD-boosted Disk Storage" value="12 GB RAM , 1
TB SSD-boosted Disk Storage">12 GB RAM , 1TB SSD-boosted Disk Storage</option>
</select>
</td>
</tr>
<tr>
<td>Payment Type</td>
<td><select id="ptype" required>
<option id="Card" value="Card">Debit card / Credit card</option>
<option id="Cash" value="Cash">Cash</option>
</select>
</td>
</tr>
</table>
<br/><br/>
<input type="submit" value="CONFIRM PURCHASE" id="submit" onclick="calculatePurchaseCost()">
<br/><br/>
<br/><br/>
<!--</form>-->
</body>
</html>
script.js
function getCoreCost(core)
{
if(core.startsWith("2"))
{
return 20000;
}
if(core.startsWith("4"))
{
return 25000;
}
if(core.startsWith("6"))
{
return 30000;
}
if(core.startsWith("8"))
{
return 40000;
}
}
function getConfigurationCost(config)
{
if(config.startsWith("4"))
{
return 5000;
}
if(config.startsWith("8"))
{
return 10000;
}
if(config.startsWith("1"))
{
return 15000;
}
}
function calculateTax(totalcost,ptype)
{
let tax,ex=0;
totalcost=parseInt(totalcost);
tax=totalcost*12/100;
if(ptype.startsWith("Card"))
{
ex=(totalcost+tax)*2/100;
}
return Math.round(totalcost+tax+ex);
function calculatePurchaseCost()
{
var core=document.getElementById('core').value;
var conf=document.getElementById('configuration').value;
var corecost=getCoreCost(core);
var confcost=getConfigurationCost(conf);
var totalcost=corecost+confcost;
var ptype=document.getElementById('ptype').value;
var tax=calculateTax(totalcost,ptype);
var server=document.getElementById('stype').value;
document.getElementById('result').innerHTML="Purchase of a "+server+" with "+conf+" has been
logged!<br>An amount of Rs."+tax+", inclusive of tax has been received by "+ptype;
}
input[type="number"] {
width:98%;
}
input[type="text"] {
width:98%;
}
input[type="date"] {
width: 98%;
}
input[type="email"] {
width:98%;
}
input[type="tel"] {
width: 98%;
}
select {
width: 98%;
}
body{
margin-left: auto;
margin-right: auto;
width: 60%;
background-size:60%;
}
form {
margin-left: auto;
margin-right: auto;
text-align: center;
width: 50%;
}
h1 {
background-color: #00cc66;
color: #FFFFFF;
font-family: Courier New;
font-style: italic;
text-align: center;
}
td, th {
border: 1px solid #ddd;
padding: 8px;
}
#main{
background-color: #9999ff;
padding-top: 12px;
padding-bottom: 12px;
text-align: center;
color: #FFFFFF;
font-weight: bold;
padding-left: 10px;
padding-right: 10px;
}
#result{
font-size:20px;
font-weight:bold;
}
</style>
</head>
<body>
<div id="main">
<h1>Boat Ride Bill Automation</h1>
<form onsubmit="return bookRide()">
<table>
<tr>
<td>Customer Name</td>
<td><input type="text" id="cname" name="cname" placeholder="Customer
Name" /></td>
</tr>
<tr>
<td>Phone Number</td>
<td><input type="tel" id="phno" name="phno" placeholder="Phone
Number" /></td>
</tr>
<tr>
<td>Email</td>
<td><input type="email" id="email" name="email" placeholder="Email" /></td>
</tr>
<tr>
<td>Number of Persons</td>
<td><input type="text" id="noOfPersons" name="noOfPersons"
placeholder="Number of Persons" required /></td>
</tr>
<tr>
<td>Boat Type</td>
<td><select id="btype" name="btype">
<option id="2seater" value="2 Seater Boat">2 Seater Pedal Boat</option>
<option id="4seater" value="4 Seater Boat">4 Seater Pedal Boat</option>
<option id="8seater" value="8 Seater Boat">8 Seater Motor Boat</option>
<option id="15seater" value="15 Seater Boat">15 Seater Motor Boat</option>
</select></td>
</tr>
<tr>
<td>Travel Duration in Hours</td>
<td><input type="number" id="duration" name="duration" /></td>
</tr>
</table>
<br>
<p><input type="submit" id="submit" name="submit" value="Book Ride"/></p>
<div id="result"></div>
</form>
</div>
<script src="script.js"></script>
</body>
</html>
script.js
function bookRide(){
var btype=document.getElementById("btype").value;
var noOfPersons=document.getElementById("noOfPersons").value;
var duration=document.getElementById("duration").value;
var boatCount=getBoatCount(btype,noOfPersons);
var boatPrice=getBoatPrice(btype,boatCount);
var cal=calculateBill(boatPrice,duration);
document.getElementById("result").innerHTML="You need to pay Rs."+cal;
}
function calculateBill(boatPrice,duration){
return boatPrice*duration;
}
function getBoatPrice(btype,boatCount){
if(btype=="2 Seater Boat"){
return (boatCount*240);
}
if(btype=="4 Seater Boat"){
return (boatCount*260);
}
if(btype=="8 Seater Boat"){
return (boatCount*560);
}
if(btype=="15 Seater Boat"){
return (boatCount*990);
}
}
function getBoatCount(btype,noOfPersons){
if(btype=="2 Seater Boat"){
if (noOfPersons%2===0){
return(parseInt(noOfPersons/2));
}
else{
return(parseInt(noOfPersons/2)+1);
}
}
if(btype=="4 Seater Boat"){
if (noOfPersons%4===0){
return(parseInt(noOfPersons/4));
}
else{
return(parseInt(noOfPersons/4)+1);
}
}
if(btype=="8 Seater Boat"){
if (noOfPersons%8===0){
return(parseInt(noOfPersons/8));
}
else{
return(parseInt(noOfPersons/8)+1);
}
}
if(btype=="15 Seater Motor Boat"){
if (noOfPersons%15===0){
return(parseInt(noOfPersons/15));
}
else{
return(parseInt(noOfPersons/15)+1);
}
}
}
Singapore Tourism-V1
index.html
<!DOCTYPE html>
<html>
<head>
<title>Singapore Tourism</title>
<style>
input[type="number"],input[type="text"],input[type="date"],input[type="email"],input[type=
"tel"],select {
width:95%;
}
body{
background-color: #993366;
font-weight: bold;
}
div{
margin-left: auto;
margin-right: auto;
text-align: center;
color: #FFFFFF;
font-size: 20px;
}
h3{
font-family: Verdana;
text-align: center;
border-radius: 6px;
margin-left: auto;
margin-right: auto;
background-color: #00ccff;
color: #FFFFFF;
width: 50%;
padding: 5px;
}
::-webkit-input-placeholder {
color: #696969;
font-weight: bold;
}
#submit{
color: #FFFFFF;
font-weight: bold;
font-family: Verdana;
background-color: #00ccff;
border-radius: 6px;
padding: 5px;
width: 50%;
margin-right: auto;
margin-left: auto;
}
#result{
color: #000000;
font-size: 20px;
}
</style>
</head>
<body>
<div>
<h3>Singapore Tourism</h3>
<form onsubmit="return calculateCost()">
<table border="1">
<tr>
<td> Name </td>
<td> <input type="text" id="name" required></td>
</tr>
<tr>
<td> Phone no </td>
<td> <input type="tel" id="phno" required></td>
</tr>
<tr>
<td> Email ID </td>
<td> <input type="email" id="email" required></td>
</tr>
<tr>
<td> Number of Persons </td>
<td> <input type="number" id="noOfPersons" required></td>
</tr>
<tr>
<td> Prefer Stay</td>
<td><input type="radio" id="yes" name="preferStay" value="Yes" required
onchange="disableNoOfDaysStay()">Yes
<input type="radio" id="no" name="preferStay" value="No" required
onchange="disableNoOfDaysStay()">No</td>
</tr>
<tr>
<td> Number of Days Stay </td>
<td> <input type="number" id="noOfDaysStay" required></td>
</tr>
<tr>
<td>Places you would like to visit</td>
<td>
<input type="checkbox" name="placesOfChoice" id="Pilgrimage"
value="Pilgrimage">Places Of Pilgrimage<br>
<input type="checkbox" name="placesOfChoice" id="Heritage"
value="Heritage">Places Of Heritage<br>
<input type="checkbox" name="placesOfChoice" id="Hills" value="Hills">Hills<br>
<input type="checkbox" name="placesOfChoice" id="Falls" value="Falls">Falls<br>
<input type="checkbox" name="placesOfChoice" id="Beach"
value="Beach">Beach<br>
<input type="checkbox" name="placesOfChoice" id="Adventures"
value="Adventures">Places Of Adventures
</td>
</tr>
</table>
<div id="result"></div>
</form>
</div>
<script src="script.js" type="text/javascript"> </script>
</body>
</html>
script.js
function getCount()
{
var count=0;
if(document.getElementById("Pilgrimage").checked===true)
{
count+=1;
}
if(document.getElementById("Heritage").checked===true)
{
count+=1;
}
if(document.getElementById("Hills").checked===true)
{
count+=1;
}
if(document.getElementById("Falls").checked===true)
{
count+=1;
}
if(document.getElementById("Beach").checked===true)
{
count+=1;
}
if(document.getElementById("Adventures").checked===true)
{
count+=1;
}
return count;
}
function getTotalCost(noOfpersons)
{
var initcost=0;
if(document.getElementById("Pilgrimage").checked===true)
{
initcost+=350;
}
if(document.getElementById("Heritage").checked===true)
{
initcost+=430;
}
if(document.getElementById("Hills").checked===true)
{
initcost+=780;
}
if(document.getElementById("Falls").checked===true)
{
initcost+=1200;
}
if(document.getElementById("Beach").checked===true)
{
initcost+=270;
}
if(document.getElementById("Adventures").checked===true)
{
initcost+=4500;
}
return initcost*noOfpersons;
}
function calculateDiscount(cost)
{
if(getCount()>=2)
{
return (cost*(85/100));
}
return 0;
}
function getStayCost(noOfPersons)
{
if(document.getElementById("yes").checked===true)
{
var noOfDays=document.getElementById("noOfDaysStay").value;
return noOfPersons* noOfDays *150;
}
return 0;
}
function disableNoOfDaysStay()
{
if(document.getElementById("no").checked===true)
{
document.getElementById("noOfDaysStay").setAttribute("disabled",true);
}
/*if(document.getElementById("yes").checked===true)
{
document.getElementById("noOfDaysStay").setAttribute("disabled",false);
}*/
}
function calculateCost()
{
var noOfPersons=document.getElementById("noOfPersons").value;
var totalcost=getTotalCost(noOfPersons);
var discount=calculateDiscount(totalcost);
var staycost=getStayCost(noOfPersons);
var packagecost=discount+staycost;
var res=packagecost+936;
document.getElementById("result").innerHTML="Your preferred package cost "+res+"$";
return false;
}
Monthly Instalment Estimator-V1
index.html
<!DOCTYPE html>
<html>
<head>
<title>Monthly Instalment Estimator</title>
<style>
input[type="number"] {
width:98%;
}
input[type="text"] {
width:98%;
}
input[type="date"] {
width: 98%;
}
input[type="email"] {
width:98%;
}
input[type="tel"] {
width: 98%;
}
select {
width: 98%;
}
body{
background-color:#FFAACC;
}
div{
margin-left: auto;
margin-right: auto;
text-align: center;
color: #FFFFFF;
font-size: 20px;
}
h3{
font-family: Verdana;
text-align: center;
border-radius: 6px;
margin-left: auto;
margin-right: auto;
background-color: #770080;
color: #FFFFFF;
width: 50%;
padding: 5px;
}
table, td, tr{
margin-left: auto;
margin-right: auto;
border: solid 2px black;
border-spacing: 1px;
border-radius: 6px;
width: 50%;
padding: 1px;
color: #000099;
background-color: #F2F2F2 ;
}
::-webkit-input-placeholder {
color: #696969;
font-weight: bold;
}
#submit{
margin-right: auto;
margin-left: auto;
color: #FFFFFF;
font-weight: bold;
font-family: Verdana;
background-color: #770080;
text-align:center;
border-radius: 6px;
padding: 5px;
width: 50%;
}
#result{
color: #770080;
font-size: 20px;
font-weight: bold;
}
</style>
</head>
<body>
<div>
<h3>Monthly Instalment Estimator</h3>
<form onsubmit="return availLoan()">
<table>
<tr>
<td>Applicant Name</td>
<td><input type="text" id="aname" name="aname" placeholder="Applicant Name"
required /></td>
</tr>
<tr>
<td>Phone Number</td>
<td><input type="tel" id="phno" name="phno" placeholder="Phone Number"
required /></td>
</tr>
<tr>
<td>Email</td>
<td><input type="email" id="email" name="email" placeholder="Email" required
/></td>
</tr>
<tr>
<td>Aadhar Number</td>
<td><input type="text" id="aadhar" name="aadhar" placeholder="Aadhar Number"
required /></td>
</tr>
<tr>
<td>Pan Number</td>
<td><input type="text" id="pan" name="pan" placeholder="Pan Number" required
/></td>
</tr>
<tr>
<td>Monthly Income</td>
<td><input type="text" id="income" name="income" placeholder="Monthly
Income" required /></td>
</tr>
<tr>
<td>Loan Type</td>
<td><select name="loanType" id="loanType">
<option id="home" value="Home Loan">Home Loan</option>
<option id="personal" value="Personal Loan">Personal Loan</option>
<option id="vehicle" value="Vehicle Loan">Vehicle Loan</option>
</select></td>
</tr>
<tr>
<td>Expected Loan Amount</td>
<td><input type="number" id="expectedAmt" name="expectedAmt" required
/></td>
</tr>
<tr>
<td>Tenure In Months</td>
<td><input type="number" id="tenure" name="tenure" required /></td>
</tr>
</table>
<br>
<p><input type="submit" id="submit" name="submit" value="Avail Loan"/></p>
<div id="result"></div>
</form>
</div>
<script src="script.js" type="text/javascript"> </script>
</body>
</html>
script.js
function calculateEMI (income, expectedAmt, tenure, interestRatePerAnnum)
{
var EMI, R, N;
R=(interestRatePerAnnum/100)/12;
N=tenure;
EMI= (expectedAmt*R*(Math.pow((1+R),N))/(Math.pow((1+R),N)-1)).toFixed(2);
return Math.round(EMI);
}
function getInterestRate(loanType)
{
var intre;
if(loanType=="Home Loan")
{
intre=7;
}
else if(loanType=="Personal Loan")
{
intre=7.8;
}
else if(loanType=="Vehicle Loan")
{
intre=15;
}
return intre;
}
function checkEligibility(income,emi)
{
var tmp;
tmp=income*60/100;
if(emi<=tmp)
{
return true;
}
else
{
return false;
}
}
function availLoan()
{
var lt,ltt;
ltt=document.getElementById("loanType");//
lt=ltt.options[ltt.selectedIndex].value;//
var irpa;
irpa=parseFloat(getInterestRate(lt));
if(elig===true)
{
document.getElementById("result").innerText="You are eligible to get a loan amount as
"+expectedLoanAmount+"and emi per month is "+emival;
}
else
{
document.getElementById("result").innerText="You are not eligible";
}
return false;
}
Automatic evaluation[+]
Driver.cs
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Threading.Tasks;
6 using System.Data.SqlClient;
7 using System.Collections;
8 using System.Data;
9 using System.Configuration;
10
11 namespace TicketManagement //DO NOT change the namespace name
12 {
13 public class Program //DO NOT change the class name
14 {
15
16 static void Main(string[] args) //DO NOT change the 'Main' method signature
17 {
18 //Implement the code here
19 char choice = 'y';
20 Console.WriteLine("Enter Ticket Details: ");
21 while( choice == 'y')
22 {
23 Console.WriteLine("Enter Passenger Id:");
24 string id = Console.ReadLine();
25 Console.WriteLine("Enter Passenger Name:");
26 string name = Console.ReadLine();
27 Console.WriteLine("Enter Travel Date:");
28 string date = Console.ReadLine();
29 Console.WriteLine("Enter Distance Travelled:");
30 int dist = Convert.ToInt32(Console.ReadLine());
31 DistanceValidator dv = new DistanceValidator();
32 while ( dv.ValidateTravelDistance(dist) == "true")
33 {
34 Console.WriteLine("Given distance is invalid");
35 Console.WriteLine("Enter Distance Travelled: ");
36 dist = Convert.ToInt32(Console.ReadLine());
37 }
38 TicketDetail td = new TicketDetail(id, name, date, dist);
39 TicketBooking tb = new TicketBooking();
40 tb.CalculateCost(td);
41 tb.AddTicket(td);
42 Console.WriteLine(td.PassengerId);
43 Console.WriteLine(td.PassengerName);
44 Console.WriteLine(td.TravelDate);
45 Console.WriteLine(td.DistanceTravel);
46 Console.WriteLine($"Ticket Cost : {td.TicketCost}");
47 Console.WriteLine("Book Another Ticket (y/n): ");
48 choice =Convert.ToChar(Console.ReadLine());
49 }
50 }
51 }
52 public class DistanceValidator
53 { //DO NOT change the class name
54
55 public String ValidateTravelDistance(int distance) //DO NOT change the method signature
56 {
57 //Implement code here
58 if(distance < 0)
59 {
60 return "Given distance is invalid";
61 }
62 else
63 {
64 return "";
65 }
66 }
67 }
68 }
69
App.config
1 <!-- THIS IS FOR REFERENCE ONLY. YOU ARE NOT REQUIRED TO MAKE ANY CHANGES HERE -->
2
3 <?xml version="1.0" encoding="utf-8" ?>
4 <configuration>
5 <startup>
6 <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
7 </startup>
8 <connectionStrings>
9 <add name="SqlCon"
connectionString="server=localhost;database=TicketBookingDB;uid=XXXXX;password=XXXXXX;"/>
10 </connectionStrings>
11 </configuration>
DBHandler.cs
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Threading.Tasks;
6 using System.Data.SqlClient;
7 using System.Configuration;
8
9 namespace TicketManagement //DO NOT change the namespace name
10
11 {
12 public class DBHandler //DO NOT change the class name
13 {
14 //Implement the methods as per the description
15 public DBHandler() { }
16
17 public SqlConnection GetConnection()
18 {
19 return new SqlConnection(ConfigurationManager.ConnectionStrings["SqlCon"].ConnectionString);
20
21 }
22
23 }
24 }
25
TicketBooking.cs
1 using System;
2 using System.Collections;
3 using System.Collections.Generic;
4 using System.Data;
5 using System.Data.SqlClient;
6 using System.Linq;
7 using System.Text;
8 using System.Threading.Tasks;
9
10 namespace TicketManagement //DO NOT change the namespace name
11 {
12 public class TicketBooking //DO NOT change the class name
13 {
14 //Implement the property as per the description
15 public SqlConnection Sqlcon { get; set; }
16
17 public TicketBooking() { }
18 DBHandler d = new DBHandler();
19 public void AddTicket(TicketDetail detail)
20 {
21
22 string query = "INSERT INTO TicketBooking VALUES(@id,@name,@date,@dist,@cost)";
23 using (SqlConnection con = d.GetConnection())
24 using (SqlCommand cmd = new SqlCommand(query, con))
25 {
26 cmd.Parameters.Add("@id", SqlDbType.VarChar).Value = detail.PassengerId;
27 cmd.Parameters.Add("@name", SqlDbType.VarChar).Value = detail.PassengerName;
28 cmd.Parameters.Add("@date", SqlDbType.VarChar).Value = detail.TravelDate;
29 cmd.Parameters.Add("@dist", SqlDbType.Int).Value = detail.DistanceTravel;
30 cmd.Parameters.Add("@cost", SqlDbType.Float).Value = detail.TicketCost;
31 con.Open();
32
33 try
34 {
35 cmd.ExecuteNonQuery();
36 }
37 catch (Exception e)
38 {
39 Console.WriteLine(e.Message);
40 }
41 finally
42 {
43 con.Close();
44 }
45 }
46 }
47
48 //Implement the methods as per the description
49 public void CalculateCost(TicketDetail detail)
50 {
51 if(detail.DistanceTravel <= 100)
52 {
53 detail.TicketCost = detail.DistanceTravel * 1;
54 }
55 else if(detail.DistanceTravel >100 && detail.DistanceTravel <= 300)
56 {
57 detail.TicketCost = detail.DistanceTravel * 1.5;
58 }
59 else if (detail.DistanceTravel > 300 && detail.DistanceTravel <= 500)
60 {
61 detail.TicketCost = detail.DistanceTravel * 2.5;
62 }
63 else if (detail.DistanceTravel > 500)
64 {
65 detail.TicketCost = detail.DistanceTravel * 4.5;
66 }
67 }
68
69 }
70 }
71
TicketDetail.cs
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Threading.Tasks;
6
7 namespace TicketManagement //DO NOT change the namespace name
8{
9 public class TicketDetail //DO NOT change the class name
10 {
11 //Implement the fields and properties as per description
12
13 private string passengerId;
14 private string passengerName;
15 private string travelDate;
16 private int distanceTravel;
17 private double ticketCost;
18
19 public string PassengerId
20 {
21 get { return passengerId; }
22 set { this.passengerId = value; }
23 }
24 public string PassengerName
25 {
26 get { return passengerName; }
27 set { this.passengerName = value; }
28 }
29 public string TravelDate
30 {
31 get { return travelDate; }
32 set { this.travelDate = value; }
33 }
34 public int DistanceTravel
35 {
36 get { return distanceTravel; }
37 set { this.distanceTravel = value; }
38 }
39 public double TicketCost
40 {
41 get { return ticketCost; }
42 set { this.ticketCost = value; }
43 }
44
45
46 public TicketDetail() { }
47 public TicketDetail(string passengerId, string passengerName, string travelDate, int distanceTravel)
48 {
49 this.passengerId = passengerId;
50 this.passengerName = passengerName;
51 this.travelDate = travelDate;
52 this.distanceTravel = distanceTravel;
53
54 }
55 }
56
57 }
58
Grade
Reviewed on Friday, 7 January 2022, 7:32 PM by Automatic grade
Grade 100 / 100
Assessment report
[+]Grading and Feedback
A New You Spa
DiamondMembers.java
super(customerId,customerName,mobileNumber,memberType,emailId);
/*this.customerId = customerId;
this.customerName = customerName;
this.mobileNumber = mobileNumber;
this.memberType = memberType;
this.emailId = emailId;*/
boolean b=true;
String s1 = this.customerId.toUpperCase();
String regex="[DIAMOND]{7}[0-9]{3}";
if(s1.matches(regex)){
b=true;
else{
b=false;
return b;
}
double discount=purchaseAmount*0.45;
double updateamount=purchaseAmount-discount;
return updateamount;
GoldMembers.java
super(customerId,customerName,mobileNumber,memberType,emailId);
boolean b=true;
String s1 = this.customerId.toUpperCase();
String regex="[GOLD]{4}[0-9]{3}";
if(s1.matches(regex)){
b=true;
else{
b=false;
return b;
double discount=purchaseAmount*0.15;
double updateamount=purchaseAmount-discount;
return updateamount;
Members.java
return customerId;
this.customerId = customerId;
return customerName;
this.customerName = customerName;
}
return mobileNumber;
this.mobileNumber = mobileNumber;
return memberType;
this.memberType = memberType;
return emailId;
this.emailId = emailId;
this.customerId = customerId;
this.customerName = customerName;
this.mobileNumber = mobileNumber;
this.memberType = memberType;
this.emailId = emailId;
PlatinumMembers.java
public class PlatinumMembers extends Members {
super(customerId,customerName,mobileNumber,memberType,emailId);
/*customerId = customerId;
customerName = customerName;
mobileNumber = mobileNumber;
memberType = memberType;
emailId = emailId;
*/
boolean b=true;
String s1 = this.customerId.toUpperCase();
String regex="[PLATINUM]{8}[0-9]{3}";
if(s1.matches(regex)){
b=true;
else{
b=false;
return b;
double updateamount=purchaseAmount-discount;
return updateamount;
UserInterface.java
import java.util.Scanner;
String cid=sc.nextLine();
String cname=sc.nextLine();
long mob=sc.nextLong();
sc.nextLine();
String mem=sc.nextLine();
String email=sc.nextLine();
double amount=sc.nextDouble();
if(d.validateCusomerId()){
res= d.calculateDiscount(amount);
System.out.println("Name :"+d.getCustomerName());
System.out.println("Id :"+d.getCustomerId());
System.out.println("Email Id :"+d.getEmailId());
} else if(g.validateCusomerId()){
res= g.calculateDiscount(amount);
System.out.println("Name :"+g.getCustomerName());
System.out.println("Id :"+g.getCustomerId());
System.out.println("Email Id :"+g.getEmailId());
} else if(p.validateCusomerId()){
res= p.calculateDiscount(amount);
System.out.println("Name :"+p.getCustomerName());
System.out.println("Id :"+p.getCustomerId());
System.out.println("Email Id :"+p.getEmailId());
} else{
Batting Average
UserInterface.java
package com.ui;
import com.utility.Player;
import java.util.ArrayList;
import java.util.Scanner;
player.setScoreList(new ArrayList<>());
boolean flag=true;
while(flag)
System.out.println("3. Exit");
int choice=sc.nextInt();
switch(choice)
case 1: {
int runScored=sc.nextInt();
player.addScoreDetails(runScored);
break;
case 2: {
System.out.println(player.getAverageRunScored());
break;
case 3: {
flag=false;
break;
Player.java
package com.utility;
import java.util.List;
return scoreList;
this.scoreList = scoreList;
}
//This method should add the runScored passed as the argument into the scoreList
scoreList.add(runScored);
/* This method should return the average runs scored by the player
Average runs can be calculated based on the sum of all runScored available in the scoreList
divided by the number of elements in the scoreList.
For Example:
List contains[150,50,50]
*/
if(scoreList.isEmpty()) {
return 0.0;
int size=scoreList.size();
int totalScore=0;
totalScore+=score;
}
return (double) totalScore / (double) size;
Main.java
import java.util.*;
String a = sc.next();
if(a.length() < 3) {
return;
return;
int j = 0;
arr1[j++] = arr[i];
if(j!=0) {
System.out.print("String should not contain ");
System.out.print(arr1[i]);
return;
char b = sc.next().charAt(0);
int present = 0;
if(arr[i] == Character.toUpperCase(b)) {
arr[i] = Character.toLowerCase(b);
present = 1;
arr[i] = Character.toUpperCase(b);
present = 1;
if(present == 0) {
else {
System.out.print(arr[i]);
NumberType.java
public interface NumberType
NumberTypeUtility.java
import java.util.Scanner;
int n=sc.nextInt();
if(isOdd().checkNumberType(n))
System.out.println(n+" is odd");
else
ChequePaymentProcess
PaymentDao.java
package com.cts.paymentProcess.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.cts.paymentProcess.model.Payment;
import com.cts.paymentProcess.util.DatabaseUtil;
connection=DatabaseUtil.getConnection();
PreparedStatement statement=null;
ResultSet resultSet=null;
try {
statement=connection.prepareStatement("select * from
cheque_payments");
resultSet=statement.executeQuery();
while(resultSet.next()){
payment.setCustomerNumber(resultSet.getInt("customerNumber"));
payment.setChequeNumber(resultSet.getString("chequeNumber"));
payment.setPaymentDate(resultSet.getDate("paymentDate"));
payment.setAmount(resultSet.getInt("amount"));
paymentList.add(payment);
} catch (SQLException e) {
e.printStackTrace();
}finally{
try{
resultSet.close();
statement.close();
}catch(Exception e){
e.printStackTrace();
return paymentList;
Payment.java
package com.cts.paymentProcess.model;
import java.util.Date;
this.customerNumber = customerNumber;
return chequeNumber;
this.chequeNumber = chequeNumber;
return paymentDate;
this.paymentDate = paymentDate;
return amount;
this.amount = amount;
}
@Override
PaymentService.java
package com.cts.paymentProcess.service;
import java.util.*;
import java.util.Calendar;
import java.util.List;
import java.util.stream.Collectors;
import com.cts.paymentProcess.dao.PaymentDao;
import com.cts.paymentProcess.model.Payment;
List<Payment> list=paymentDao.getAllRecord();
list2 = list.stream().filter(x-
>x.getCustomerNumber()==customerNumber).collect(Collectors.toList());
return list2;
}
List<Payment> list=paymentDao.getAllRecord();
list2 = list.stream().filter(x->x.getPaymentDate().getYear()==(year-
1900)).sorted(Comparator.comparingInt(Payment::getAmount)).collect(Collectors.toList());
return list2;
SkeletonValidator.java
package com.cts.paymentProcess.skeletonValidator;
import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;
public SkeletonValidator(){
validateClassName("com.cts.paymentProcess.dao.PaymentDao");
validateMethodSignature("getAllRecord:java.util.List","com.cts.paymentProcess.dao.Payme
ntDao");
validateClassName("com.cts.paymentProcess.model.Payment");
validateMethodSignature("toString:java.lang.String","com.cts.paymentProcess.model.Paym
ent");
validateClassName("com.cts.paymentProcess.service.PaymentService");
validateMethodSignature("findCustomerByNumber:java.util.List,findCustomerByYear:java.ut
il.List","com.cts.paymentProcess.service.PaymentService");
validateClassName("com.cts.paymentProcess.util.DatabaseUtil");
validateMethodSignature("getConnection:java.sql.Connection","com.cts.paymentProcess.uti
l.DatabaseUtil");
try {
Class.forName(className);
iscorrect = true;
} catch (ClassNotFoundException e) {
LOG.log(Level.SEVERE,
return iscorrect;
try {
String[] methodSignature;
methodSignature = singleMethod.split(":");
methodName = methodSignature[0];
returnType = methodSignature[1];
cls = Class.forName(className);
if (methodName.equals(findMethod.getName())) {
foundMethod = true;
if
(!(findMethod.getReturnType().getName().equals(returnType))) {
errorFlag = true;
} else {
if (!foundMethod) {
errorFlag = true;
if (!errorFlag) {
} catch (Exception e) {
LOG.log(Level.SEVERE,
DatabaseUtil.java
package com.cts.paymentProcess.util;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import java.util.ResourceBundle;
private DatabaseUtil() {
//ENSURE YOU DON'T CHANGE THE BELOW CODE WHEN YOU SUBMIT
try{
props.load(fis);
try {
Class.forName(props.getProperty("DB_DRIVER_CLASS"));
} catch (ClassNotFoundException e) {
e.printStackTrace();
try {
con =
DriverManager.getConnection(props.getProperty("DB_URL"),props.getProperty("DB_USERNAME"),p
rops.getProperty("DB_PASSWORD"));
} catch (SQLException e) {
e.printStackTrace();
catch(IOException e){
e.printStackTrace();
return con;
App.java
package com.cts.paymentProcess;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Scanner;
import com.cts.paymentProcess.model.Payment;
import com.cts.paymentProcess.service.PaymentService;
import com.cts.paymentProcess.skeletonValidator.SkeletonValidator;
new SkeletonValidator();
Payment payment=null;
do{
System.out.println("Select Option:");
int choice=scanner.nextInt();
switch(choice){
int number=scanner.nextInt();
List<Payment> numberList=new
PaymentService().findCustomerByNumber(number);
if(numberList.size()==0){
System.out.format("%15s%15s%15s%15s\n","Customer Number","Cheque
Number","Payment Date","Amount");
numberList.stream()
.forEach(System.out::println);
break;
int year=scanner.nextInt();
if(yearList.size()==0){
}else{
System.out.format("%15s%15s%15s%15s\n","Customer Number","Cheque
Number","Payment Date","Amount");
yearList.stream()
.forEach(System.out::println);
break;
case 3:System.exit(0);
default:System.out.println("\nWrong Choice\n");
}while(true);
Passenger Amenity
Main.java
import java.util.Scanner;
int num,n,i,count1=0,count2=0,y;
char alpha,ch;
String n1,n2;
n=sc.nextInt();
if(n<=0){
System.exit(0);
for(i=0;i<n;i++,count1=0,count2=0){
arr1[i] =sc.next();
arr2[i]= sc.next();
num =Integer.parseInt(arr2[i].substring(1,(arr2[i].length())));
alpha= arr2[i].charAt(0);
count2++;
for(ch=65;ch<84;ch++){
if(ch==alpha){
count1++;
if(count1==0){
if(count2==0){
System.exit(0);
for(i=0;i<n;i++){
for(int j=i+1;j<n;j++){
if(arr2[i].charAt(0)==arr2[j].charAt(0)){
if((Integer.parseInt(arr2[i].substring(1,(arr2[i].length()))))<(Integer.parseInt(arr2[j].substring(1,arr2[j]
.length())))){
n1=arr1[i];
n2=arr2[i];
arr1[i]=arr1[j];
arr2[i]=arr2[j];
arr1[j]=n1;
arr2[j]=n2;
else
if(arr2[i].charAt(0)<arr2[j].charAt(0))
n1=arr1[i];
n2=arr2[i];
arr1[i]=arr1[j];
arr2[i]=arr2[j];
arr1[j]=n1;
arr2[j]=n2;
}
}
for(i=0;i<n;i++){
String a=arr1[i].toUpperCase();
String b=arr2[i];
System.out.print(a+" "+b);
System.out.println("");
ExamScheduler
AssessmentDAO.java
package com.cts.cc.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.Period;
import java.util.List;
import java.sql.*;
import com.cts.cc.model.Assessment;
import com.cts.cc.util.DatabaseUtil;
if(assessments==null || assessments.isEmpty()) {
int rowsCount = 0;
try{
for(Assessment a:assessments)
st.setString(1,a.getExamCode());
st.setString(2,a.getExamTitle());
st.setString(3,a.getExamDate().toString());
st.setString(4,a.getExamTime().toString());
st.setString(5,a.getExamDuration().toString());
st.setString(6,a.getEvalDays().toString());
int rs=st.executeUpdate();
if(rs!=-1)
rowsCount=rowsCount+1;
} catch(SQLException e){
return rowsCount;
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, code);
ResultSet rs = ps.executeQuery();
if(rs.next()) {
assessment.setExamCode(rs.getString(1));
assessment.setExamTitle(rs.getString(2));
assessment.setExamDate(LocalDate.parse(rs.getString(3)));
assessment.setExamTime(LocalTime.parse(rs.getString(4)));
assessment.setExamDuration(Duration.parse(rs.getString(5)));
assessment.setEvalDays(Period.parse(rs.getString(6)));
return assessment;
GenerateAssessmentFunction.java
package com.cts.cc.functions;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.Period;
import java.util.function.Function;
import com.cts.cc.model.Assessment;
@Override
String temp[]=t.split(",");
Assessment a = new
Assessment(temp[0],temp[1],LocalDate.parse(temp[2]),LocalTime.parse(temp[3]),Duration.parse(te
mp[4]),Period.parse(temp[5]));
return a;
Assessment.java
package com.cts.cc.model;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
Period evalDays) {
super();
this.examCode = examCode;
this.examTitle = examTitle;
this.examDate = examDate;
this.examTime = examTime;
this.examDuration = examDuration;
this.evalDays = evalDays;
public Assessment() {
return examCode;
this.examCode = examCode;
return examTitle;
this.examTitle = examTitle;
return examDate;
this.examDate = examDate;
}
return examTime;
this.examTime = examTime;
return examDuration;
this.examDuration = examDuration;
return evalDays;
this.evalDays = evalDays;
DateTimeFormatter date1=DateTimeFormatter.ofPattern("dd-MMM-y");
DateTimeFormatter date2=DateTimeFormatter.ofPattern("HH:mm");
LocalTime t=examTime.plus(examDuration);
String d=DateTimeFormatter.ofPattern("HH:mm").format(t);
LocalDate t1=examDate.plus(evalDays);
String d1=DateTimeFormatter.ofPattern("dd-MMM-y").format(t1);
System.out.println("Title: "+examTitle);
DatabaseUtil.java
package com.cts.cc.util;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
//ENSURE YOU DON'T CHANGE THE BELOW CODE WHEN YOU SUBMIT
props.load(fis);
Class.forName(props.getProperty("DB_DRIVER_CLASS"));
con =
DriverManager.getConnection(props.getProperty("DB_URL"),props.getProperty("DB_USERNAME"),p
rops.getProperty("DB_PASSWORD"));
catch(IOException e){
e.printStackTrace();
return con;
FileUtil.java
package com.cts.cc.util;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.io.*;
import java.util.*;
import com.cts.cc.functions.GenerateAssessmentFunction;
import com.cts.cc.model.Assessment;
String line="";
list=new ArrayList<Assessment>();
while((line=br.readLine())!=null)
list.add(function.apply(line));
return list;
Main.java
package com.cts.cc;
import java.util.List;
import com.cts.cc.dao.AssessmentDAO;
import com.cts.cc.model.Assessment;
import com.cts.cc.util.FileUtil;
new SkeletonValidator();
try {
dao.uploadAssessments(assessments);
assessment.printDetails();
} catch (Exception e) {
System.out.println(e);
SkeletonValidator.java
package com.cts.cc;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.Period;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.cts.cc.model.Assessment;
public SkeletonValidator() {
Period.class };
testClass(assessmentClass, assessmentParams);
testClass(assessmentDAOClass, null);
testClass(funtionalClass, null);
testClass(databaseUtilClass, null);
testClass(fileUtilClass, null);
testFields(assessmentClass, assessmentFields);
try {
constructor.equals(constructor);
} catch (ClassNotFoundException e) {
} catch (NoSuchMethodException e) {
} catch (SecurityException e) {
LOG.log(Level.SEVERE,
try {
classUnderTest.getDeclaredField(field);
} catch (ClassNotFoundException e) {
} catch (NoSuchFieldException e) {
LOG.log(Level.SEVERE,
} catch (SecurityException e) {
LOG.log(Level.SEVERE,
try {
LOG.log(Level.SEVERE, " You have changed the " + "return type in '"
+ methodName
}
LOG.info(methodName + " signature is valid.");
} catch (ClassNotFoundException e) {
} catch (NoSuchMethodException e) {
} catch (SecurityException e) {
LOG.log(Level.SEVERE,
Main.java
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
for(int i=0;i<str.length;i++)
str[i]=sc.next();
for(int i=0;i<m.length;i++)
String s[]=str[i].split(":");
m[i]=new Member(s[0],s[1],s[2]);
mList.add(m[i]);
int tot1=sc.nextInt();
for(int i=0;i<tot1;i++)
String s1=sc.next();
t1[i]=new ZEEShop(s1,mList);
t1[i].start();
//System.out.println(s1+" "+t1.getCount());
}
try {
Thread.currentThread().sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
for(ZEEShop s:t1)
System.out.println(s.getMemberCategory()+":"+s.getCount());
Member.java
return memberId;
this.memberId = memberId;
return memberName;
}
public void setMemberName(String memberName) {
this.memberName = memberName;
return category;
this.category = category;
super();
this.memberId = memberId;
this.memberName = memberName;
this.category = category;
ZEEShop.java
import java.util.List;
this.memberCategory = memberCategory;
this.memberList = memberList;
return memberCategory;
this.memberCategory = memberCategory;
return count;
this.count = count;
}
public List<Member> getMemberList() {
return memberList;
this.memberList = memberList;
synchronized(this)
for(Member m:memberList)
if(m.getCategory().equals(memberCategory))
count++;
FamilyInsurancePolicy.java
public class FamilyInsurancePolicy extends InsurancePolicies{
int count=0;
if(policyId.contains("FAMILY"));
count++;
char ch[]=policyId.toCharArray();
for(int i=6;i<9;i++)
count++;
if(count==4)
return true;
else
return false;
double amount=0;
amount=2500*months*no_of_members;
amount=5000*months*no_of_members;
else if (age>=60)
amount=10000*months*no_of_members;
return amount;
IndividualInsurancePolicy.java
int count=0;
if(policyId.contains("SINGLE"));
count++;
char ch[]=policyId.toCharArray();
for(int i=6;i<9;i++)
count++;
if(count==4)
return true;
else
return false;
}
public double calculateInsuranceAmount(int months)
double amount=0;
amount=2500*months;
amount=5000*months;
else if (age>=60)
amount=10000*months;
return amount;
InsurancePolicies.java
return clientName;
this.clientName = clientName;
return policyId;
return age;
this.age = age;
return mobileNumber;
this.mobileNumber = mobileNumber;
return emailId;
this.emailId = emailId;
super();
this.clientName = clientName;
this.policyId = policyId;
this.age = age;
this.mobileNumber = mobileNumber;
this.emailId = emailId;
SeniorCitizenPolicy.java
public class SeniorCitizenPolicy extends InsurancePolicies{
int count=0;
if(policyId.contains("SENIOR"));
count++;
char ch[]=policyId.toCharArray();
for(int i=6;i<9;i++)
count++;
if(count==4)
return true;
else
return false;
double amount=0;
amount=0;
else if (age>=60)
amount=10000*months*no_of_members;
return amount;
}
UserInterface.java
import java.util.Scanner;
String name=sc.next();
String id=sc.next();
int age=sc.nextInt();
long mnum=sc.nextLong();
String email=sc.next();
int month=sc.nextInt();
double amount=0;
if(id.contains("SINGLE"))
IndividualInsurancePolicy g=new
IndividualInsurancePolicy(name,id,age,mnum,email);
if(g.validatePolicyId())
//System.out.println(g.validatePolicyId());
amount=g.calculateInsuranceAmount(month);
System.out.println("Name :"+name);
System.out.println("Email Id :"+email);
else
else if(id.contains("FAMILY"))
FamilyInsurancePolicy g=new
FamilyInsurancePolicy(name,id,age,mnum,email);
if(g.validatePolicyId())
int num=sc.nextInt();
amount=g.calculateInsuranceAmount(month,num);
System.out.println("Name :"+name);
System.out.println("Email Id :"+email);
}
else
else if(id.contains("SENIOR"))
if(g.validatePolicyId())
int num=sc.nextInt();
amount=g.calculateInsuranceAmount(month,num);
System.out.println("Name :"+name);
System.out.println("Email Id :"+email);
else
else
}
The Next Recharge Date
Main.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
System.out.println("Recharged date");
String date=br.readLine();
String currentDate="29/10/2019";
if(Main.isValidFormat(date)&&(Main.dateCompare(date,currentDate))){
System.out.println("Validity days");
int days=Integer.parseInt(br.readLine());
if(days>0)
System.out.println(Main.futureDate(date,days));
else
else
String regex="^(3[01]|[12][0-9]|0[1-9])/(1[0-2]|0[1-9])/[0-9]{4}$";
Pattern pattern=Pattern.compile(regex);
Matcher matcher=pattern.matcher((CharSequence)date);
return matcher.matches();
Date d1=sdformat.parse(date1);
Date d2=sdformat.parse(date2);
if((d1.compareTo(d2)<0)||(d1.compareTo(d2)==0))
return true;
else
return false;
Calendar c=Calendar.getInstance();
try{
Date mydate=sdformat.parse(date);
c.setTime(mydate);
c.add(Calendar.DATE, days);
}catch(ParseException e){
e.printStackTrace();
String toDate=sdformat.format(c.getTime());
return toDate;
TravelRequestSystem
TravelRequestDao.java
package com.cts.travelrequest.dao;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.*;
import java.util.*;
//import java.util.Properties;
import com.cts.travelrequest.vo.TravelRequest;
class DB{
//ENSURE YOU DON'T CHANGE THE BELOW CODE WHEN YOU SUBMIT
try{
props.load(fis);
Class.forName(props.getProperty("DB_DRIVER_CLASS"));
// create the connection now
con =
DriverManager.getConnection(props.getProperty("DB_URL"),props.getProperty("DB_USERNAME"),p
rops.getProperty("DB_PASSWORD"));
catch(IOException e){
e.printStackTrace();
return con;
/**
* @return list
*/
try{
Connection con=DB.getConnection();
PreparedStatement ps=con.prepareStatement(query);
ps.setString(1,sourceCity);
ps.setString(2,destinationCity);
ResultSet rs=ps.executeQuery();
while(rs.next()){
String tid=rs.getString("travelReqId");
java.sql.Date date=rs.getDate("travelDate");
String apstat=rs.getString("approvalStatus");
String sour=rs.getString("sourceCity");
String des=rs.getString("destinationCity");
double cost=rs.getDouble("travelCost");
travel.add(tr);
catch(ClassNotFoundException e){
e.printStackTrace();
catch(SQLException e ){
e.printStackTrace();
/**
* @return list
*/
double amount=0;
try{
Connection con=DB.getConnection();
PreparedStatement ps1=con.prepareStatement(query);
ps1.setString(1,approvalStatus);
ResultSet rs1=ps1.executeQuery();
while(rs1.next()){
amount+=rs1.getDouble("travelCost");
catch(ClassNotFoundException e){
e.printStackTrace();
catch(SQLException e){
e.printStackTrace();
Main.java
package com.cts.travelrequest.main;
import java.sql.*;
import java.util.*;
import java.text.SimpleDateFormat;
import com.cts.travelrequest.service.TravelRequestService;
import com.cts.travelrequest.skeletonvalidator.SkeletonValidator;
import com.cts.travelrequest.vo.TravelRequest;
new SkeletonValidator();
String sourceCity=sc.next();
String destinationCity=sc.next();
String status=sc.next();
if(service.validateSourceAndDestination(sourceCity,destinationCity).equals("valid")){
if(ltr.isEmpty()){
else{
for(TravelRequest t:ltr){
String d=sd.format(t.getTravelDate());
System.out.println(t.getTravelReqId()+"\t| "+d+"\t|
"+t.getApprovalStatus()+"\t| "+t.getSourceCity()+"\t| "+t.getDestinationCity()+"\t|
"+t.getTravelCost());
else{
if(service.validateApprovalStatus(status).contentEquals("valid")){
System.out.println(service.calculateTotalTravelCost(status));
}
else{
TravelRequestService.java
package com.cts.travelrequest.service;
import java.util.List;
import com.cts.travelrequest.dao.TravelRequestDao;
import com.cts.travelrequest.vo.TravelRequest;
/**
* @return status
*/
if(approvalStatus.equalsIgnoreCase("Approved")||approvalStatus.equalsIgnoreCase("Pending")){
return "valid";
}
/**
* @return status
*/
if(!sourceCity.equalsIgnoreCase(destinationCity)){
if(sourceCity.equalsIgnoreCase("Pune")|| sourceCity.equalsIgnoreCase("Mumbai")||
sourceCity.equalsIgnoreCase("Chennai")|| sourceCity.equalsIgnoreCase("Bangalore")||
sourceCity.equalsIgnoreCase("Hydrabad")){
if(destinationCity.equalsIgnoreCase("Pune")||
destinationCity.equalsIgnoreCase("Mumbai")||destinationCity.equalsIgnoreCase("Chennai")||
destinationCity.equalsIgnoreCase("Bangalore")|| destinationCity.equalsIgnoreCase("Hydrabad")){
return "valid";
else{
return "invalid";
else{
return "invalid";
else{
return "invalid";
/**
*
* @return listOfTravelRequest
*/
if(this.validateSourceAndDestination(sourceCity,destinationCity).contentEquals("valid")){
return TravelRequestDao.getTravelDetails(sourceCity,destinationCity);
else{
return null;
/**
* @return totalCost
*/
if(this.validateApprovalStatus(approvalStatus).equals("valid")){
return TravelRequestDao.calculateTotalTravelCost(approvalStatus);
else{
return -1;
SkeletonValidator.java
package com.cts.travelrequest.skeletonvalidator;
import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author t-aarti3
* This class is used to verify if the Code Skeleton is intact and not
* */
public SkeletonValidator() {
validateClassName("com.cts.travelrequest.service.TravelRequestService");
validateClassName("com.cts.travelrequest.vo.TravelRequest");
validateMethodSignature(
"validateApprovalStatus:java.lang.String,validateSourceAndDestination:java.lang.String,getT
ravelDetails:java.util.List,calculateTotalTravelCost:double",
"com.cts.travelrequest.service.TravelRequestService");
try {
Class.forName(className);
iscorrect = true;
} catch (ClassNotFoundException e) {
LOG.log(Level.SEVERE,
return iscorrect;
try {
String[] methodSignature;
methodSignature = singleMethod.split(":");
methodName = methodSignature[0];
returnType = methodSignature[1];
cls = Class.forName(className);
if (methodName.equals(findMethod.getName())) {
foundMethod = true;
if
(!(findMethod.getReturnType().getName().equals(returnType))) {
errorFlag = true;
} else {
if (!foundMethod) {
errorFlag = true;
if (!errorFlag) {
} catch (Exception e) {
LOG.log(Level.SEVERE,
TravelRequest.java
package com.cts.travelrequest.vo;
import java.util.Date;
// member variables
public TravelRequest() {
super();
// parameterized constructor
super();
this.travelReqId = travelReqId;
this.travelDate = travelDate;
this.approvalStatus = approvalStatus;
this.sourceCity = sourceCity;
this.destinationCity = destinationCity;
this.travelCost = travelCost;
// setter, getter
/**
*/
return travelReqId;
/**
* @param travelReqId
*/
this.travelReqId = travelReqId;
/**
*/
return travelDate;
/**
* @param travelDate
*/
this.travelDate = travelDate;
}
/**
*/
return approvalStatus;
/**
* @param approvalStatus
*/
this.approvalStatus = approvalStatus;
/**
*/
return sourceCity;
/**
* @param sourceCity
*/
this.sourceCity = sourceCity;
/**
*/
return destinationCity;
}
/**
* @param destinationCity
*/
this.destinationCity = destinationCity;
/**
*/
return travelCost;
/**
* @param travelCost
*/
this.travelCost = travelCost;
}
AirVoice - Registration
Customer.java
return customerName;
this.customerName = customerName;
return contactNumber;
this.contactNumber = contactNumber;
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
return age;
this.age = age;
Main.java
import java.util.Scanner;
String name=(sc.nextLine());
long no=sc.nextLong();
sc.nextLine();
String mail=sc.nextLine();
System.out.println("Enter the Age:");
int age=sc.nextInt();
c.setCustomerName(name);
c.setContactNumber(no);
c.setEmailId(mail);
c.setAge(age);
System.out.println("Name:"+c.getCustomerName());
System.out.println("ContactNumber:"+c.getContactNumber());
System.out.println("EmailId:"+c.getEmailId());
System.out.println("Age:"+c.getAge());
Alliteration
import java.util.*;
int count=0;
char aletter=sc.next().charAt(0);
char acon=Character.toLowerCase(aletter);
sc.nextLine();
String sentence_letter=sc.nextLine();
String cons=sentence_letter.toLowerCase();
for(int i=0;i<cons.length();i++)
ch[i]=cons.charAt(i);
count++;
System.out.println(count);
if(count>3)
else if(count == 3)
System.out.println("No score");
import java.util.Scanner;
public class Main {
int n1 = 0;
int n2 = 0;
if(size<5||size>10)
return;
for(int i=0;i<size;i++)
a[i]=sc.nextInt();
for(int i=0;i<size;i++)
if(i+2<size)
x[i]=Math.abs(a[i]-a[i+2]);
if(x[i]>max)
max=x[i];
n1=a[i];
n2=a[i+2];
else
continue;
int min=0;
if(n1>n2)
min=n2;
else
min=n1;
for(int i=0;i<size;i++)
if(a[i]==min)
System.out.println(i);
break;
Advertisement.java
return advertisementId;
this.advertisementId = advertisementId;
return priority;
this.priority = priority;
return noOfDays;
this.noOfDays = noOfDays;
}
public String getClientName() {
return clientName;
this.clientName = clientName;
super();
this.advertisementId = advertisementId;
this.priority = priority;
this.noOfDays = noOfDays;
this.clientName = clientName;
ImageAdvertisement
this.inches = inches;
return inches;
}
public void setInches(int inches) {
this.inches = inches;
@Override
float baseAdvertisementCost=baseCost*inches*noOfDays;
float boosterCost=0f;
float serviceCost=0f;
if(priority.equals("high")){
boosterCost+=baseAdvertisementCost*0.1f;
serviceCost+=1000;
else if(priority.equals("medium")){
boosterCost+=baseAdvertisementCost*0.07f;
serviceCost+=700;
else if(priority.equals("low")){
serviceCost+=200;
return baseAdvertisementCost+boosterCost+serviceCost;
}
}
Main.java
import java.util.Scanner;
int id=input.nextInt();
String priority=input.next();
int noOfDays=input.nextInt();
input.nextLine();
String clientName=input.nextLine();
String type=input.next();
if(type.equals("video")){
int duration=input.nextInt();
VideoAdvertisement ad1=new
VideoAdvertisement(id,priority,noOfDays,clientName,duration);
float baseCost=(float)input.nextDouble();
else if(type.equals("image")){
int inches=input.nextInt();
ImageAdvertisement ad1=new
ImageAdvertisement(id,priority,noOfDays,clientName,inches);
float baseCost=(float)input.nextDouble();
System.out.printf("The Advertisement cost is
%.1f",ad1.calculateAdvertisementCharge(baseCost));
else if(type.equals("text")){
int characters=input.nextInt();
TextAdvertisement ad1=new
TextAdvertisement(id,priority,noOfDays,clientName,characters);
float baseCost=(float)input.nextDouble();
TextAdvertisement
return noOfCharacters;
this.noOfCharacters = noOfCharacters;
}
public TextAdvertisement(int advertisementId, String priority, int noOfDays, String
clientName,
int noOfCharacters) {
this.noOfCharacters = noOfCharacters;
@Override
float baseAdvertisementCost=baseCost*noOfCharacters*noOfDays;
float boosterCost=0f;
float serviceCost=0f;
if(priority.equals("high")){
boosterCost+=baseAdvertisementCost*0.1f;
serviceCost+=1000;
else if(priority.equals("medium")){
boosterCost+=baseAdvertisementCost*0.07f;
serviceCost+=700;
else if(priority.equals("low")){
serviceCost+=200;
return baseAdvertisementCost+boosterCost+serviceCost;
VideoAdvertisement
{
private int duration;
this.duration = duration;
return duration;
this.duration = duration;
@Override
float baseAdvertisementCost=baseCost*duration*noOfDays;
float boosterCost=0f;
float serviceCost=0f;
if(priority.equals("high")){
boosterCost+=baseAdvertisementCost*0.1f;
serviceCost+=1000;
else if(priority.equals("medium")){
boosterCost+=baseAdvertisementCost*0.07f;
serviceCost+=700;
else if(priority.equals("low")){
serviceCost+=200;
return baseAdvertisementCost+boosterCost+serviceCost;
Call Details
Call.java
this.callId=Integer.parseInt(data.substring(0,3));
this.calledNumber=Long.parseLong(data.substring(4,14));
this.duration=Float.parseFloat(data.substring(15));
return this.callId;
return this.calledNumber;
Main.java
import java.util.Scanner;
obj.parseData(data);
System.out.println("Call id:"+obj.getCallId());
System.out.println("Called number:"+obj.getCalledNumber());
System.out.println("Duration:"+obj.getDuration());
CreditCardValidator
Creditcard.java
package com.cts.entity;
super();
this.number = number;
return number;
this.number = number;
CreditCardService
package com.cts.services;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.nio.file.*;
import com.cts.entity.CreditCard;
String msg=null;
if(validateAgainstBlocklist(card, fileName))
msg="Card is blocked";
else if(validateNumber(card.getNumber()))
else
msg="valid card";
return msg;
if(card.getNumber().equalsIgnoreCase(str2) ||
card.getNumber().equalsIgnoreCase(str3))
bol=true;
}
else{
bol=false;
return bol;
boolean bol=true;
if(len!=16)
bol=true;
else{
bol=false;
return bol;
// Get the blocklisted no's from the file and return list of numbers
for(int i=0;i<dig1.length;i++)
{
li.add(dig1[i]);
return li;
SkeletonValidator.java
package com.cts.skeletonvalidator;
import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author
* This class is used to verify if the Code Skeleton is intact and not modified by participants thereby
ensuring smooth auto evaluation
*/
public SkeletonValidator() {
validateClassName("com.cts.entity.CreditCard");
validateClassName("com.cts.services.CreditCardService");
validateMethodSignature(
"validate:String,validateAgainstBlocklist:boolean,validateNumber:boolean,getBlockListNumb
ers:List","com.cts.services.CreditCardService");
}
private static final Logger LOG = Logger.getLogger("SkeletonValidator");
try {
Class.forName(className);
iscorrect = true;
} catch (ClassNotFoundException e) {
} catch (Exception e) {
LOG.log(Level.SEVERE,
return iscorrect;
try {
methodSignature = singleMethod.split(":");
methodName = methodSignature[0];
returnType = methodSignature[1];
cls = Class.forName(className);
if (methodName.equals(findMethod.getName())) {
foundMethod = true;
if
(!(findMethod.getReturnType().getSimpleName().equals(returnType))) {
errorFlag = true;
} else {
if (!foundMethod) {
errorFlag = true;
if (!errorFlag) {
} catch (Exception e) {
LOG.log(Level.SEVERE,
CreditCardValidatorMain
package com.cts;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import com.cts.entity.CreditCard;
import com.cts.services.CreditCardService;
import com.cts.skeletonvalidator.SkeletonValidator;
new SkeletonValidator();
creditCard.setNumber(cardNumber);
//Write your code here read card numnber and create CreditCard object based on
cardnumber
String validationMessage=creditCardService.validate(creditCard,
"resources/blacklist.csv");
System.out.println(validationMessage);
Eshooping
Main.java
package com.cts.eshopping.main;
import com.cts.eshopping.orderservice.CartService;
import com.cts.eshopping.skeletonvalidator.SkeletonValidator;
import com.cts.eshopping.vo.OrderLineItem;
System.out.println(cs.calculateDiscount(amt));
CartService.java
package com.cts.eshopping.orderservice;
import com.cts.eshopping.vo.OrderLineItem;
/**
*/
* Method to calculate total purchase amount for all the order line items
* @param orderLineItems
* @return totalOrderAmount
*/
double totalOrderAmount = 0;
int qt =0;
for(int i=0;i<orderLineItems.length;i++){
qt = orderLineItems[i].quantity;
cost = orderLineItems[i].itemCostPerQuantity;
totalOrderAmount += (qt*cost);
/**
* @param totalOrderAmount
* @return discount
*/
if(totalOrderAmount<1000){
discount = (totalOrderAmount*10)/100;
}
discount = (totalOrderAmount*20)/100;
else if(totalOrderAmount>=10000){
discount = (totalOrderAmount*30)/100;
/**
* Method to verify if the order line item is flagged as Bulk Order or not
* @param lineItem
* @return boolean
*/
boolean result=false;
if(lineItem.quantity>5){
result = true;
result=false;
/**
*
* @param orderLineItems
* @return
*/
int count = 0;
for(int i=0;i<orderLineItems.length;i++){
if(isBulkOrder(orderLineItems[i])){
count++;
SkeletonValidator.java
package com.cts.eshopping.skeletonvalidator;
import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author 222805
* This class is used to verify if the Code Skeleton is intact and not modified by participants thereby
ensuring smooth auto evaluation
*/
validateClassName("com.cts.eshopping.orderservice.CartService");
validateClassName("com.cts.eshopping.vo.OrderLineItem");
validateMethodSignature(
"calculateOrderTotalAmount:double,calculateDiscount:double,isBulkOrder:boolean,countOf
BulkOrderLineItems:int",
"com.cts.eshopping.orderservice.CartService");
try {
Class.forName(className);
iscorrect = true;
} catch (ClassNotFoundException e) {
} catch (Exception e) {
LOG.log(Level.SEVERE,
}
return iscorrect;
try {
String[] methodSignature;
methodSignature = singleMethod.split(":");
methodName = methodSignature[0];
returnType = methodSignature[1];
cls = Class.forName(className);
if (methodName.equals(findMethod.getName())) {
foundMethod = true;
if
(!(findMethod.getReturnType().getName().equals(returnType))) {
errorFlag = true;
if (!foundMethod) {
errorFlag = true;
if (!errorFlag) {
} catch (Exception e) {
LOG.log(Level.SEVERE,
OrderLineItem.java
package com.cts.eshopping.vo;
/**
*/
return itemId;
this.itemId = itemId;
return itemName;
this.itemName = itemName;
return itemCostPerQuantity;
this.itemCostPerQuantity = itemCostPerQuantity;
}
return quantity;
this.quantity = quantity;
this.itemId = itemId;
this.itemName = itemName;
this.itemCostPerQuantity=itemCostPerQuantity;
this.quantity = quantity;
GPA Calculation
UserInterface.java
package com.ui;
import com.utility.*;
import java.util.*;
gpa.setGradePointList(new ArrayList<Integer>());
int option=0;
double gpa1=0;
do
{
System.out.println("1. Add Grade\n2. Calculate GPA\n3. Exit");
option = Integer.valueOf(sc.nextLine());
switch(option)
gpa.addGradePoint(grade);
break;
if(gpa1 > 0)
System.out.println("GPA Scored");
System.out.println(gpa1);
else
break;
case 3 : break;
}while(option!=3);
GPACalculator.java
package com.utility;
import java.util.*;
return gradePointList;
this.gradePointList = gradePointList;
/*This method should add equivalent grade points based on the grade obtained by the student
passed as argument into gradePointList
Grade S A B C D E
Grade Point 10 9 8 7 6 5
For example if the gradeobtained is A, its equivalent grade points is 9 has to added into the
gradePointList*/
if(gradeObtained == 'S')
gradePointList.add(10);
{
gradePointList.add(9);
gradePointList.add(8);
gradePointList.add(7);
gradePointList.add(6);
else
gradePointList.add(5);
/* This method should return the GPA of all grades scored in the semester
For Example:
*/
double total=0,value=0,size=0;
size = gradePointList.size();
if(size < 1)
return 0;
Iterator i = gradePointList.iterator();
while(i.hasNext())
value = (Integer)i.next();
total += value;
gpa = total/size;
return gpa;
InsurancePremiumGenerator_v2
PropertyDetails.java
package com.cts.insurance.entity;
public PropertyDetails() {
return builtUpArea;
this.builtUpArea = builtUpArea;
return builtYear;
this.builtYear = builtYear;
return reconstructionCost;
this.reconstructionCost = reconstructionCost;
}
public Integer getHouseholdValuation() {
return householdValuation;
this.householdValuation = householdValuation;
return burglaryCoverReqd;
this.burglaryCoverReqd = burglaryCoverReqd;
return politicalUnrestCoverReqd;
this.politicalUnrestCoverReqd = politicalUnrestCoverReqd;
return sumAssured;
this.sumAssured = sumAssured;
}
public PropertyDetails(Integer builtUpArea,Integer builtYear, Integer reconstructionCost,
Integer householdValuation,
super();
this.builtUpArea = builtUpArea;
this.builtYear=builtYear;
this.reconstructionCost = reconstructionCost;
this.householdValuation = householdValuation;
this.burglaryCoverReqd = burglaryCoverReqd;
this.politicalUnrestCoverReqd = politicalUnrestCoverReqd;
Constants.java
package com.cts.insurance.misc;
CalculatePremiumService.java
package com.cts.insurance.services;
import com.cts.insurance.entity.PropertyDetails;
import com.cts.insurance.misc.Constants;
import java.time.LocalDate;
public class CalculatePremiumService {
double amountToBePaid = 0;
double additionalAmount1=0;
double additionalAmount2=0;
* calculatePremiumForPoliticalUnrestCoverage(propertyDetails, amountToBePaid)
* else return 0;
*/
if(!validatePropertyParameters(propertyDetails)) {
return 0;
amountToBePaid=calculatePremiumByPropertyAge(propertyDetails);
additionalAmount1=calculatePremiumForBurglaryCoverage(propertyDetails,
amountToBePaid);
additionalAmount2=calculatePremiumForPoliticalUnrestCoverage(propertyDetails,
amountToBePaid);
return Math.round(amountToBePaid+additionalAmount1+additionalAmount2);
}
public boolean validatePropertyParameters(PropertyDetails propertyDetails) {
/*
* conditions to be checked
*/
if(!((householdValuation==Constants.MIN_HOUSEHOLD_VALUATION) ||
(householdValuation >= 100000 && householdValuation <= 1500000))) {
return false;
return false;
return true;
//Use Constants.MIN_PREMIUM_AMOUNT
int sumAssured =
propertyDetails.getBuiltUpArea()*propertyDetails.getReconstructionCost()+propertyDetails.getHous
eholdValuation();
propertyDetails.setSumAssured(sumAssured);
double premium = 0;
if(propertyAge>15) {
premium =
Constants.MIN_PREMIUM_AMOUNT+(propertyDetails.getSumAssured()*0.35);
else if(propertyAge>=6) {
premium =
Constants.MIN_PREMIUM_AMOUNT+(propertyDetails.getSumAssured()*0.2);
else {
premium =
Constants.MIN_PREMIUM_AMOUNT+(propertyDetails.getSumAssured()*0.1);
return premium;
if(propertyDetails.getBurglaryCoverReqd().equalsIgnoreCase(Constants.YES)) {
return amount*.01;
return 0;
//Ex:-
propertyDetails.getPoliticalUnrestCoverReqd().equalsIgnoreCase(Constants.YES) to check condition
if(propertyDetails.getPoliticalUnrestCoverReqd().equalsIgnoreCase(Constants.YES)) {
return amount*.01;
}
return 0;
SkeletonValidator.java
package com.cts.insurance.skeleton;
import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author
* This class is used to verify if the Code Skeleton is intact and not modified by participants thereby
ensuring smooth auto evaluation
*/
public SkeletonValidator() {
validateClassName("com.cts.insurance.entity.PropertyDetails");
validateClassName("com.cts.insurance.misc.Constants");
validateClassName("com.cts.insurance.services.CalculatePremiumService");
validateClassName("com.cts.insurance.InsurancePremiumGeneratorApp");
validateMethodSignature(
"checkOwnerDetails:boolean,getPremiumAmount:double,validatePropertyParameters:bool
ean,calculatePremiumByPropertyAge:double,calculatePremiumForBurglaryCoverage:double,calculat
ePremiumForPoliticalUnrestCoverage:double","com.cts.insurance.services.CalculatePremiumService
");
}
private static final Logger LOG = Logger.getLogger("SkeletonValidator");
try {
Class.forName(className);
iscorrect = true;
} catch (ClassNotFoundException e) {
} catch (Exception e) {
LOG.log(Level.SEVERE,
return iscorrect;
try {
methodSignature = singleMethod.split(":");
methodName = methodSignature[0];
returnType = methodSignature[1];
cls = Class.forName(className);
if (methodName.equals(findMethod.getName())) {
foundMethod = true;
if
(!(findMethod.getReturnType().getSimpleName().equals(returnType))) {
errorFlag = true;
} else {
if (!foundMethod) {
errorFlag = true;
LOG.log(Level.SEVERE, " Unable to find the given public
method " + methodName
if (!errorFlag) {
} catch (Exception e) {
LOG.log(Level.SEVERE,
InsurancePremiumGeneratorApp.java
package com.cts.insurance;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import com.cts.insurance.entity.PropertyDetails;
import com.cts.insurance.misc.Constants;
import com.cts.insurance.services.CalculatePremiumService;
import com.cts.insurance.skeleton.SkeletonValidator;
public class InsurancePremiumGeneratorApp {
Integer builtUpArea = 0;
Integer builtYear=0;
Integer reconstructionCost = 0;
//read name
name = br.readLine();
//read mobile
mobile = br.readLine();
if(premiumService.checkOwnerDetails(name, mobile)) {
//read builtUpArea
builtUpArea = Integer.parseInt(br.readLine());
//read builtYear
builtYear = Integer.parseInt(br.readLine());
//read reconstructionCost
reconstructionCost = Integer.parseInt(br.readLine());
System.out.println(
//read response
if(response.equalsIgnoreCase("yes")) {
//read householdValuation
householdValuation = Integer.parseInt(br.readLine());
//read burglaryCoverReqd
burglaryCoverReqd = br.readLine();
System.out.println("Do you want to include Political unrest cover? Please provide
yes/no");
//read politicalUnrestCoverReqd
politicalUnrestCoverReqd = br.readLine();
if(premiumAmount==0.0) {
}else {
System.out.println("Sum Insured:
Rs."+propertyDetails.getSumAssured()+"\nInsurance Premium for the property of " + name + ": Rs."
+ premiumAmount);
Oil Stores
Main.java
import java.util.Scanner;
int pc=sc.nextInt();
System.out.println("Enter category");
char cat=sc.next().charAt(0);
System.out.println("Enter cost");
float c=sc.nextFloat();
obj.setName(n);
obj.setPack(pc);
obj.setCategory(cat);
obj.setCost(c);
float qty=sc.nextFloat();
Oil.java
import java.util.Scanner;
this.name=name;
this.pack=pack;
this.category=category;
this.cost=cost;
this.name=name;
return name;
this.pack=pack;
return pack;
this.category=category;
return category;
this.cost=cost;
return cost;
float price=((qty*1000)/pack)*cost;
return price;
}
Power Progress
import java.util.*;
int m=sc.nextInt();
if(m<=0){
System.out.println(""+m+" is an invalid");
return;
int n=sc.nextInt();
if(n<=0){
System.out.println(""+n+" is an invalid");
return;
if(m>=n){
return;
for(int i=1;i<=n;i++){
System.out.print((int)Math.pow(m,i)+" ");
Singapore Tourism
import java.util.*;
public class Main
map.put("BEACH",270);
map.put("PILGRIMAGE",350);
map.put("HERITAGE",430);
map.put("HILLS",780);
map.put("FALLS",1200);
map.put("ADVENTURES",4500);
String pname=sc.next();
String name=sc.next();
if(!map.containsKey(name.toUpperCase()))
else
int nod=sc.nextInt();
if(nod<=0)
else
if(not<=0)
else
double d=(double)map.get(name.toUpperCase());
double totalcost=d*(double)not*(double)nod;
if(totalcost>=1000)
totalcost=totalcost-((totalcost*15)/100);
}
Code RED
CasualEmployee:
return supplementaryHours; }
this.supplementaryHours = supplementaryHours; }
return foodAllowance; }
this.foodAllowance = foodAllowance;
super(EmployeeId, EmployeeName,yearsOfExperience,gender,salary);
this.supplementaryHours=supplementaryHours;
this.foodAllowance=foodAllowance;
double incsalary=total+(total*incrementPercentage/100);
return incsalary;
} }
Employee:
return EmployeeId; }
this.EmployeeId = employeeId; }
return EmployeeName;
this.EmployeeName = employeeName;
return yearsOfExperience;
this.yearsOfExperience = yearsOfExperience;
return gender;
this.gender = gender;
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
super();
this.EmployeeId = employeeId;
this.EmployeeName = employeeName;
this.yearsOfExperience = yearsOfExperience;
this.gender = gender;
this.salary=salary;
PermanentEmployee:
return medicalAllowance;
this.medicalAllowance = medicalAllowance;
return VehicleAllowance;
VehicleAllowance = vehicleAllowance;
this.medicalAllowance=medicalAllowance;
this.VehicleAllowance=vehicleAllowance;
double incsalary=total+(total*incrementPercentage/100);
return incsalary;
TraineeEmployee:
return supplementaryTrainingHours;
this.supplementaryTrainingHours = supplementaryTrainingHours;
return scorePoints;
this.scorePoints = scorePoints;
{
super(EmployeeId, EmployeeName, yearsOfExperience, gender, salary);
this.supplementaryTrainingHours=supplementaryTrainingHours;
this.scorePoints=scorePoints;
double total=(supplementaryTrainingHours*500)+(scorePoints*50)+this.salary;
double incsalary=total+(total*incrementPercentage/100);
return incsalary;
} }
UserInterface:
import java.util.Scanner;
System.out.println("Enter Gender");
System.out.println("Enter Salary");
double salary=sc.nextDouble();
double incSalary=0;
incSalary=te.calculateIncrementedSalary(5);
incSalary = ce.calculateIncrementedSalary(12);
incSalary=pe.calculateIncrementedSalary(12);
else
} }
BookAMovieTicket:
this.ticketId=ticketId;
this.customerName=customerName;
this.mobileNumber=mobileNumber;
this.emailId=emailId;
this.movieName=movieName;
return ticketId;
return emailId;
return movieName;
return mobileNumber;
this.ticketId=ticketId;
this.customerName=customerName;
this.mobileNumber=mobileNumber;
this.emailId=emailId;
this.movieName=movieName;
GoldTicket:
int count=0;
if(ticketId.contains("GOLD"));
count++;
char[] cha=ticketId.toCharArray();
for(int i=4;i<7;i++){
if(cha[i]>='1'&& cha[i]<='9')
count++;
if(count==4)
return true;
else
return false;
double amount;
if(ACFacility.equals("yes")){
amount=500*numberOfTickets;
else{
amount=350*numberOfTickets;
return amount;
}
PlatinumTicket:
int count=0;
if(ticketId.contains("PLATINUM"));
count++;
char[] cha=ticketId.toCharArray();
for(int i=8;i<11;i++){
if(cha[i]>='1'&& cha[i]<='9')
count++;
if(count==4)
return true;
else
return false;
double amount;
if(ACFacility.equals("yes")){
amount=750*numberOfTickets;
}
else{
amount=600*numberOfTickets;
return amount;
SilverTicket:
int count=0;
if(ticketId.contains("SILVER"));
count++;
char[] cha=ticketId.toCharArray();
for(int i=6;i<9;i++){
if(cha[i]>='1'&& cha[i]<='9')
count++;
if(count==4)
return true;
else
return false;
double amount;
if(ACFacility.equals("yes")){
amount=250*numberOfTickets;
else{
amount=100*numberOfTickets;
return amount;
UserInterface:
import java.util.*;
String tid=sc.next();
String cnm=sc.next();
long mno=sc.nextLong();
String email=sc.next();
System.out.println("Enter Movie Name");
String mnm=sc.next();
int tno=sc.nextInt();
if(tid.contains("PLATINUM")){
boolean b1=PT.validateTicketId();
if(b1==true){
else if(b1==false){
System.exit(0);
else if(tid.contains("GOLD")){
boolean b2=GT.validateTicketId();
if(b2==true){
else if (b2==false){
System.out.println("Provide valid Ticket Id");
System.exit(0);
else if(tid.contains("SILVER")){
boolean b3=ST.validateTicketId();
if(b3==true){
else if(b3==false){
System.exit(0);
}
TICKET RESERVATION
INVALID CARRIER-
PASSENGER.JAVA-
public Passenger() {
super();
// TODO Auto-generated constructor stub
}
PASSENGER CATERGORY-
import java.util.List;
@FunctionalInterface
public interface PassengerCategorization {
abstract public List<Passenger> retrievePassenger_BySource(List<Passenger>
passengerRecord,String source);
PASSENGER UTILITY-
import java.util.List;
import java.io.*;
import java.util.*;
return list;
}
SKELETON VALIDATION-
import java.lang.reflect.Method;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Stream;
/**
* @author TJ
*
* This class is used to verify if the Code Skeleton is intact and not modified by
participants thereby ensuring smooth auto evaluation
*
*/
public class SkeletonValidator {
public SkeletonValidator() {
validateClassName("PassengerCategorization");
validateClassName("Passenger");
validateClassName("InvalidCarrierException");
validateClassName("PassengerUtility");
validateMethodSignature(
"retrievePassenger_BySource:java.util.List",
"PassengerCategorization");
validateMethodSignature(
"fetchPassenger:java.util.List",
"PassengerUtility");
validateMethodSignature(
"isValidCarrierName:boolean",
"PassengerUtility");
validateMethodSignature(
"searchPassengerRecord:PassengerCategorization",
"UserInterface");
}
} catch (ClassNotFoundException e) {
LOG.log(Level.SEVERE, "You have changed either the " + "class
name/package. Use the correct package "
+ "and class name as provided in the skeleton");
} catch (Exception e) {
LOG.log(Level.SEVERE,
"There is an error in validating the " + "Class Name.
Please manually verify that the "
+ "Class name is same as skeleton before
uploading");
}
return iscorrect;
methodName = methodSignature[0];
returnType = methodSignature[1];
cls = Class.forName(className);
Method[] methods = cls.getMethods();
for (Method findMethod : methods) {
if (methodName.equals(findMethod.getName())) {
foundMethod = true;
if (!
(findMethod.getReturnType().getName().equals(returnType))) {
errorFlag = true;
LOG.log(Level.SEVERE, " You have changed
the " + "return type in '" + methodName
+ "' method. Please stick to
the " + "skeleton provided");
} else {
LOG.info("Method signature of " +
methodName + " is valid");
}
}
}
if (!foundMethod) {
errorFlag = true;
LOG.log(Level.SEVERE, " Unable to find the given
public method " + methodName
+ ". Do not change the " + "given public
method name. " + "Verify it with the skeleton");
}
}
if (!errorFlag) {
LOG.info("Method signature is valid");
}
} catch (Exception e) {
LOG.log(Level.SEVERE,
" There is an error in validating the " + "method
structure. Please manually verify that the "
+ "Method signature is same as the
skeleton before uploading");
}
}
USER INTERFACE-
import java.util.*;
import java.io.*;
if((pass.getSource().toLowerCase()).equals(source.toLowerCase())){
result.add(pass);
}
}
return result;
};
}
PassengerCategorization pc = searchPassengerRecord();
//FILL THE CODE HERE
System.out.println("Invalid Carrier Records are:");
PassengerUtility pu = new PassengerUtility();
List<Passenger> list = null;
try{
list = pu.fetchPassenger(new String("PassengerRecord.txt"));
}
catch(FileNotFoundException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}
System.out.println("Enter the source to search");
Scanner sc = new Scanner(System.in);
String inp = sc.next();
INVALID LAPTOP-
package com.cts.zeelaptopagency.exception;
public class InvalidLaptopIdException extends Exception{
public InvalidLaptopIdException() {
MAIN.JAVA-
package com.cts.zeelaptopagency.main;
import com.cts.zeelaptopagency.service.LaptopService;
import java.util.*;
import com.cts.zeelaptopagency.skeletonvalidator.SkeletonValidator;
import java.io.*;
import com.cts.zeelaptopagency.vo.Laptop;
import com.cts.zeelaptopagency.exception.*;
}
}
LAPTOP SERVICE.JAVA-
package com.cts.zeelaptopagency.service;
import com.cts.zeelaptopagency.vo.Laptop;
import java.io.File;
import java.io.*;
import java.util.List;
import java.util.*;
import com.cts.zeelaptopagency.exception.InvalidLaptopIdException;
import com.cts.zeelaptopagency.vo.Laptop;
/**
* Method to access file
*
* @return File
*/
public File accessFile()
{
/**
* Method to validate LaptopId and, for invalid laptopId throw
InvalidLaptopIdException with laptopId as argument
*
* @param laptopid
* @return status
*/
if(laptopId.toUpperCase().startsWith("ZEE"))
{
}else{
throw new InvalidLaptopIdException(laptopId);
}
return true;
//TODO change this return value
}
/**
* Method to read file ,Do necessary operations , writes validated data to
List and prints invalid laptopID in its catch block
*
* @param file
* @return List
*/
while((c=file1.read())!=-1)
{
s1+=(char)c;
}
}catch(FileNotFoundException e)
{
e.printStackTrace();
}catch(IOException e)
{
e.printStackTrace();
}
String[] arr=s1.split("\n");
String[] laptopids=new String[4];
Laptop l;
for(String s:arr)
{
l=new Laptop();
laptopids=s.split(",");
l.setLaptopId(laptopids[0]);
l.setCustomerName(laptopids[1]);
l.setBasicCost(Double.parseDouble((laptopids[2])));
l.setNoOfDays(Integer.parseInt(laptopids[3]));
this.calculateFinalAmount(l);
l.setTotalAmount(l.getBasicCost()*l.getNoOfDays());
lap.add(l);
/**
* Method to find and set totalAmount based on basicCost and noOfdays
*
*
*
*/
{
//Type code here to calculate totalAmount based on no of days and basic
cost
double d=l.getBasicCost()*l.getNoOfDays();
l.setTotalAmount(d);
}
SKELETON VALIDATOR-
package com.cts.zeelaptopagency.skeletonvalidator;
import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;
public SkeletonValidator() {
validateClassName("com.cts.zeelaptopagency.service.LaptopService");
validateClassName("com.cts.zeelaptopagency.vo.Laptop");
validateMethodSignature(
"accessFile:java.io.File,validate:boolean,readData:java.util.List",
"com.cts.zeelaptopagency.service.LaptopService");
} catch (ClassNotFoundException e) {
LOG.log(Level.SEVERE, "You have changed either the " +
"class name/package. Use the correct package "
+ "and class name as provided in the
skeleton");
} catch (Exception e) {
LOG.log(Level.SEVERE,
"There is an error in validating the " + "Class
Name. Please manually verify that the "
+ "Class name is same as skeleton
before uploading");
}
return iscorrect;
}
methodName = methodSignature[0];
returnType = methodSignature[1];
cls = Class.forName(className);
Method[] methods = cls.getMethods();
for (Method findMethod : methods) {
if (methodName.equals(findMethod.getName())) {
foundMethod = true;
if (!
(findMethod.getReturnType().getName().equals(returnType))) {
errorFlag = true;
LOG.log(Level.SEVERE, " You have
changed the " + "return type in '" + methodName
+ "' method. Please
stick to the " + "skeleton provided");
} else {
LOG.info("Method signature of " +
methodName + " is valid");
}
}
}
if (!foundMethod) {
errorFlag = true;
LOG.log(Level.SEVERE, " Unable to find the
given public method " + methodName
+ ". Do not change the " + "given
public method name. " + "Verify it with the skeleton");
}
}
if (!errorFlag) {
LOG.info("Method signature is valid");
}
} catch (Exception e) {
LOG.log(Level.SEVERE,
" There is an error in validating the " +
"method structure. Please manually verify that the "
+ "Method signature is same as the
skeleton before uploading");
}
}
}
LAPTOP.JAVA-
package com.cts.zeelaptopagency.vo;
/**
* Value Object - Laptop
*
*/
public Laptop()
{
}
public String toString()
{
return "Laptop [laptopId="+this.getLaptopId()+",
customerName="+this.getCustomerName()+", basicCost="+this.getBasicCost()+",
noOfDays="+this.getNoOfDays()+", totalAmount="+this.getTotalAmount()+"]";
}
public String getLaptopId() {
return laptopId;
}
public void setLaptopId(String laptopId) {
this.laptopId = laptopId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public double getBasicCost() {
return basicCost;
}
public void setBasicCost(double basicCost) {
this.basicCost = basicCost;
}
public int getNoOfDays() {
return noOfDays;
}
public void setNoOfDays(int noOfDays) {
this.noOfDays = noOfDays;
}
public double getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(double totalAmount) {
this.totalAmount = totalAmount;
}
LAPTOP DETAILS-
Laptop Details:
ZEE01,Jack,2000.50,4
ZEE02,Dev,4000.00,3
EEZ03,John,4500.00,5
ZAE04,Milan,3500.00,4
ZEE05,Surya,2500.50,7
ZEE06,Milan,5000.00,6
USER INTERFACE-
package com.ui;
import java.util.Scanner;
import com.utility.ThemeParkBO;
switch(choice){
case 1:
System.out.println("Enter the day");
String day = sc.next();
System.out.println("Enter the customer count");
int cc = sc.nextInt();
park.addBookingDetails(cc);
break;
case 2:
double res = park.findAverageCustomerBooked();
if(res==0){
System.out.println("No records found");
//break;
}
else{
System.out.println(res);
//break;
}
break;
case 3:
System.out.println("Thank you for using the application");
flag = false;
break;
}
}
}
}
THEMEPARKBO.JAVA-
package com.utility;
import com.ui.UserInterface;
import java.util.*;
import java.util.List;
// This Method should add the customerCount passed as argument into the
// bookingList
/*
* This method should return the average customer booked based on the
* customerCount values available in the bookingList.
*/
if(counter==0) return 0;
avg = count/counter;
return avg;
}
}
PASSENGER
PASSENGER UTILITY-
import java.util.List;
import java.io.*;
import java.util.*;
return list;
}
PASSENGER CATEGORIZATION-
PASSENGER SKELETION-
import java.lang.reflect.Method;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Stream;
/**
* @author TJ
*
* This class is used to verify if the Code Skeleton is intact and not modified by
participants thereby ensuring smooth auto evaluation
*
*/
public class SkeletonValidator {
public SkeletonValidator() {
validateClassName("PassengerCategorization");
validateClassName("Passenger");
validateClassName("InvalidCarrierException");
validateClassName("PassengerUtility");
validateMethodSignature(
"retrievePassenger_BySource:java.util.List",
"PassengerCategorization");
validateMethodSignature(
"fetchPassenger:java.util.List",
"PassengerUtility");
validateMethodSignature(
"isValidCarrierName:boolean",
"PassengerUtility");
validateMethodSignature(
"searchPassengerRecord:PassengerCategorization",
"UserInterface");
}
} catch (ClassNotFoundException e) {
LOG.log(Level.SEVERE, "You have changed either the " + "class
name/package. Use the correct package "
+ "and class name as provided in the skeleton");
} catch (Exception e) {
LOG.log(Level.SEVERE,
"There is an error in validating the " + "Class Name.
Please manually verify that the "
+ "Class name is same as skeleton before
uploading");
}
return iscorrect;
methodName = methodSignature[0];
returnType = methodSignature[1];
cls = Class.forName(className);
Method[] methods = cls.getMethods();
for (Method findMethod : methods) {
if (methodName.equals(findMethod.getName())) {
foundMethod = true;
if (!
(findMethod.getReturnType().getName().equals(returnType))) {
errorFlag = true;
LOG.log(Level.SEVERE, " You have changed
the " + "return type in '" + methodName
+ "' method. Please stick to
the " + "skeleton provided");
} else {
LOG.info("Method signature of " +
methodName + " is valid");
}
}
}
if (!foundMethod) {
errorFlag = true;
LOG.log(Level.SEVERE, " Unable to find the given
public method " + methodName
+ ". Do not change the " + "given public
method name. " + "Verify it with the skeleton");
}
}
if (!errorFlag) {
LOG.info("Method signature is valid");
}
} catch (Exception e) {
LOG.log(Level.SEVERE,
" There is an error in validating the " + "method
structure. Please manually verify that the "
+ "Method signature is same as the
skeleton before uploading");
}
}
import java.util.*;
import java.io.*;
if((pass.getSource().toLowerCase()).equals(source.toLowerCase())){
result.add(pass);
}
}
return result;
};
}
PassengerCategorization pc = searchPassengerRecord();
//FILL THE CODE HERE
System.out.println("Invalid Carrier Records are:");
PassengerUtility pu = new PassengerUtility();
List<Passenger> list = null;
try{
list = pu.fetchPassenger(new String("PassengerRecord.txt"));
}
catch(FileNotFoundException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}
System.out.println("Enter the source to search");
Scanner sc = new Scanner(System.in);
String inp = sc.next();
EMPLOYEE SALARY
EMPLOYEE-
MAIN .JAVA-
1 import java.util.*;
2 public class Main {
3
4 public static void main(String[] args)
5 {
6 Scanner read=new Scanner(System.in);
7
8 //Fill the code
9 try
10 {
11 System.out.println("Enter the Employee Id");
12 int id=Integer.parseInt(read.nextLine());
13 System.out.println("Enter the Employee Name");
14 String name=read.nextLine();
15 System.out.println("Enter the salary");
16 double salary=Double.parseDouble(read.nextLine());
17 System.out.println("Enter the Number of Years in Experience");
18 int exp_year=Integer.parseInt(read.nextLine());
19 Employee e=new Employee(id,name,salary);
20 e.findIncrementPercentage(exp_year);
21
22 double incrementedSalary=e.calculateIncrementSalary();
23 System.out.printf("Incremented Salary %.2f", incrementedSalary);
24 }
25 catch(Exception e)
26 {
27 System.out.println(e);
28 }
29 }
30
31 }
HOME APPLIANCES
USER INTERFACE-
import java.util.*;
public class HomeAppliances {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Product Id");
String id = sc.nextLine();
System.out.println("Enter Product Name");
String name = sc.nextLine();
switch (name)
{
case "AirConditioner":
{
System.out.println("Enter Batch Id");
String batch = sc.next();
System.out.println("Enter Dispatch
date");
String date = sc.next();
System.out.println("Enter Warranty
Years");
int years = sc.nextInt();
System.out.println("Enter type of Air
Conditioner");
String type = sc.nextLine();
System.out.println("Enter quantity");
double capac = sc.nextDouble();
AirConditioner ob1 = new
AirConditioner(id, name, batch, date, years, type,
capac);
double price =
ob1.calculateProductPrice();
System.out.printf("Price of the Product
is %.2f ", price);
}
case "LEDTV":
{
System.out.println("Enter Batch Id");
String batch = sc.nextLine();
System.out.println("Enter Dispatch
date");
String date = sc.nextLine();
System.out.println("Enter Warranty
Years");
int years = sc.nextInt();
System.out.println(name);
System.out.println("Enter size in
inches");
int size = sc.nextInt();
System.out.println("Enter quality");
String quality = sc.nextLine();
LEDTV ob2 = new LEDTV(id, name, batch,
date, years, size, quality);
double price =
ob2.calculateProductPrice();
System.out.printf("Price of the Product
is %.2f ", price);
}
case "MicrowaveOven":
{
System.out.println("Enter Batch Id");
String batch = sc.nextLine();
System.out.println("Enter Dispatch
date");
String date = sc.nextLine();
System.out.println("Enter Warranty
Years");
int years = sc.nextInt();
System.out.println("Enter quantity");
int quantity = sc.nextInt();
System.out.println("Enter quality");
String quality = sc.nextLine();
MicrowaveOven ob3 = new
MicrowaveOven(id, name, batch, date, years,
quantity, quality);
double price =
ob3.calculateProductPrice();
System.out.printf("Price of the Product
is %.2f ", price);
}
default: {
System.out.println("Provide a valid
Product name");
}
}
}
}
MICROWAVE.JAVA
ELECTRONIC PRODUCT.JAVA-
LED TV.JAVA
CINEMA
PLATINUM TICKET-
GOLD TICKET-
SILVER TICKET-
USER INTERFACE-
import java.util.*;
public class UserInterface {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter Ticket Id");
String tid=sc.next();
System.out.println("Enter Customer Name");
String cnm=sc.next();
System.out.println("Enter Mobile Number");
long mno=sc.nextLong();
System.out.println("Enter Email id");
String email=sc.next();
System.out.println("Enter Movie Name");
String mnm=sc.next();
System.out.println("Enter number of tickets");
int tno=sc.nextInt();
System.out.println("Do you want AC or not");
String choice =sc.next();
if(tid.contains("PLATINUM")){
PlatinumTicket PT=new PlatinumTicket(tid,cnm,mno,email,mnm);
boolean b1=PT.validateTicketId();
if(b1==true){
double cost =PT.caculateTicketCost(tno, choice);
System.out.println("Ticket cost is "+ cost);
}
else if(b1==false){
System.out.println("Provide valid Ticket Id");
System.exit(0);
}
}
else if(tid.contains("GOLD")){
GoldTicket GT=new GoldTicket(tid,cnm,mno,email,mnm);
boolean b2=GT.validateTicketId();
if(b2==true){
double cost=GT.caculateTicketCost(tno, choice);
System.out.println("Ticket cost is "+cost);
}
else if (b2==false){
System.out.println("Provide valid Ticket Id");
System.exit(0);
}
}
else if(tid.contains("SILVER")){
SilverTicket ST=new SilverTicket(tid,cnm,mno,email,mnm);
boolean b3=ST.validateTicketId();
if(b3==true){
double cost=ST.caculateTicketCost(tno, choice);
System.out.println("Ticket cost is "+cost);
}
else if(b3==false){
System.out.println("Provide valid Ticket Id");
System.exit(0);
}
}
}
}
Reverse A word
helloworld:
String[] words;
if (words.length<3) {
if (a.equals(b)&& b.equals(c)) {
input1.append(words[words.length-1]);
input1 =input1.reverse();
input1.append(words[0]);
System.out.println(input1);
} else {
input1.append(words[0]);
input1.reverse();
input1.append(words[words.length-1]);
System.out.println(input1); }
}
KidsorHome
AirConditioner:
this.airConditionerType = airConditionerType;
this.capacity = capacity;
return airConditionerType;
this.airConditionerType = airConditionerType;
return capacity;
this.capacity = capacity;
double price = 0;
if(airConditionerType.equalsIgnoreCase("Residential")){
if (capacity == 2.5){
price = 32000;
price = 40000;
price = 47000;
} }
else if(airConditionerType.equalsIgnoreCase("Commercial"))
{ if (capacity == 2.5){
price = 40000;
price = 55000;
price = 67000;
} }
else if(airConditionerType.equalsIgnoreCase("Industrial")){
if (capacity == 2.5){
price = 47000;
price = 60000;
price = 70000;
} }
return price;
} }
ElectronicProducts:
this.productId = productId;
this.productName = productName;
this.batchId = batchId;
this.dispatchDate = dispatchDate;
this.warrantyYears = warrantyYears;
return productId;
this.productId = productId;
return productName;
this.productName = productName;
return batchId;
this.batchId = batchId;
return dispatchDate;
this.dispatchDate = dispatchDate;
return warrantyYears;
this.warrantyYears = warrantyYears;
} }
LEDTV:
this.quality = quality;
return size;
this.size = size;
return quality;
this.quality = quality;
double price = 0;
if(quality.equalsIgnoreCase("Low")){
} else if(quality.equalsIgnoreCase("Medium")){
} else if(quality.equalsIgnoreCase("High")){
return price;
} }
MicrowaveOven:
this.quantity = quantity;
this.quality = quality;
} public int getQuantity() {
return quantity;
this.quantity = quantity;
return quality;
this.quality = quality;
double price = 0;
if(quality.equalsIgnoreCase("Low")){
} else if(quality.equalsIgnoreCase("Medium")){
} else if(quality.equalsIgnoreCase("High")){
return price;
} }
UserInterface:
import java.util.Scanner;
double price;
String quality;
switch(productName){
case "AirConditioner":
System.out.println("Enter quantity");
price = ac.calculateProductPrice();
break;
case "LEDTV":
System.out.println("Enter quality");
quality = sc.next();
price = l.calculateProductPrice();
break;
case "MicrowaveOven":
System.out.println("Enter quantity");
quality = sc.next();
price = m.calculateProductPrice();
break;
default:
System.exit(0);
}
Slogan
Main:
import java.util.Scanner;
String slogan=sc.nextLine();
char[] ch=slogan.toCharArray();
for(int i=0;i<slogan.length();i++){
} else{
System.out.println("Invalid slogan");
return;
int sum=0;
int mul=0;
char c = str.charAt(i);
count[c]++;
if (count[chh] == 1) {
sum++;
} else {
mul++; }
} if(sum==mul){
} else{
}
1. AirVoice - Registration
Grade settings: Maximum grade: 100
Disable external file upload, paste and drop external content: Yes
Run: Yes Evaluate: Yes
Automatic grade: Yes Maximum execution time: 16 s
SmartBuy is a leading mobile shop in the town. After buying a product, the customer needs to
provide a few personal details for the invoice to be generated.
You being their software consultant have been approached to develop software to retrieve the
personal details of the customers, which will help them to generate the invoice faster.
String emailId
int age
Get the details as shown in the sample input and assign the value for its attributes using the
setters.
Display the details as shown in the sample output using the getters method.
Note:
In the Sample Input / Output provided, the highlighted text in bold corresponds to the input given
by the user and the rest of the text represents the output.
Ensure to provide the names for classes, attributes and methods as specified in the question.
Sample Input 1:
john
Enter the ContactNumber:
9874561230
32
Sample Output 1:
Name:john
ContactNumber:9874561230
EmailId:[email protected]
Age:32
Automatic evaluation[+]
Customer.java
1 public class Customer {
2 private String customerName;
3
4 private long contactNumber;
5
6 private String emailId;
7
8 private int age;
9
10 public String getCustomerName() {
11 return customerName;
12 }
13
14 public void setCustomerName(String customerName) {
15 this.customerName = customerName;
16 }
17
18 public long getContactNumber() {
19 return contactNumber;
20 }
21
22 public void setContactNumber(long contactNumber) {
23 this.contactNumber = contactNumber;
24 }
25
26 public String getEmailId() {
27 return emailId;
28 }
29
30 public void setEmailId(String emailId) {
31 this.emailId= emailId;
32 }
33
34 public int getAge() {
35 return age;
36 }
37
38 public void setAge(int age){
39 this.age = age;
40 }
41
42
43
44 }
Main.java
1 import java.util.Scanner;
2
3 public class Main {
4
5 public static void main (String[] args) {
6 Scanner sc=new Scanner(System.in);
7
8 //Fill the code
9 Customer c=new Customer();
10 System.out.println("Enter the Name:");
11 String name=(sc.nextLine());
12 System.out.println("Enter the ContactNumber:");
13 long no=sc.nextLong();
14 sc.nextLine();
15 System.out.println("Enter the EmailId:");
16 String mail=sc.nextLine();
17
18 System.out.println("Enter the Age:");
19 int age=sc.nextInt();
20 c.setCustomerName(name);
21 c.setContactNumber(no);
22 c.setEmailId(mail);
23 c.setAge(age);
24 System.out.println("Name:"+c.getCustomerName());
25 System.out.println("ContactNumber:"+c.getContactNumber());
26 System.out.println("EmailId:"+c.getEmailId());
27 System.out.println("Age:"+c.getAge());
28
29
30
31 }
32
33 }
2. Grade
Reviewed on Friday, 10 December 2021, 6:14 PM by Automatic grade
Grade 100 / 100
Assessment report
[+]Grading and Feedback
3. ZeeZee bank
Grade settings: Maximum grade: 100
Disable external file upload, paste and drop external content: Yes
Run: Yes Evaluate: Yes
Automatic grade: Yes Maximum execution time: 16 s
ZeeZee is a leading private sector bank. In the last Annual meeting, they decided to give their
customer a 24/7 banking facility. As an initiative, the bank outlined to develop a stand-alone
device that would offer deposit and withdrawal of money to the customers anytime.
You being their software consultant have been approached to develop software to implement the
functionality of deposit and withdrawal anytime.
As per this requirement, the customer should be able to deposit money into his account at any
time and the deposited amount should reflect in his account balance.
As per this requirement, the customer should be able to withdraw money from his account
anytime he wants. The amount to be withdrawn should be less than or equal to the balance in
the account. After the withdrawal, the account should reflect the balance amount
Component Specification: Account
In the Main class, Get the details as shown in the sample input.
Create an object for the Account class and invoke the deposit method to deposit the amount and
withdraw method to withdraw the amount from the account.
Note:
If the balance amount is insufficient then display the message as shown in the Sample Input /
Output.
In the Sample Input / Output provided, the highlighted text in bold corresponds to the input given
by the user and the rest of the text represents the output.
Ensure to provide the names for classes, attributes, and methods as specified in the question.
Sample Input/Output 1:
1234567890
15000
Enter the amount to be deposited:
1500
500
Sample Input/Output 2:
1234567890
15000
1500
18500
Insufficient balance
Automatic evaluation[+]
Main.java
1 import java.util.Scanner;
2 import java.text.DecimalFormat;
3
4 public class Main{
5
6 public static void main (String[] args) {
7 Scanner sc=new Scanner(System.in);
8 DecimalFormat decimalFormat=new DecimalFormat("0.00");
9 System.out.println("Enter the account number:");
10 long accountNumber= sc.nextLong();
11 System.out.println("Enter the available amount in the account:");
12 double balanceAmount= sc.nextDouble();
13 Account account=new Account(accountNumber,balanceAmount);
14 System.out.println("Enter the amount to be deposited:");
15 double depositAmount=sc.nextDouble();
16 account.deposit(depositAmount);
17 double availableBalance=account.getBalanceAmount();
18 System.out.println("Available balance is:"+decimalFormat.format(availableBalance));
19 System.out.println("Enter the amount to be withdrawn:");
20 double withdrawAmount= sc.nextDouble();
21 boolean isWithdrawn=account.withdraw(withdrawAmount);
22 availableBalance=account.getBalanceAmount();
23 if(!isWithdrawn){
24 System.out.println("Insufficient balance");
25 }
26 System.out.println("Available balance is:"+decimalFormat.format(availableBalance));
27
28 //Fill the code
29 }
30 }
Account.java
1
2 public class Account {
3 private long accountNumber;
4 private double balanceAmount;
5 public Account(long accountNumber,double balanceAmount){
6 this.accountNumber=accountNumber;
7 this.balanceAmount=balanceAmount;
8 }
9 public long getAccountNumber(){
10 return accountNumber;
11 }
12 public void setAccountNumber(long accountNumber){
13 this.accountNumber=accountNumber;
14 }
15 public double getBalanceAmount(){
16 return balanceAmount;
17 }
18 public void setBalanceAmount(double balanceAmount){
19 this.balanceAmount=balanceAmount;
20 }
21 public void deposit(double depositAmount){
22 balanceAmount+=depositAmount;
23 }
24 public boolean withdraw(double withdrawAmount){
25 if(withdrawAmount<=balanceAmount){
26 balanceAmount-=withdrawAmount;
27 return true;
28 }
29 return false;
30 }
31 }
Grade
Reviewed on Thursday, 27 May 2021, 3:28 AM by Automatic grade
Grade 100 / 100
Assessment report
[+]Grading and Feedback
3.Call Details
Grade settings: Maximum grade: 100
Disable external file upload, paste and drop external content: Yes
Run: Yes Evaluate: Yes
Automatic grade: Yes Maximum execution time: 16 s
AirCarrier is a leading mobile network provider. They maintain a record of all the calls made by
their postpaid customers.The details are stored in a particular format
[callId:calledNumber:noOfMinutes] .At the end of every month, the network provider wants to
extract the information from the file and populate it to the Call object for calculating the bill.
You being their software consultant have been approached to develop software to implement the
functionality of extracting the data from the given format.
float duration
This requirement is responsible for extracting the customer’s callId, calledNumber and duration
from the callDetails. After the extraction set the callId, calledNumber and duration to the call
object.
In the Main class, Get the details as shown in the sample input.
Create an object for the Call and invoke the parseData method to set the callId, calledNumber
and duration for each customer.
Invoke the corresponding getters to display the call details as shown in the Sample Output
Note:
In the Sample Input / Output provided, the highlighted text in bold corresponds to the input given
by the user and the rest of the text represents the output.
Ensure to provide the names for classes, attributes and methods as specified in the question.
Sample Input 1:
102:6547891230:2.15
Sample Output 1:
Call id:102
Called number:6547891230
Duration:2.15
============================================================
Automatic evaluation[+]
Main.java
1 import java.util.Scanner;
2
3 public class Main {
4
5 public static void main (String[] args) {
6 Scanner sc=new Scanner(System.in);
7 System.out.println("Enter the call details:");
8 String a=sc.nextLine();
9 Call obj=new Call();
10 obj.parseData(a);
11 System.out.println("Call id:"+obj.getCallId());
12 System.out.println("Called number:"+obj.getCalledNumber());
13 System.out.println("Duration:"+obj.getDuration());
14 //Fill the code
15
16 }
17 }
Call.java
1
2 public class Call {
3 private int callId;
4 private long calledNumber;
5 private float duration;
6 public Call(){
7 }
8 public int getCallId(){
9 return callId;
10 }
11 public long getCalledNumber(){
12 return calledNumber;
13 }
14 public float getDuration(){
15 return duration;
16 }
17 public void setCallId(int callId){
18 this.callId=callId;
19 }
20 public void setCalledNumber(long calledNumber){
21 this.calledNumber=calledNumber;
22 }
23 public void setDuration(float duration){
24 this.duration=duration;
25 }
26 public void parseData(String calld){
27 callId=Integer.parseInt(calld.split(":")[0]);
28 setCallId(callId);
29 calledNumber=Long.parseLong(calld.split(":")[1]);
30 setCalledNumber(calledNumber);
31 duration=Float.parseFloat(calld.split(":")[2]);
32 setDuration(duration);
33 }
34 }
Grade
Reviewed on Tuesday, 4 May 2021, 4:58 AM by Automatic grade
Grade 100 / 100
Assessment report
[+]Grading and Feedback
The pair is found by checking whether the product of the numbers is same as the product of the
reversed numbers. If it is same, then print "Correct pair found". If not print, "Correct pair not
found".
Note:
In the Sample Input / Output provided, the highlighted text in bold corresponds to the input given
by the user and the remaining text represents the output.
Hint: [13*62=31*26]
Sample Input 1:
13
62
Sample Output 1:
Sample Input 2:
10
56
Sample Output 2:
Automatic evaluation[+]
Main.java
1 import java.util.*;
2
3 public class Main{
4
5 public static void main (String[] args) {
6 Scanner sc=new Scanner(System.in);
7
8 int a=sc.nextInt();
9 int b=sc.nextInt();
10 if(a>99||a<10||b>99||b<10){
11 System.out.println("No");
12
13 }
14 Main obj=new Main();
15 int ra=obj.rvs(a);
16 int rb=obj.rvs(b);
17 if(a*b==ra*rb){
18 System.out.println(a+" and "+b+" are correct pair");
19 }
20 else{
21 System.out.println(a+" and "+b+" are not correct pair");
22 }
23 }
24 int rvs(int num){
25 int r,rnum=0;
26 while(num>0)
27 {
28 r=num%10;
29 rnum=rnum*10+r;
30 num/=10;
31 }
32 return(rnum);
33 }
34 }
35
36
37
38
39
40
Grade
Reviewed on Thursday, 27 May 2021, 3:38 AM by Automatic grade
Grade 100 / 100
Assessment report
TEST CASE PASSED
[+]Grading and Feedback
----------------------------------End---------------------------------------------------
Group-2
You being their software consultant have been approached by them to develop an application
which can be used for managing their business. You need to implement a java program using
thread to find out the count of members in each membership category. Membership details
should be obtained from the user in the console.
Count the number of members available in the memberList based on the membership category
to be searched and set the value to count attribute.
Create a class called Main with the main method and get the inputs like number of
members, member details, number of times Membership category needs to be
searched and Membership category to be searched from the user.
Parse the member details and set the values for all attributes in Member class
using constructor.
Invoke the ZEEShop thread class for each memberCategory and count the number of members
in that category and display the count as shown in the sample input and output.
Assumption: The memberCategory is case –sensitive and will be of only three values –
Platinum or Gold or Silver.
Note:
In the Sample Input / Output provided, the highlighted text in bold corresponds to the input given
by the user and the remaining text represents the output.
102:Sam:Gold
103:John:Silver
104:Rose:Platinum
105:Tint:Silver
Gold
Silver
Platinum
Gold
Gold:2
Silver:2
Platinum:1
Gold:2
Automatic evaluation[+]
Member.java
1
2 public class Member {
3
4 private String memberId;
5 private String memberName;
6 private String category;
7
8 public String getMemberId() {
9 return memberId;
10 }
11 public void setMemberId(String memberId) {
12 this.memberId = memberId;
13 }
14 public String getMemberName() {
15 return memberName;
16 }
17 public void setMemberName(String memberName) {
18 this.memberName = memberName;
19 }
20 public String getCategory() {
21 return category;
22 }
23 public void setCategory(String category) {
24 this.category = category;
25 }
26
27 public Member(String memberId, String memberName, String category) {
28 super();
29 this.memberId = memberId;
30 this.memberName = memberName;
31 this.category = category;
32 }
33
34
35 }
Main.java
1 import java.util.*;
2 public class Main {
3
4 public static void main(String args[]){
5 // Fill the code here
6 List<Member> memberList = new ArrayList<Member>();
7 Scanner scan = new Scanner(System.in);
8 System.out.println("Enter the no of Members");
9 int memberCount = scan.nextInt();
10 String tempIp;
11 while(memberCount>0){
12 System.out.println("Enter the member details");
13 tempIp = scan.next();
14 String tempArr[] = tempIp.split(":");
15 memberList.add(new Member(tempArr[0],tempArr[1],tempArr[2]));
16 memberCount--;
17 }
18 System.out.println("Enter the number of times Membership category needs to be searched");
19 int noOfTimes = scan.nextInt();
20 String[] tempArr = new String[noOfTimes];
21 for(int index=0;index<noOfTimes;index++){
22 System.out.println("Enter the category");
23 tempArr[index] = scan.next();
24 }
25 int countArr[] = new int [noOfTimes];
26 for(int i=0; i<noOfTimes;i++){
27 ZEEShop thread = new ZEEShop(tempArr[i],memberList);
28 thread.run();
29 /*try{
30 thread.join();
31 }catch(InterruptedException e){
32
33 }*/
34 countArr[i] = thread.getCount();
35 }
36 for(int i=0;i<noOfTimes;i++){
37 System.out.println(tempArr[i]+ ":"+countArr[i]);
38 }
39 scan.close();
40 /*List<ZEEShop> zList = new ArrayList<ZEEShop>()
41 for(int i = 0;i<count;i++){
42 ZEEShop zs = new ZEEShop(category , memList);
43 zList.add(zs);
44 }
45 for(ZEEShop z: zeelist){
46 z.start();
47 try{
48 z.join();
49 }catch(Exception e){
50 e.printStackTrace();
51 }
52 }*/
53 }
54 }
55
ZEEShop.java
1 import java.util.*;
2 public class ZEEShop extends Thread {
3 // Fill the code here
4 private String memberCategory;
5 private int count;
6 private List<Member> memberList;
7 public ZEEShop(String memberCategory, List memberList){
8 super();
9 this.memberCategory = memberCategory;
10 this.memberList = memberList;
11 }
12 public int getCount(){
13 return count;
14 }
15 public String getMemberCategory(){
16 return memberCategory;
17 }
18 public List<Member> getMemberList(){
19 return memberList;
20 }
21 public void setMemberCategory(String memberCategory){
22 this.memberCategory = memberCategory;
23 }
24 public void setMemberList(List<Member> memberList){
25 this.memberList = memberList;
26 }
27 public void setCount(int count){
28 this.count = count;
29 }
30 public void run(){
31
32 synchronized(this)
33 {
34 for(Member m : memberList){
35 if(m.getCategory().equals(memberCategory))
36 count++;
37 }
38
39 }
40 }
41 }
42
Grade
Reviewed on Friday, 7 January 2022, 7:25 PM by Automatic grade
Grade 100 / 100
Assessment report
[+]Grading and Feedback
2. Grade Calculation
Grade settings: Maximum grade: 100
Disable external file upload, paste and drop external content: Yes
Run: Yes Evaluate: Yes
Automatic grade: Yes Maximum execution time: 32 s
Grade Calculation
Rita is working as a science teacher in an International school. She is the Class Teacher of class
V and was busy in calculating the grade for each student in her class, based on his/her total
marks obtained in SA1 assessment.
Since she found it very difficult to calculate the grade, she approached you to develop an
application which can be used for completing her task faster. You need to implement a java
program using thread to calculate the grade for each student. Student details should be obtained
from the user in the console.
Calculate the grade based on total marks (sum of all marks) as shown below obtained by each
student and set the same in result attribute for respective student.
Assumption: Each student will have only five subjects and marks of each subject will be greater
than or equal to 0 and lesser than or equal to 100. Hence the maximum Total marks obtained by
each student will be 500. And the minimum Total marks obtained by each student will be 0.
Create a class called Main with the main method and get the inputs like number of
threads and Student details from the user.
Parse the student details and set the values of studName and marks attributes
in GradeCalculator thread class using constructor.
Invoke the GradeCalculator thread class to calculate the grade based on total marks and set the
same to result attribute.
Display the Student name and Grade obtained by each student as shown in the sample input
and output.
Note:
In the Sample Input / Output provided, the highlighted text in bold corresponds to the input given
by the user and the remaining text represents the output.
Jeba:100:80:90:40:55
Adam:90:80:90:50:75
Rohit:99:99:99:99:99
Jeba:B
David:E
Adam:B
Rohit:A
Automatic evaluation[+]
Main.java
1 import java.util.Scanner;
2 import java.io.BufferedReader;
3 import java.io.InputStreamReader;
4 public class Main {
5 public static void main(String[] args) throws Exception {
6 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
7 System.out.println("Enter the number of Threads");
8 int th=Integer.parseInt(br.readLine());
9 GradeCalculator obj=null;
10 String str="";
11 String[] details=new String[th];
12 for(int i=0;i<th;i++)
13 {
14 System.out.println("Enter the String");
15 str=br.readLine();
16 details[i]=str;
17 }
18 for(int i=0;i<th;i++)
19 {
20 String sp[]=details[i].split(":");
21 int k=0;
22 int arr[]=new int[sp.length];
23 for(int j=1;j<sp.length;j++)
24 arr[k++]=Integer.parseInt(sp[j]);
25 obj=new GradeCalculator(sp[0],arr);
26 obj.start();
27 try{
28 Thread.sleep(1000);
29 }
30 catch(Exception e)
31 {
32 System.out.println(e);
33 }
34 }
35 //Fill your code here
36
37 }
38
39 }
GradeCalculator.java
1
2 public class GradeCalculator extends Thread{
3 private String studName;
4 private char result;
5 private int[] marks;
6 public String getStudName()
7 {
8 return studName;
9 }
10 public void setStudName()
11 {
12 this.studName=studName;
13 }
14 public char getResult()
15 {
16 return result;
17 }
18 public void setResult(char result)
19 {
20 this.result=result;
21 }
22 public int[] getMarks()
23 {
24 return marks;
25 }
26 public void setMarks(int[] marks)
27 {
28 this.marks=marks;
29 }
30 public GradeCalculator(String studName,int[] marks)
31 {
32 this.studName=studName;
33 this.marks=marks;
34 }
35 public void run()
36 {
37 int sum=0;
38 int[] score=getMarks();
39 for(int i=0;i<score.length;i++)
40 sum=sum+score[i];
41 if((400<=sum)&&(sum<=500))
42 System.out.println(getStudName()+":"+'A');
43 if((300<=sum)&&(sum<=399))
44 System.out.println(getStudName()+":"+'B');
45 if((200<=sum)&&(sum<=299))
46 System.out.println(getStudName()+":"+'C');
47 if(sum<200)
48 System.out.println(getStudName()+":"+'E');
49 }
50 }
Grade
Reviewed on Friday, 7 January 2022, 7:24 PM by Automatic grade
Grade 100 / 100
Assessment report
[+]Grading and Feedback
You being his best friend, help him in completing his weekend assignment. You need to
implement a java program using inner class concept to display the details available in
primaryDataSet, secondaryDataSet and Query.
Create a class called TestApplication with the main method and get the inputs for primary data
set and secondary data set like theatreId, theatreName, location, noOfScreen and ticketCost,
and details of Query like queryId and queryCategory from the user.
Display the details of primary data set, secondary data set and Query as shown in the sample
input and output.
Note:
In the Sample Input / Output provided, the highlighted text in bold corresponds to the input given
by the user and the remaining text represents the output.
PNR6001
KV cinemas
Chennai
120
RNV5001
Inoxe
Bangalore
5
Enter the ticket cost
150
Q510
DML
Theatre id : PNR6001
Location : Chennai
No of Screen : 8
Theatre id : RNV5001
Location : Bangalore
No of Screen : 5
Query id : Q510
Automatic evaluation[+]
Query.java
1
2 //Write the required business logic as expected in the question description
3
4 public class Query {
5 private String queryId;
6 private String queryCategory;
7 private DataSet primaryDataSet;
8 private DataSet secondaryDataSet;
9
10 @Override
11 public String toString()
12 {
13 String g="";
14 g+=("Primary data set"+"\n");
15 g+=("Theatre id :"+primaryDataSet.getTheatreId()+"\n");
16 g+=("Theatre name :"+primaryDataSet.getTheatreName()+"\n");
17 g+=("Location :"+primaryDataSet.getLocation()+"\n");
18 g+=("No of Screen :"+primaryDataSet.getNoOfScreen()+"\n");
19 g+=("Ticket Cost :"+primaryDataSet.getTicketCost()+"\n");
20
21 g+=("Secondary data set"+"\n");
22 g+=("Theatre id :"+secondaryDataSet.getTheatreId()+"\n");
23 g+=("Theatre name :"+secondaryDataSet.getTheatreName()+"\n");
24 g+=("Location :"+secondaryDataSet.getLocation()+"\n");
25 g+=("No of Screen :"+secondaryDataSet.getNoOfScreen()+"\n");
26 g+=("Ticket Cost :"+secondaryDataSet.getTicketCost()+"\n");
27 g+=("Query id : "+queryId+"\n");
28 g+=("Query category : "+queryCategory+"\n");
29
30 return g;
31 }
32 public class DataSet{
33 private String theatreId;
34 private String theatreName;
35 private String location;
36 private int noOfScreen;
37 private double ticketCost;
38
39 public double getTicketCost()
40 {
41 return ticketCost;
42 }
43 public void setTicketCost(double a)
44 {
45 ticketCost=a;
46 }
47
48 public int getNoOfScreen()
49 {
50 return noOfScreen;
51 }
52 public void setNoOfScreen(int a)
53 {
54 noOfScreen=a;
55 }
56 public String getLocation()
57 {
58 return location;
59 }
60 public void setLocation(String a)
61 {
62 location=a;
63 }
64 public String getTheatreName ()
65 {
66 return theatreName;
67 }
68 public void setTheatreName(String a)
69 {
70 theatreName=a;
71 }
72
73 public String getTheatreId()
74 {
75 return theatreId;
76 }
77 public void setTheatreId(String a)
78 {
79 theatreId=a;
80 }
81 }
82 public void setSecondaryDataSet(DataSet pD)
83 {
84 this.secondaryDataSet=pD;
85 }
86 public DataSet getSecondaryDataSet()
87 {
88 return this.secondaryDataSet;
89 }
90 public void setPrimaryDataSet(DataSet pD)
91 {
92 this.primaryDataSet=pD;
93 }
94 public DataSet getPrimaryDataSet()
95 {
96 return this.primaryDataSet;
97 }
98 public void setQueryId (String queryId)
99 {
100 this.queryId=queryId;
101 }
102 public void setQueryCategory(String queryCategory)
103 {
104 this.queryCategory=queryCategory;
105 }
106 public String getQueryId()
107 {
108 return this.queryId;
109 }
110 public String getQueryCategory()
111 {
112 return this.queryCategory;
113 }
114
115 }
TestApplication.java
1 import java.util.*;
2 public class TestApplication {
3 //Write the required business logic as expected in the question description
4 public static void main (String[] args) {
5 Scanner sc= new Scanner (System.in);
6 Query q= new Query();
7 Query.DataSet pd= q.new DataSet();
8 Query.DataSet sd= q.new DataSet();
9 System.out.println("Enter the Details for primary data set");
10 System.out.println("Enter the theatre id");
11 pd.setTheatreId(sc.nextLine());
12 System.out.println("Enter the theatre name");
13 pd.setTheatreName(sc.nextLine());
14 System.out.println("Enter the location");
15 pd.setLocation(sc.nextLine());
16 System.out.println("Enter the no of screens");
17 pd.setNoOfScreen(sc.nextInt());
18 System.out.println("Enter the ticket cost");
19 pd.setTicketCost(sc.nextDouble());
20 System.out.println("Enter the Details for secondary data set");
21 System.out.println("Enter the theatre id");
22
23 String id2=sc.next();
24 //System.out.println(id2);
25 sd.setTheatreId(id2);
26 System.out.println("Enter the theatre name");
27 sc.nextLine();
28 sd.setTheatreName(sc.nextLine());
29 System.out.println("Enter the location");
30 String gll=sc.nextLine();
31 sd.setLocation(gll);
32 System.out.println("Enter the no of screens");
33
34 //System.out.println(gll);
35 //String pp=sc.nextLine();
36 //System.out.println(pp);
37
38 sd.setNoOfScreen(sc.nextInt());
39 System.out.println("Enter the ticket cost");
40 sd.setTicketCost(sc.nextDouble());
41 sc.nextLine();
42 System.out.println("Enter the query id");
43 q.setQueryId(sc.nextLine());
44 System.out.println("Enter the query category");
45 q.setQueryCategory(sc.nextLine());
46
47 q.setSecondaryDataSet(sd);
48 q.setPrimaryDataSet(pd);
49 System.out.println(q.toString());
50 }
51 }
Grade
Reviewed on Friday, 17 December 2021, 6:59 PM by Automatic grade
Grade 100 / 100
Assessment report
[+]Grading and Feedback
You being their software consultant have been approached by them to develop an application
which can be used for managing their business. You need to implement a java program to view
all the flight based on source and destination.
int
noOfSeats
double
flightFare
Note: The class and methods should be declared as public and all the attributes should be
declared as private.
Requirement 1: Retrieve all the flights with the given source and destination
The customer should have the facility to view flights which are from a particular source to
destination. Hence the system should fetch all the flight details for the given source and
destination from the database. Those flight details should be added to a ArrayList and return the
same.
The flight table is already created at the backend. The structure of flight table is:
Column Name Datatype
flightId int
source varchar2(30)
destination varchar2(30)
noofseats int
flightfare number(8,2)
To connect to the database you are provided with database.properties file and DB.java file. (Do
not change any values in database.properties file)
Create a class called Main with the main method and get the inputs
like source and destination from the user.
Display the details of flight such as flightId, noofseats and flightfare for all the flights returned
as ArrayList<Flight> from the
method viewFlightBySourceDestination in FlightManagementSystem class.
If no flight is available in the list, the output should be “No flights available for the given source
and destination”.
Note:
In the Sample Input / Output provided, the highlighted text in bold corresponds to the input given
by the user and the remaining text represents the output.
Malaysia
Singapore
Malaysia
Dubai
Automatic evaluation[+]
Flight.java
1
2 public class Flight {
3
4 private int flightId;
5 private String source;
6 private String destination;
7 private int noOfSeats;
8 private double flightFare;
9 public int getFlightId() {
10 return flightId;
11 }
12 public void setFlightId(int flightId) {
13 this.flightId = flightId;
14 }
15 public String getSource() {
16 return source;
17 }
18 public void setSource(String source) {
19 this.source = source;
20 }
21 public String getDestination() {
22 return destination;
23 }
24 public void setDestination(String destination) {
25 this.destination = destination;
26 }
27 public int getNoOfSeats() {
28 return noOfSeats;
29 }
30 public void setNoOfSeats(int noOfSeats) {
31 this.noOfSeats = noOfSeats;
32 }
33 public double getFlightFare() {
34 return flightFare;
35 }
36 public void setFlightFare(double flightFare) {
37 this.flightFare = flightFare;
38 }
39 public Flight(int flightId, String source, String destination,
40 int noOfSeats, double flightFare) {
41 super();
42 this.flightId = flightId;
43 this.source = source;
44 this.destination = destination;
45 this.noOfSeats = noOfSeats;
46 this.flightFare = flightFare;
47 }
48
49
50
51 }
52
FlightManagementSystem.java
1 import java.sql.Connection;
2 import java.sql.ResultSet;
3 import java.sql.SQLException;
4 import java.util.ArrayList;
5 import java.util.List;
6 import java.sql.PreparedStatement;
7 public class FlightManagementSystem {
8 public ArrayList <Flight> viewFlightBySourceDestination(String source,String destination){
9 Connection conn = null;
10 ResultSet Rs = null;
11 String sql = "select * from flight where source=? and destination=? order by flightid";
12 ArrayList<Flight> flight = new ArrayList<>();
13 try{
14 conn = DB.getConnection();
15 PreparedStatement ps = conn.prepareStatement(sql);
16
17 ps.setString(1, source);
18 ps.setString(2, destination);
19
20 Rs=ps.executeQuery();
21 while(Rs.next()){
22 Flight F = new Flight(Rs.getInt(1),source,destination,Rs.getInt(4),Rs.getInt(5));
23 flight.add(F);
24 }
25 }catch(ClassNotFoundException e){
26 e.printStackTrace();
27 }catch(SQLException e){
28 e.printStackTrace();
29 }
30
31 return flight;
32 }
33 }
Main.java
1 import java.util.Comparator;
2 import java.util.Scanner;
3 import java.util.ArrayList;
4
5
6 public class Main{
7 public static void main(String[] args){
8 Scanner sc=new Scanner(System.in);
9 // fill your code here
10 System.out.println("Enter the source");
11 String source=sc.nextLine();
12 System.out.println("Enter the destination");
13 String destination=sc.nextLine();
14 ArrayList<Flight> flight = new
FlightManagementSystem().viewFlightBySourceDestination(source,destination);
15 if(flight.isEmpty())
16 {
17 System.out.println("No flights available for the given source and destination");
18
19 }
20 else
21 {
22 System.out.println("Flightid Noofseats Flightfare");
23 for(Flight f : flight)
24 {
25 System.out.println(f.getFlightId()+" "+f.getNoOfSeats()+" "+f.getFlightFare());
26 }
27 }
28
29
30 }
31 }
DB.java
1 import java.io.FileInputStream;
2 import java.io.IOException;
3 import java.sql.Connection;
4 import java.sql.DriverManager;
5 import java.sql.SQLException;
6 import java.util.Properties;
7
8 public class DB {
9
10 private static Connection con = null;
11 private static Properties props = new Properties();
12
13
14 //ENSURE YOU DON'T CHANGE THE BELOW CODE WHEN YOU SUBMIT
15 public static Connection getConnection() throws ClassNotFoundException, SQLException {
16 try{
17
18 FileInputStream fis = null;
19 fis = new FileInputStream("database.properties");
20 props.load(fis);
21
22 // load the Driver Class
23 Class.forName(props.getProperty("DB_DRIVER_CLASS"));
24
25 // create the connection now
26 con =
DriverManager.getConnection(props.getProperty("DB_URL"),props.getProperty("DB_USERNAME"),props.getPr
operty("DB_PASSWORD"));
27 }
28 catch(IOException e){
29 e.printStackTrace();
30 }
31 return con;
32 }
33 }
34
database.properties
1 #IF NEEDED, YOU CAN MODIFY THIS PROPERTY FILE
2 #ENSURE YOU ARE NOT CHANGING THE NAME OF THE PROPERTY
3 #YOU CAN CHANGE THE VALUE OF THE PROPERTY
4 #LOAD THE DETAILS OF DRIVER CLASS, URL, USERNAME AND PASSWORD IN DB.java using this
properties file only.
5 #Do not hard code the values in DB.java.
6
7 DB_DRIVER_CLASS=com.mysql.jdbc.Driver
8 DB_URL=jdbc:mysql://localhost:3306/${sys:DB_USERNAME}
9 DB_USERNAME=${sys:DB_USERNAME}
10 DB_PASSWORD=${sys:DB_USERNAME}
11
Grade
Reviewed on Wednesday, 12 May 2021, 6:31 AM by Automatic grade
Grade 100 / 100
Assessment report
[+]Grading and Feedback
CLUB MEMBER DETAILS
ClubMember.java*
this.memberId = memberId;
return memberId;
this.memberName = memberName;
return memberName;
this.memberType = memberType;
return memberType;
return membershipFees;
this.memberId = memberId;
this.memberName = memberName;
this.memberType = memberType;
Main.java*
import java.util.Scanner;
sc.nextLine();
System.out.println("Enter Name");
clubMemberObj.calculateMembershipFees();
}
CreditCardValidator
CreditCard.java*
package com.cts.entity;
public CreditCard() {
super();
this.number = number;
return number;
this.number = number;
CreditCardService.java*
package com.cts.services;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.nio.file.*;
import com.cts.entity.CreditCard;
//check whether the card is blocklisted and card contains only 16 digits
String msg=null;
if(validateAgainstBlocklist(card, fileName))
msg="Card is blocked";
else if(validateNumber(card.getNumber()))
else
msg="valid card";
return msg;
if(card.getNumber().equalsIgnoreCase(str2) || card.getNumber().equalsIgnoreCase(str3))
{
bol=true;
else{
bol=false;
return bol;
boolean bol=true;
if(len!=16)
bol=true;
else{
bol=false;
return bol;
// Get the blocklisted no's from the file and return list of numbers
for(int i=0;i<dig1.length;i++)
li.add(dig1[i]);
}
return li;
SkeletonValidator.java*
package com.cts.skeletonvalidator;
import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;
public SkeletonValidator() {
validateClassName("com.cts.entity.CreditCard");
validateClassName("com.cts.services.CreditCardService");
validateMethodSignature(
"validate:String,validateAgainstBlocklist:boolean,validateNumber:boolean,getBlockListNumbers:List","com.c
ts.services.CreditCardService");
try {
Class.forName(className);
iscorrect = true;
} catch (ClassNotFoundException e) {
LOG.log(Level.SEVERE, "You have changed either the " + "class name/package. Use the correct package "
} catch (Exception e) {
LOG.log(Level.SEVERE, "There is an error in validating the " + "Class Name. Please manually verify that the "
return iscorrect;
try {
String[] methodSignature;
methodSignature = singleMethod.split(":");
methodName = methodSignature[0];
returnType = methodSignature[1];
cls = Class.forName(className);
if (methodName.equals(findMethod.getName())) {
foundMethod = true;
if (!(findMethod.getReturnType().getSimpleName().equals(returnType))) {
errorFlag = true;
LOG.log(Level.SEVERE, " You have changed the " + "return type in '" + methodName
+ "' method. Please stick to the " + "skeleton provided");
} else {
if (!foundMethod) {
errorFlag = true;
LOG.log(Level.SEVERE, " Unable to find the given public method " + methodName
+ ". Do not change the " + "given public method name. " +
"Verify it with the skeleton");
if (!errorFlag) {
} catch (Exception e) {
CreditCardValidatorMain.java*
package com.cts;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import com.cts.entity.CreditCard;
import com.cts.services.CreditCardService;
import com.cts.skeletonvalidator.SkeletonValidator;
new SkeletonValidator();
creditCard.setNumber(cardNumber);
//Write your code here read card numnber and create CreditCard object based on cardnumber
System.out.println(validationMessage);
}
ESHOPPING
Main.java*
package com.cts.eshopping.main;
import com.cts.eshopping.orderservice.CartService;
import com.cts.eshopping.skeletonvalidator.SkeletonValidator;
import com.cts.eshopping.vo.OrderLineItem;
System.out.println(cs.calculateDiscount(amt));
}
CartService.java*/orderService
package com.cts.eshopping.orderservice;
import com.cts.eshopping.vo.OrderLineItem;
/**
*/
/**
* Method to calculate total purchase amount for all the order line items
* @param orderLineItems
* @return totalOrderAmount
*/
double totalOrderAmount = 0;
int qt =0;
for(int i=0;i<orderLineItems.length;i++){
qt = orderLineItems[i].quantity;
cost = orderLineItems[i].itemCostPerQuantity;
totalOrderAmount += (qt*cost);
/**
* @param totalOrderAmount
* @return discount
*/
if(totalOrderAmount<1000){
discount = (totalOrderAmount*10)/100;
discount = (totalOrderAmount*20)/100;
else if(totalOrderAmount>=10000){
discount = (totalOrderAmount*30)/100;
/**
* Method to verify if the order line item is flagged as Bulk Order or not
* @param lineItem
* @return boolean
*/
boolean result=false;
if(lineItem.quantity>5){
result = true;
result=false;
}
/**
* @param orderLineItems
* @return
*/
int count = 0;
for(int i=0;i<orderLineItems.length;i++){
if(isBulkOrder(orderLineItems[i])){
count++;
SkeletonValidator.java*
package com.cts.eshopping.skeletonvalidator;
import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author 222805
* This class is used to verify if the Code Skeleton is intact and not modified by participants thereby ensuring smooth
auto evaluation
*/
public class SkeletonValidator {
public SkeletonValidator() {
validateClassName("com.cts.eshopping.orderservice.CartService");
validateClassName("com.cts.eshopping.vo.OrderLineItem");
validateMethodSignature(
"calculateOrderTotalAmount:double,calculateDiscount:double,isBulkOrder:boolean,countOfBulkOrderLineIt
ems:int",
"com.cts.eshopping.orderservice.CartService");
try {
Class.forName(className);
iscorrect = true;
} catch (ClassNotFoundException e) {
LOG.log(Level.SEVERE, "You have changed either the " + "class name/package. Use the correct package "
} catch (Exception e) {
return iscorrect;
}
protected final void validateMethodSignature(String methodWithExcptn, String className) {
try {
String[] methodSignature;
methodSignature = singleMethod.split(":");
methodName = methodSignature[0];
returnType = methodSignature[1];
cls = Class.forName(className);
if (methodName.equals(findMethod.getName())) {
foundMethod = true;
if (!(findMethod.getReturnType().getName().equals(returnType))) {
errorFlag = true;
LOG.log(Level.SEVERE, " You have changed the " + "return type in '" + methodName
+ "' method. Please stick to the " + "skeleton provided");
} else {
if (!foundMethod) {
errorFlag = true;
LOG.log(Level.SEVERE, " Unable to find the given public method " + methodName
+ ". Do not change the " + "given public method name. " + "Verify it with the skeleton");
if (!errorFlag) {
} catch (Exception e) {
OrderLineItem.java*
package com.cts.eshopping.vo;
/**
*/
return itemId;
}
public void setItemId(String itemId){
this.itemId = itemId;
return itemName;
this.itemName = itemName;
return itemCostPerQuantity;
this.itemCostPerQuantity = itemCostPerQuantity;
return quantity;
this.quantity = quantity;
this.itemId = itemId;
this.itemName = itemName;
this.itemCostPerQuantity=itemCostPerQuantity;
this.quantity = quantity;
}
Fixed Deposit Details
FDScheme.java*
import java.util.*;
class FDScheme{
super();
this.schemeNo=schemeNo;
this.depositAmt=depositAmt;
this.period=period;
calculateInterestRate();
return schemeNo;
this.schemeNo=schemeNo;
return depositAmt;
this.depositAmt=depositAmt;
return period;
return rate;
this.rate=rate;
this.rate=(float)5.5;
this.rate=(float)6.25;
this.rate=(float)7.5;
Main.java*
import java.util.Scanner;
int no=sc.nextInt();
sc.nextLine();
double amt=sc.nextDouble();
int prd=sc.nextInt();
FDScheme obj=new
FDScheme(no,amt,prd);
}
GPA CALCULATION
UserInterface.java*
package com.ui;
import com.utility.*;
import java.util.*;
gpa.setGradePointList(new ArrayList<Integer>());
int option=0;
double gpa1=0;
do
option = Integer.valueOf(sc.nextLine());
switch(option)
gpa.addGradePoint(grade);
break;
if(gpa1 > 0)
System.out.println("GPA Scored");
System.out.println(gpa1);
else
break;
case 3 : break;
}while(option!=3);
GPACalculator.java*
package com.utility;
import java.util.*;
return gradePointList;
this.gradePointList = gradePointList;
/*This method should add equivalent grade points based on the grade obtained by the student passed as
argument into gradePointList
Grade S A B C D E
Grade Point 10 9 8 7 6 5
For example if the gradeobtained is A, its equivalent grade points is 9 has to added into the
gradePointList*/
public void addGradePoint(char gradeObtained) {
if(gradeObtained == 'S')
gradePointList.add(10);
gradePointList.add(9);
gradePointList.add(8);
gradePointList.add(7);
gradePointList.add(6);
else
gradePointList.add(5);
/* This method should return the GPA of all grades scored in the semester
For Example:
double gpa=-1;
double total=0,value=0,size=0;
size = gradePointList.size();
if(size < 1)
return 0;
Iterator i = gradePointList.iterator();
while(i.hasNext())
value = (Integer)i.next();
total += value;
gpa = total/size;
return gpa;
}
HUNGER EATS
FoodProduct.java*
package com.bean;
return foodId;
this.foodId = foodId;
return foodName;
this.foodName = foodName;
return costPerUnit;
this.costPerUnit = costPerUnit;
return quantity;
this.quantity = quantity;
}
UserInterface.java*
package com.ui;
import java.util.Scanner;
import com.utility.Order;
import com.bean.FoodProduct;
int itemno;
String bank;
itemno=sc.nextInt();
for(int i=0;i<itemno;i++){
fd.setFoodId(sc.nextInt());
fd.setFoodName(sc.next());
fd.setCostPerUnit(sc.nextDouble());
fd.setQuantity(sc.nextInt());
z.addToCart(fd);
}
System.out.println("Enter the bank name to avail offer");
bank=sc.next();
z.findDiscount(bank);
Order.java*
package com.utility;
import java.util.*;
import com.bean.FoodProduct;
return discountPercentage;
this.discountPercentage = discountPercentage;
return foodList;
this.foodList = foodList;
}
//This method should set the discount percentage based on bank passed as argument
if(bankName.equals("HDFC")){
discountPercentage=15.0;
else if(bankName.equals("ICICI")){
discountPercentage=25.0;
else if(bankName.equals("CUB")){
discountPercentage=30.0;
else if(bankName.equals("SBI")){
discountPercentage=50.0;
else if(bankName.equals("OTHERS")){
discountPercentage=0.0;
//This method should add the FoodProduct Object into Food List
List<FoodProduct> f=getFoodList();
f.add(foodProductObject);
setFoodList(f);
double bill=0;
List<FoodProduct> f=getFoodList();
for(int i=0;i<f.size();i++){
//
// System.out.println(f.get(i).getCostPerUnit());
//
// System.out.println(f.get(i).getQuantity());
bill+=f.get(i).getQuantity()*f.get(i).getCostPerUnit()*1.0;
bill=bill-((bill*discountPercentage)/100);
return bill;
}
INSURANCE PREMIUM GENERATOR
PropertyDetails.java*
package com.cts.insurance.entity;
public PropertyDetails() {
return builtUpArea;
this.builtUpArea = builtUpArea;
return builtYear;
this.builtYear = builtYear;
this.reconstructionCost = reconstructionCost;
return householdValuation;
this.householdValuation = householdValuation;
return burglaryCoverReqd;
this.burglaryCoverReqd = burglaryCoverReqd;
return politicalUnrestCoverReqd;
this.politicalUnrestCoverReqd = politicalUnrestCoverReqd;
return sumAssured;
}
public void setSumAssured(Integer sumAssured) {
this.sumAssured = sumAssured;
super();
this.builtUpArea = builtUpArea;
this.builtYear=builtYear;
this.reconstructionCost = reconstructionCost;
this.householdValuation = householdValuation;
this.burglaryCoverReqd = burglaryCoverReqd;
this.politicalUnrestCoverReqd = politicalUnrestCoverReqd;
Constants.java*
package com.cts.insurance.misc;
CalculatePremiumService.java*
package com.cts.insurance.services;
import com.cts.insurance.entity.PropertyDetails;
import com.cts.insurance.misc.Constants;
import java.time.LocalDate;
double amountToBePaid = 0;
double additionalAmount1=0;
double additionalAmount2=0;
* calculatePremiumForPoliticalUnrestCoverage(propertyDetails, amountToBePaid)
* else return 0;
*/
if(!validatePropertyParameters(propertyDetails)) {
return 0;
amountToBePaid=calculatePremiumByPropertyAge(propertyDetails);
additionalAmount1=calculatePremiumForBurglaryCoverage(propertyDetails, amountToBePaid);
additionalAmount2=calculatePremiumForPoliticalUnrestCoverage(propertyDetails,
amountToBePaid);
return Math.round(amountToBePaid+additionalAmount1+additionalAmount2);
}
/*
* conditions to be checked
*/
return false;
return false;
return true;
//Use Constants.MIN_PREMIUM_AMOUNT
int sumAssured =
propertyDetails.getBuiltUpArea()*propertyDetails.getReconstructionCost()+propertyDetails.getHouseholdValuation(
);
propertyDetails.setSumAssured(sumAssured);
double premium = 0;
if(propertyAge>15) {
premium = Constants.MIN_PREMIUM_AMOUNT+(propertyDetails.getSumAssured()*0.35);
else if(propertyAge>=6) {
premium = Constants.MIN_PREMIUM_AMOUNT+(propertyDetails.getSumAssured()*0.2);
else {
premium = Constants.MIN_PREMIUM_AMOUNT+(propertyDetails.getSumAssured()*0.1);
return premium;
if(propertyDetails.getBurglaryCoverReqd().equalsIgnoreCase(Constants.YES)) {
return amount*.01;
return 0;
//Ex:-propertyDetails.getPoliticalUnrestCoverReqd().equalsIgnoreCase(Constants.YES) to check
condition
if(propertyDetails.getPoliticalUnrestCoverReqd().equalsIgnoreCase(Constants.YES)) {
return amount*.01;
return 0;
}
SkeletonValidator.java*
package com.cts.insurance.skeleton;
import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author
* This class is used to verify if the Code Skeleton is intact and not modified by participants thereby ensuring smooth
auto evaluation
*/
public SkeletonValidator() {
validateClassName("com.cts.insurance.entity.PropertyDetails");
validateClassName("com.cts.insurance.misc.Constants");
validateClassName("com.cts.insurance.services.CalculatePremiumService");
validateClassName("com.cts.insurance.InsurancePremiumGeneratorApp");
validateMethodSignature(
"checkOwnerDetails:boolean,getPremiumAmount:double,validatePropertyParameters:boolean,calculatePre
miumByPropertyAge:double,calculatePremiumForBurglaryCoverage:double,calculatePremiumForPoliticalUnrestCov
erage:double","com.cts.insurance.services.CalculatePremiumService");
try {
Class.forName(className);
iscorrect = true;
LOG.info("Class Name " + className + " is correct");
} catch (ClassNotFoundException e) {
LOG.log(Level.SEVERE, "You have changed either the " + "class name/package. Use the
correct package "+ "and class name as provided in the skeleton");
} catch (Exception e) {
LOG.log(Level.SEVERE,
"There is an error in validating the " + "Class Name. Please manually verify that the "
return iscorrect;
try {
String[] methodSignature;
methodSignature = singleMethod.split(":");
methodName = methodSignature[0];
returnType = methodSignature[1];
cls = Class.forName(className);
foundMethod = true;
if (!(findMethod.getReturnType().getSimpleName().equals(returnType))) {
errorFlag = true;
LOG.log(Level.SEVERE, " You have changed the " + "return type in '" +
methodName+ "' method. Please stick to the " + "skeleton provided");
} else {
if (!foundMethod) {
errorFlag = true;
LOG.log(Level.SEVERE, " Unable to find the given public method " + methodName
+ ". Do not change the " + "given public method name. " + "Verify it with the
skeleton");
if (!errorFlag) {
} catch (Exception e) {
}
InsurancePremiumGeneratorApp.java*
package com.cts.insurance;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import com.cts.insurance.entity.PropertyDetails;
import com.cts.insurance.misc.Constants;
import com.cts.insurance.services.CalculatePremiumService;
import com.cts.insurance.skeleton.SkeletonValidator;
Integer builtUpArea = 0;
Integer builtYear=0;
Integer reconstructionCost = 0;
//read name
name = br.readLine();
//read mobile
mobile = br.readLine();
if(premiumService.checkOwnerDetails(name, mobile)) {
//read builtUpArea
builtUpArea = Integer.parseInt(br.readLine());
//read builtYear
builtYear = Integer.parseInt(br.readLine());
//read reconstructionCost
reconstructionCost = Integer.parseInt(br.readLine());
System.out.println(
"Do you want to include valuation of HouseHold Articles? Please provide yes/no");
//read response
if(response.equalsIgnoreCase("yes")) {
//read householdValuation
householdValuation = Integer.parseInt(br.readLine());
burglaryCoverReqd = br.readLine();
System.out.println("Do you want to include Political unrest cover? Please provide yes/no");
//read politicalUnrestCoverReqd
politicalUnrestCoverReqd = br.readLine();
if(premiumAmount==0.0) {
}else {
}
NUMEROLOGY NUMBER
Main.java*
import java.util.Scanner;
int sum = 0;
return sum;
while (string.length() != 1) {
string = String.valueOf(getSum(Long.parseLong(string)));
return Integer.parseInt(string);
int oddCount = 0;
if (Character.digit(ch, 10) % 2 != 0) {
++oddCount;
}
return oddCount;
int evenCount = 0;
if (Character.digit(ch, 10) % 2 == 0) {
++evenCount;
return evenCount;
System.out.println("Sum of digits");
System.out.println(getSum(num));
System.out.println("Numerology number");
System.out.println(getNumerology(num));
System.out.println(getOddCount(num));
System.out.println(getEvenCount(num));
}
OIL STORES
Oil.java*
import java.util.Scanner;
this.name=name;
this.pack=pack;
this.category=category;
this.cost=cost;
this.name=name;
return name;
this.pack=pack;
return pack;
this.category=category;
return category;
}
this.cost=cost;
return cost;
float price=((qty*1000)/pack)*cost;
return price;
Main.java*
import java.util.Scanner;
String n=sc.next();
int pc=sc.nextInt();
System.out.println("Enter category");
char cat=sc.next().charAt(0);
System.out.println("Enter cost");
float c=sc.nextFloat();
obj.setName(n);
obj.setPack(pc);
obj.setCategory(cat);
obj.setCost(c);
float qty=sc.nextFloat();
}
PAYMENT-INHERITENCE
Bill.java*
Cheque cheque=(Cheque)payObj;
if(cheque.payAmount())
Cash cash=(Cash)payObj;
if(cash.payAmount())
Credit credit=(Credit)payObj;
if(credit.payAmount())
result="Payment done successfully via credit card. Remaining amount in your "+credit.getCardType()+" card
is "+credit.getCreditCardAmount();
return result;
}
Cash.java*
return cashAmount;
this.cashAmount = cashAmount;
Cheque.java
import java.util.*;
import java.util.GregorianCalendar;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.text.SimpleDateFormat;
this.chequeNo = chequeNo;
return chequeAmount;
this.chequeAmount = chequeAmount;
return dateOfIssue;
this.dateOfIssue = dateOfIssue;
myDate.setTime(date);
return (2020-myDate.get(Calendar.YEAR))*12+(0-myDate.get(Calendar.MONTH));
@Override
int months=findDifference(getDateOfIssue());
return (getChequeAmount()>=getDueAmount()&months<=6);
try{
catch(ParseException e)
e.printStackTrace();
Credit.java*
return creditCardNo;
this.creditCardNo = creditCardNo;
return cardType;
this.cardType = cardType;
return creditCardAmount;
super();
public Credit()
@Override
int tax=0;
boolean isDeducted=false;
switch(cardType)
tax=(int)(0.02*getDueAmount())+getDueAmount();
if(tax<=getCreditCardAmount())
setCreditCardAmount(getCreditCardAmount()-tax);
isDeducted=true;
break;
tax=(int)(0.05*getDueAmount())+getDueAmount();
if(tax<=getCreditCardAmount())
{
setCreditCardAmount(getCreditCardAmount()-tax);
isDeducted=true;
break;
tax=(int)(0.1*getDueAmount())+getDueAmount();
if(tax<=getCreditCardAmount())
setCreditCardAmount(getCreditCardAmount()-tax);
isDeducted=true;
break;
return isDeducted;
Payment.java*
return dueAmount;
this.dueAmount = dueamount;
return false;
}
Main.java*
import java.util.*;
int dueAmount=sc.nextInt();
String mode=sc.next();
switch(mode)
int cashAmount=sc.nextInt();
cash.setCashAmount(cashAmount);
cash.setDueAmount(dueAmount);
System.out.println(bill.processPayment(cash));
break;
String number=sc.next();
int chequeAmount=sc.nextInt();
String date=sc.next();
cheque.setChequeAmount(chequeAmount);
cheque.setChequeNo(number);
cheque.generateDate(date);
cheque.setDueAmount(dueAmount);
System.out.println(bill.processPayment(cheque));
break;
String cardType=sc.next();
credit.setCardType(cardType);
credit.setCreditCardNo(creditNumber);
credit.setDueAmount(dueAmount);
System.out.println(bill.processPayment(credit));
break;
default:
break;
sc.close();
}
POWER PROGRESS
Main.java*
import java.util.*;
int m=sc.nextInt();
if(m<=0){
System.out.println(""+m+" is an invalid");
return;
int n=sc.nextInt();
if(n<=0){
System.out.println(""+n+" is an invalid");
return;
if(m>=n){
return;
for(int i=1;i<=n;i++){
System.out.print((int)Math.pow(m,i)+" ");
}
PRIME NUMBERS ENDING WITH 1
Main.java*
import java.util.Scanner;
int last=0;
int flag = 0;
low = sc.nextInt();
high = sc.nextInt();
else {
int i = low;
int x = i % 10;
if (i % j != 0 && x == 1) {
flag = 1;
} else {
flag = 0;
break;
if (flag == 1 )
System.out.println(i);
i++;
}}}
SINGAPORE TOURISM
Main.java*
import java.util.*;
map.put("BEACH",270);
map.put("PILGRIMAGE",350);
map.put("HERITAGE",430);
map.put("HILLS",780);
map.put("FALLS",1200);
map.put("ADVENTURES",4500);
String pname=sc.next();
String name=sc.next();
if(!map.containsKey(name.toUpperCase()))
else
int nod=sc.nextInt();
if(nod<=0)
else
if(not<=0)
else
double d=(double)map.get(name.toUpperCase());
double totalcost=d*(double)not*(double)nod;
if(totalcost>=1000)
totalcost=totalcost-((totalcost*15)/100);
}
SUBSTITUTION CYPHER TECHNIQUE
Main.java*
import java.util.Scanner;
int shift = 7;
int f=0;
f=1;
alpha=(char)(alpha - shift);
decryptMessage=decryptMessage+alpha;
f=1;
alpha=(char)(alpha - shift);
decryptMessage=decryptMessage+alpha;
decryptMessage=decryptMessage+alpha;
}
if(decryptMessage.length() == 0 || f == 0){
System.exit(0);
System.out.println("Decrpted Text:\n"+decryptMessage);
}
ZEE ZEE BANK
Account.java*
long accountNumber;
double balanceAmount;
super();
this.accountNumber=accno;
this.balanceAmount=bal;
return accountNumber;
this.accountNumber=accno;
return balanceAmount;
this.balanceAmount=bal;
float total=(float)(balanceAmount+depositAmt);
balanceAmount=total;
float total;
if(withdrawAmt>balanceAmount){
System.out.println("Insufficient balance");
return false;
}else{
total=(float)(balanceAmount-withdrawAmt);
setBalanceAmount(total);
return true;
Main.java*
import java.util.Scanner;
ac.setAccountNumber(sc.nextLong());
ac.setBalanceAmount(sc.nextDouble());
ac.deposit(sc.nextDouble());
System.out.println();
ac.withdraw(sc.nextDouble());
}
THE NEXT RECHARGE DATE
Main.java*
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
System.out.println("Recharged date");
String date=br.readLine();
String currentDate="29/10/2019";
if(Main.isValidFormat(date)&&(Main.dateCompare(date,currentDate))){
System.out.println("Validity days");
int days=Integer.parseInt(br.readLine());
if(days>0)
System.out.println(Main.futureDate(date,days));
else
else
String regex="^(3[01]|[12][0-9]|0[1-9])/(1[0-2]|0[1-9])/[0-9]{4}$";
Pattern pattern=Pattern.compile(regex);
Matcher matcher=pattern.matcher((CharSequence)date);
return matcher.matches();
}
Date d1=sdformat.parse(date1);
Date d2=sdformat.parse(date2);
if((d1.compareTo(d2)<0)||(d1.compareTo(d2)==0))
return true;
else
return false;
Calendar c=Calendar.getInstance();
try{
Date mydate=sdformat.parse(date);
c.setTime(mydate);
c.add(Calendar.DATE, days);
}catch(ParseException e){
e.printStackTrace();
String toDate=sdformat.format(c.getTime());
return toDate;
}
A New You Spa
DiamondMembers.java*
super(customerId,customerName,mobileNumber,memberType,emailId);
/*this.customerId = customerId;
this.customerName = customerName;
this.mobileNumber = mobileNumber;
this.memberType = memberType;
this.emailId = emailId;*/
boolean b=true;
String s1 = this.customerId.toUpperCase();
String regex="[DIAMOND]{7}[0-9]{3}";
if(s1.matches(regex)){
b=true;
else{
b=false;
return b;
double updateamount=purchaseAmount-discount;
return updateamount;
GoldMembers.java*
super(customerId,customerName,mobileNumber,memberType,emailId);
boolean b=true;
String s1 = this.customerId.toUpperCase();
String regex="[GOLD]{4}[0-9]{3}";
if(s1.matches(regex)){
b=true;
else{
b=false;
return b;
double discount=purchaseAmount*0.15;
double updateamount=purchaseAmount-discount;
return updateamount;
}
Members.java*
return customerId;
this.customerId = customerId;
return customerName;
this.customerName = customerName;
return mobileNumber;
this.mobileNumber = mobileNumber;
return memberType;
return emailId;
this.emailId = emailId;
public Members(String customerId, String customerName, long mobileNumber, String memberType, String
emailId) {
this.customerId = customerId;
this.customerName = customerName;
this.mobileNumber = mobileNumber;
this.memberType = memberType;
this.emailId = emailId;
PlatinumMembers.java*
super(customerId,customerName,mobileNumber,memberType,emailId);
/*customerId = customerId;
customerName = customerName;
mobileNumber = mobileNumber;
memberType = memberType;
emailId = emailId;
*/
}
public boolean validateCusomerId(){
boolean b=true;
String s1 = this.customerId.toUpperCase();
String regex="[PLATINUM]{8}[0-9]{3}";
if(s1.matches(regex)){
b=true;
else{
b=false;
return b;
double discount=purchaseAmount*0.3;
double updateamount=purchaseAmount-discount;
return updateamount;
UserInterface.java*
import java.util.Scanner;
String cname=sc.nextLine();
long mob=sc.nextLong();
sc.nextLine();
String mem=sc.nextLine();
String email=sc.nextLine();
double amount=sc.nextDouble();
double res=0.0;
if(d.validateCusomerId()){
res= d.calculateDiscount(amount);
System.out.println("Name :"+d.getCustomerName());
System.out.println("Id :"+d.getCustomerId());
System.out.println("Email Id :"+d.getEmailId());
} else if(g.validateCusomerId()){
res= g.calculateDiscount(amount);
System.out.println("Name :"+g.getCustomerName());
System.out.println("Id :"+g.getCustomerId());
System.out.println("Email Id :"+g.getEmailId());
} else if(p.validateCusomerId()){
res= p.calculateDiscount(amount);
System.out.println("Name :"+p.getCustomerName());
System.out.println("Id :"+p.getCustomerId());
System.out.println("Email Id :"+p.getEmailId());
} else{
}
BATTING AVERAGE
UserInterface.java*
package com.ui;
import com.utility.Player;
import java.util.ArrayList;
import java.util.Scanner;
player.setScoreList(new ArrayList<>());
boolean flag=true;
while(flag)
System.out.println("3. Exit");
int choice=sc.nextInt();
switch(choice)
case 1: {
int runScored=sc.nextInt();
player.addScoreDetails(runScored);
break;
case 2: {
System.out.println(player.getAverageRunScored());
break;
}
case 3: {
flag=false;
break;
Player.java*
package com.utility;
import java.util.List;
return scoreList;
this.scoreList = scoreList;
//This method should add the runScored passed as the argument into the scoreList
scoreList.add(runScored);
/* This method should return the average runs scored by the player
Average runs can be calculated based on the sum of all runScored available in the scoreList divided by the
number of elements in the scoreList.
For Example:
List contains[150,50,50]
*/
if(scoreList.isEmpty()) {
return 0.0;
int size=scoreList.size();
int totalScore=0;
totalScore+=score;
}
Change The Cash
Main.java*
import java.util.*;
String a = sc.next();
if(a.length() < 3) {
return;
return;
int j = 0;
arr1[j++] = arr[i];
if(j!=0) {
System.out.print(arr1[i]);
return;
char b = sc.next().charAt(0);
int present = 0;
if(arr[i] == Character.toUpperCase(b)) {
arr[i] = Character.toLowerCase(b);
present = 1;
arr[i] = Character.toUpperCase(b);
present = 1;
if(present == 0) {
else {
System.out.print(arr[i]);
}
Check Number Type
NumberType.java*
NumberTypeUtility.java*
import java.util.Scanner;
int n=sc.nextInt();
if(isOdd().checkNumberType(n))
System.out.println(n+" is odd");
else
}
Cheque Payment Process
PaymentDao.java*
package com.cts.paymentProcess.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.cts.paymentProcess.model.Payment;
import com.cts.paymentProcess.util.DatabaseUtil;
connection=DatabaseUtil.getConnection();
PreparedStatement statement=null;
ResultSet resultSet=null;
try {
resultSet=statement.executeQuery();
while(resultSet.next()){
payment.setCustomerNumber(resultSet.getInt("customerNumber"));
payment.setChequeNumber(resultSet.getString("chequeNumber"));
payment.setPaymentDate(resultSet.getDate("paymentDate"));
payment.setAmount(resultSet.getInt("amount"));
paymentList.add(payment);
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
try{
resultSet.close();
statement.close();
}catch(Exception e){
e.printStackTrace();
} }
return paymentList;
Payment.java*
package com.cts.paymentProcess.model;
import java.util.Date;
return customerNumber;
}
public void setCustomerNumber(int customerNumber) {
this.customerNumber = customerNumber;
return chequeNumber;
this.chequeNumber = chequeNumber;
return paymentDate;
this.paymentDate = paymentDate;
return amount;
this.amount = amount;
@Override
}
PaymentService.java*
package com.cts.paymentProcess.service;
import java.util.*;
import java.util.Calendar;
import java.util.List;
import java.util.stream.Collectors;
import com.cts.paymentProcess.dao.PaymentDao;
import com.cts.paymentProcess.model.Payment;
List<Payment> list=paymentDao.getAllRecord();
list2 = list.stream().filter(x->x.getCustomerNumber()==customerNumber).collect(Collectors.toList());
return list2;
List<Payment> list=paymentDao.getAllRecord();
list2 = list.stream().filter(x->x.getPaymentDate().getYear()==(year-
1900)).sorted(Comparator.comparingInt(Payment::getAmount)).collect(Collectors.toList());
return list2;
}
SkeletonValidator.java*
package com.cts.paymentProcess.skeletonValidator;
import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;
public SkeletonValidator(){
validateClassName("com.cts.paymentProcess.dao.PaymentDao");
validateMethodSignature("getAllRecord:java.util.List","com.cts.paymentProcess.dao.PaymentDao");
validateClassName("com.cts.paymentProcess.model.Payment");
validateMethodSignature("toString:java.lang.String","com.cts.paymentProcess.model.Payment");
validateClassName("com.cts.paymentProcess.service.PaymentService");
validateMethodSignature("findCustomerByNumber:java.util.List,findCustomerByYear:java.util.List","com.cts.
paymentProcess.service.PaymentService");
validateClassName("com.cts.paymentProcess.util.DatabaseUtil");
validateMethodSignature("getConnection:java.sql.Connection","com.cts.paymentProcess.util.DatabaseUtil")
;
try {
Class.forName(className);
iscorrect = true;
} catch (ClassNotFoundException e) {
LOG.log(Level.SEVERE, "You have changed either the " + "class name/package. Use the
correct package "
} catch (Exception e) {
LOG.log(Level.SEVERE,
"There is an error in validating the " + "Class Name. Please manually verify
that the "
return iscorrect;
try {
String[] methodSignature;
methodSignature = singleMethod.split(":");
methodName = methodSignature[0];
returnType = methodSignature[1];
cls = Class.forName(className);
if (methodName.equals(findMethod.getName())) {
foundMethod = true;
if (!(findMethod.getReturnType().getName().equals(returnType))) {
errorFlag = true;
} else {
if (!foundMethod) {
errorFlag = true;
+ ". Do not change the " + "given public method name. " +
"Verify it with the skeleton");
if (!errorFlag) {
} catch (Exception e) {
LOG.log(Level.SEVERE,
" There is an error in validating the " + "method structure. Please manually
verify that the "
DatabaseUtil.java*
package com.cts.paymentProcess.util;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import java.util.ResourceBundle;
private DatabaseUtil() {
//ENSURE YOU DON'T CHANGE THE BELOW CODE WHEN YOU SUBMIT
try{
FileInputStream fis = null;
props.load(fis);
try {
Class.forName(props.getProperty("DB_DRIVER_CLASS"));
} catch (ClassNotFoundException e) {
e.printStackTrace();
try {
con =
DriverManager.getConnection(props.getProperty("DB_URL"),props.getProperty("DB_USERNAME"),props.getPropert
y("DB_PASSWORD"));
} catch (SQLException e) {
e.printStackTrace();
catch(IOException e){
e.printStackTrace();
return con;
}
App.java(Main)*
package com.cts.paymentProcess;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Scanner;
import com.cts.paymentProcess.model.Payment;
import com.cts.paymentProcess.service.PaymentService;
import com.cts.paymentProcess.skeletonValidator.SkeletonValidator;
new SkeletonValidator();
Payment payment=null;
do{
System.out.println("Select Option:");
int choice=scanner.nextInt();
switch(choice){
int number=scanner.nextInt();
if(numberList.size()==0){
}else{
System.out.format("%15s%15s%15s%15s\n","Customer Number","Cheque Number","Payment
Date","Amount");
numberList.stream()
.forEach(System.out::println);
break;
int year=scanner.nextInt();
if(yearList.size()==0){
}else{
yearList.stream()
.forEach(System.out::println);
break;
case 3:System.exit(0);
default:System.out.println("\nWrong Choice\n");
}while(true);
}
Employee Eligibility for Promotion
Main.java*
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.util.TreeMap;
import java.util.Date;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
//System.out.println("In-time");
String fdt=currTime.format(formatter);
// System.out.println(fdt);
int no = sc.nextInt();
String id = sc.next();
m.put(id, date);
}
int count = 0;
int val = 0;
if (entry.getValue().matches("(0[1-9]|[1-2][0-9]|3[0-1])/(0[1-9]|1[0-2])/[0-9]{4}"))
val++;
if (lin >= 5)
count++;
System.out.println(entry.getKey());
else
break;
}
Exam Scheduler
AssessmentDao.java*
package com.cts.cc.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.Period;
import java.util.List;
import java.sql.*;
import com.cts.cc.model.Assessment;
import com.cts.cc.util.DatabaseUtil;
if(assessments==null || assessments.isEmpty()) {
int rowsCount = 0;
try{
for(Assessment a:assessments)
st.setString(1,a.getExamCode());
st.setString(2,a.getExamTitle());
st.setString(3,a.getExamDate().toString());
st.setString(4,a.getExamTime().toString());
st.setString(5,a.getExamDuration().toString());
st.setString(6,a.getEvalDays().toString());
int rs=st.executeUpdate();
if(rs!=-1)
rowsCount=rowsCount+1;
} catch(SQLException e){
return rowsCount;
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, code);
ResultSet rs = ps.executeQuery();
if(rs.next()) {
assessment.setExamCode(rs.getString(1));
assessment.setExamTitle(rs.getString(2));
assessment.setExamDate(LocalDate.parse(rs.getString(3)));
assessment.setExamTime(LocalTime.parse(rs.getString(4)));
assessment.setExamDuration(Duration.parse(rs.getString(5)));
assessment.setEvalDays(Period.parse(rs.getString(6)));
return assessment;
}
GenerateAssessmentFunction.java*
package com.cts.cc.functions;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.Period;
import java.util.function.Function;
import com.cts.cc.model.Assessment;
@Override
String temp[]=t.split(",");
Assessment a = new
Assessment(temp[0],temp[1],LocalDate.parse(temp[2]),LocalTime.parse(temp[3]),Duration.parse(temp[4]),Period.p
arse(temp[5]));
return a;
Assessment.java*
package com.cts.cc.model;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
public Assessment(String examCode, String examTitle, LocalDate examDate, LocalTime examTime, Duration
examDuration,
Period evalDays) {
super();
this.examCode = examCode;
this.examTitle = examTitle;
this.examDate = examDate;
this.examTime = examTime;
this.examDuration = examDuration;
this.evalDays = evalDays;
public Assessment() {
return examCode;
this.examCode = examCode;
return examTitle;
}
public void setExamTitle(String examTitle) {
this.examTitle = examTitle;
return examDate;
this.examDate = examDate;
return examTime;
this.examTime = examTime;
return examDuration;
this.examDuration = examDuration;
return evalDays;
this.evalDays = evalDays;
}
DateTimeFormatter date1=DateTimeFormatter.ofPattern("dd-MMM-y");
DateTimeFormatter date2=DateTimeFormatter.ofPattern("HH:mm");
LocalTime t=examTime.plus(examDuration);
String d=DateTimeFormatter.ofPattern("HH:mm").format(t);
LocalDate t1=examDate.plus(evalDays);
String d1=DateTimeFormatter.ofPattern("dd-MMM-y").format(t1);
System.out.println("Title: "+examTitle);
DatabaseUtil.java*
package com.cts.cc.util;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
//ENSURE YOU DON'T CHANGE THE BELOW CODE WHEN YOU SUBMIT
try{
props.load(fis);
Class.forName(props.getProperty("DB_DRIVER_CLASS"));
con =
DriverManager.getConnection(props.getProperty("DB_URL"),props.getProperty("DB_USERNAME"),props.getPropert
y("DB_PASSWORD"));
catch(IOException e){
e.printStackTrace();
return con;
FileUtil.java*
package com.cts.cc.util;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.io.*;
import java.util.*;
import com.cts.cc.functions.GenerateAssessmentFunction;
import com.cts.cc.model.Assessment;
String line="";
list=new ArrayList<Assessment>();
while((line=br.readLine())!=null)
list.add(function.apply(line));
return list;
SkeletonValidator.java*
package com.cts.cc;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.Period;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.cts.cc.model.Assessment;
public SkeletonValidator() {
Period.class };
testClass(assessmentClass, assessmentParams);
testClass(assessmentDAOClass, null);
testClass(funtionalClass, null);
testClass(databaseUtilClass, null);
testClass(fileUtilClass, null);
testFields(assessmentClass, assessmentFields);
try {
constructor.equals(constructor);
} catch (ClassNotFoundException e) {
+ "Use the correct package and class name as provided in the skeleton");
} catch (NoSuchMethodException e) {
+ "Do not change the given public constructor. " + "Verify it with the
skeleton");
} catch (SecurityException e) {
LOG.log(Level.SEVERE,
"There is an error in validating the " + className + ". " + "Please verify the
skeleton manually");
try {
classUnderTest.getDeclaredField(field);
} catch (ClassNotFoundException e) {
+ "Use the correct package and class name as provided in the skeleton");
} catch (NoSuchFieldException e) {
LOG.log(Level.SEVERE,
"You have changed one/more field(s). " + "Use the field name(s) as provided
in the skeleton");
} catch (SecurityException e) {
LOG.log(Level.SEVERE,
"There is an error in validating the " + className + ". " + "Please verify the
skeleton manually");
public void testMethods(String className, String methodName, Class[] paramTypes, Class returnType) {
try {
LOG.log(Level.SEVERE, " You have changed the " + "return type in '" + methodName
} catch (ClassNotFoundException e) {
+ "Use the correct package and class name as provided in the skeleton");
} catch (NoSuchMethodException e) {
} catch (SecurityException e) {
LOG.log(Level.SEVERE,
"There is an error in validating the " + className + ". " + "Please verify the
skeleton manually");
}
Main.java*
package com.cts.cc;
import java.util.List;
import com.cts.cc.dao.AssessmentDAO;
import com.cts.cc.model.Assessment;
import com.cts.cc.util.FileUtil;
new SkeletonValidator();
try {
dao.uploadAssessments(assessments);
assessment.printDetails();
} catch (Exception e) {
System.out.println(e);
}
Book Details
Main.java*
import java.util.Scanner;
if(string.length()==18)
int i1 = Integer.parseInt(substr1);
int i2 = Integer.parseInt(substr2);
//System.out.println(substr3);
int i3 = Integer.parseInt(substr3);
if(i3>=10)
if((substr4.charAt(0)>='A'&&substr4.charAt(0)<='Z')||(substr4.charAt(0)>='a'&&substr4.charAt(0)<='z'))
if((substr5.charAt(0)>='0'&&substr5.charAt(0)<='9')&&(substr5.charAt(1)>='0'&&substr5.charAt(1)<='9')&&
(substr5.charAt(2)>='0'&&substr5.charAt(2)<='9')&&(substr5.charAt(3)>='0'&&substr5.charAt(3)<='9')&&
(substr5.charAt(4)>='0'&&substr5.charAt(4)<='9'))
{
String substr6 = string.substring(12,18);
if(i1==101)
else if(i1==102)
else if(i1==103)
else
System.out.printf("\n");
else
System.out.printf("\n");
else
System.out.printf("\n");
}
}
else
System.out.printf("\n");
else
System.out.printf("\n");
else
System.out.printf("\n");
}
Find Membership Category
Member.java*
return memberId;
this.memberId = memberId;
return memberName;
this.memberName = memberName;
return category;
this.category = category;
super();
this.memberId = memberId;
this.memberName = memberName;
this.category = category;
}
}
ZeeShop.java*
import java.util.List;
super();
this.memberCategory = memberCategory;
this.memberList = memberList;
return memberCategory;
this.memberCategory = memberCategory;
}
public int getCount() {
return count;
this.count = count;
return memberList;
this.memberList = memberList;
synchronized(this)
for(Member m:memberList)
if(m.getCategory().equals(memberCategory))
count++;
}
}
Main.java*
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
int tot=sc.nextInt();
for(int i=0;i<str.length;i++)
str[i]=sc.next();
for(int i=0;i<m.length;i++)
String s[]=str[i].split(":");
m[i]=new Member(s[0],s[1],s[2]);
mList.add(m[i]);
int tot1=sc.nextInt();
for(int i=0;i<tot1;i++)
String s1=sc.next();
t1[i]=new ZEEShop(s1,mList);
t1[i].start();
//System.out.println(s1+" "+t1.getCount());
try {
Thread.currentThread().sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
for(ZEEShop s:t1)
System.out.println(s.getMemberCategory()+":"+s.getCount());
}
Go Hospitals
InPatient.java*
public InPatient(String patientId, String patientName, long mobileNumber, String gender, double roomRent) {
super(patientId,patientName,mobileNumber,gender);
this.roomRent=roomRent;
return roomRent;
this.roomRent = roomRent;
double bill_amount;
bill_amount=((this.roomRent*noOfDays)+medicinalBill);
return bill_amount;
OutPatient.java*
public OutPatient(String patientId, String patientName, long mobileNumber, String gender, double consultingFee)
{
super(patientId,patientName,mobileNumber,gender);
this.consultingFee=consultingFee;
return consultingFee;
this.consultingFee = consultingFee;
double bill_amount;
bill_amount=this.consultingFee+scanPay+medicinalBill;
return bill_amount;
Patient.java*
this.patientId = patientId;
this.patientName = patientName;
this.mobileNumber = mobileNumber;
this.gender = gender;
return patientId;
this.patientId = patientId;
return patientName;
this.patientName = patientName;
return mobileNumber;
this.mobileNumber = mobileNumber;
return gender;
this.gender = gender;
}
UserInterface.java*
import java.util.Scanner;
System.out.println("1.In Patient");
System.out.println("1.Out Patient");
int ch=read.nextInt();
System.out.println("Patient Id");
String id=read.nextLine();
System.out.println("Patient Name");
String name=read.nextLine();
read.nextLine();
System.out.println("Phone Number");
long num=read.nextLong();
System.out.println("Gender");
String gen=read.next();
if(ch==1){
System.out.println("Room Rent");
double rent=read.nextDouble();
System.out.println("Medicinal Bill");
double bill=read.nextDouble();
int days=read.nextInt();
else{
System.out.println("Consultancy Fee");
double fee=read.nextDouble();
System.out.println("Medicinal Bill");
double medbill=read.nextDouble();
System.out.println("Scan Pay");
double pay=read.nextDouble();
}
Grade Calculation
GradeCalculator.java*
return studName;
this.studName = studName;
return result;
this.result = result;
return marks;
this.marks = marks;
}
public GradeCalculator(String studName, int[] marks){
this.studName = studName;
this.marks = marks;
int sum = 0;
for(int i = 0;i<score.length;i++)
sum = sum+score[i];
if((400<=sum)&&(sum<=500))
System.out.println(getStudName()+":"+'A');
if((300<=sum)&&(sum<=399))
System.out.println(getStudName()+":"+'B');
if((200<=sum)&&(sum<=299))
System.out.println(getStudName()+":"+'C');
if(sum<200)
System.out.println(getStudName()+":"+'E');
Main.java*
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.InputStreamReader;
int th = Integer.parseInt(br.readLine());
str = br.readLine();
details[i]=str;
int k = 0;
arr[k++] = Integer.parseInt(sp[j]);
obj.start();
try{
Thread.sleep(1000);
catch(Exception e)
System.out.println(e);
}
Passanger Amenity
Main.java*
import java.util.Scanner;
int num,n,i,count1=0,count2=0,y;
char alpha,ch;
String n1,n2;
n=sc.nextInt();
if(n<=0){
System.exit(0);
for(i=0;i<n;i++,count1=0,count2=0){
arr1[i] =sc.next();
arr2[i]= sc.next();
num =Integer.parseInt(arr2[i].substring(1,(arr2[i].length())));
alpha= arr2[i].charAt(0);
count2++;
for(ch=65;ch<84;ch++){
if(ch==alpha){
count1++;
if(count1==0){
System.out.println(""+alpha+" is invalid coach");
System.exit(0);
if(count2==0){
System.exit(0);
for(i=0;i<n;i++){
for(int j=i+1;j<n;j++){
if(arr2[i].charAt(0)==arr2[j].charAt(0)){
if((Integer.parseInt(arr2[i].substring(1,(arr2[i].length()))))<(Integer.parseInt(arr2[j].substring(1,arr2[j].length())))){
n1=arr1[i];
n2=arr2[i];
arr1[i]=arr1[j];
arr2[i]=arr2[j];
arr1[j]=n1;
arr2[j]=n2;
else
if(arr2[i].charAt(0)<arr2[j].charAt(0))
n1=arr1[i];
n2=arr2[i];
arr1[i]=arr1[j];
arr2[i]=arr2[j];
arr1[j]=n1;
arr2[j]=n2;
}
for(i=0;i<n;i++){
String a=arr1[i].toUpperCase();
String b=arr2[i];
System.out.print(a+" "+b);
System.out.println("");
}
Perform Calculation
Calculate.java*
Calculator.java*
import java.util.Scanner;
int a = sc.nextInt();
int b= sc.nextInt();
return Perform_calculation;
return Perform_calculation;
return Perform_calculation;
}
float c = (float)a;
float d = (float)b;
return (c/d);
};
return Perform_calculation;
}
Query DataSet
Query.java*
@Override
String g="";
g+=("Theatre id : "+primaryDataSet.getTheatreId()+"\n");
g+=("Location :"+primaryDataSet.getLocation()+"\n");
g+=("Theatre id : "+secondaryDataSet.getTheatreId()+"\n");
g+=("Location :"+secondaryDataSet.getLocation()+"\n");
g+=("Query id : "+queryId+"\n");
return g;
}
public class DataSet{
return ticketCost;
ticketCost=a;
return noOfScreen;
noOfScreen=a;
return location;
location=a;
}
return theatreName;
theatreName=a;
return theatreId;
theatreId=a;
this.secondaryDataSet=pD;
return this.secondaryDataSet;
this.primaryDataSet=pD;
}
public DataSet getPrimaryDataSet()
return this.primaryDataSet;
this.queryId=queryId;
this.queryCategory=queryCategory;
return this.queryId;
return this.queryCategory;
TestApplication.java*
import java.util.*;
pd.setTheatreName(sc.nextLine());
pd.setLocation(sc.nextLine());
pd.setNoOfScreen(sc.nextInt());
pd.setTicketCost(sc.nextDouble());
String id2=sc.next();
// System.out.println(id2);
sd.setTheatreId(id2);
sc.nextLine();
sd.setTheatreName(sc.nextLine());
String gll=sc.nextLine();
sd.setLocation(gll);
// System.out.println(gll);
// String pp=sc.nextLine();
// System.out.println(pp);
sd.setNoOfScreen(sc.nextInt());
sd.setTicketCost(sc.nextDouble());
sc.nextLine();
q.setQueryId(sc.nextLine());
q.setQueryCategory(sc.nextLine());
q.setSecondaryDataSet(sd);
q.setPrimaryDataSet(pd);
System.out.println(q.toString());
}
Retrive Flight Based On Source And Destination
Flight.java*
return flightId;
this.flightId = flightId;
return source;
this.source = source;
return destination;
this.destination = destination;
return noOfSeats;
this.noOfSeats = noOfSeats;
}
public double getFlightFare() {
return flightFare;
this.flightFare = flightFare;
super();
this.flightId = flightId;
this.source = source;
this.destination = destination;
this.noOfSeats = noOfSeats;
this.flightFare = flightFare;
FlightManagement.java*
import java.util.ArrayList;
import java.sql.*;
try{
String query="SELECT * FROM flight WHERE source= '" + source + "' AND destination= '" + destination + "' ";
Statement st=con.createStatement();
while(rst.next()){
String src=rst.getString(2);
String dst=rst.getString(3);
int noofseats=rst.getInt(4);
double flightfare=rst.getDouble(5);
e.printStackTrace();
return flightList;
DB.java*
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class DB {
try{
props.load(fis);
Class.forName(props.getProperty("DB_DRIVER_CLASS"));
con =
DriverManager.getConnection(props.getProperty("DB_URL"),props.getProperty("DB_USERNAME"),props.getPropert
y("DB_PASSWORD"));
catch(IOException e){
e.printStackTrace();
return con;
Main.java*
import java.util.Scanner;
import java.util.ArrayList;
String source=sc.next();
String destination=sc.next();
FlightManagementSystem fms= new FlightManagementSystem();
ArrayList<Flight> flightList=fms.viewFlightBySourceDestination(source,destination);
if(flightList.isEmpty()){
return;
}
Silver Health Plan Insurance
FamilyInsurancePolicy.java
public FamilyInsurancePolicy(String clientName, String policyId, int age, long mobileNumber, String emailId) {
int count=0;
if(policyId.contains("FAMILY"));
count++;
char ch[]=policyId.toCharArray();
for(int i=6;i<9;i++)
count++;
if(count==4)
return true;
else
return false;
double amount=0;
amount=2500*months*no_of_members;
amount=5000*months*no_of_members;
else if (age>=60)
amount=10000*months*no_of_members;
return amount;
IndividualInsurancePolicy.java*
public IndividualInsurancePolicy(String clientName, String policyId, int age, long mobileNumber, String
emailId) {
int count=0;
if(policyId.contains("SINGLE"));
count++;
char ch[]=policyId.toCharArray();
for(int i=6;i<9;i++)
count++;
if(count==4)
return true;
else
return false;
double amount=0;
if(age>=5 && age<=25)
amount=2500*months;
amount=5000*months;
else if (age>=60)
amount=10000*months;
return amount;
InsurancePolicies.java*
return clientName;
this.clientName = clientName;
return policyId;
this.policyId = policyId;
return age;
return mobileNumber;
this.mobileNumber = mobileNumber;
return emailId;
this.emailId = emailId;
public InsurancePolicies(String clientName, String policyId, int age, long mobileNumber, String emailId) {
super();
this.clientName = clientName;
this.policyId = policyId;
this.age = age;
this.mobileNumber = mobileNumber;
this.emailId = emailId;
SeniorCitizenPolicy.java*
public SeniorCitizenPolicy(String clientName, String policyId, int age, long mobileNumber, String emailId) {
int count=0;
if(policyId.contains("SENIOR"));
count++;
char ch[]=policyId.toCharArray();
for(int i=6;i<9;i++)
count++;
if(count==4)
return true;
else
return false;
double amount=0;
amount=0;
else if (age>=60)
amount=10000*months*no_of_members;
return amount;
UserInterface.java*
import java.util.Scanner;
{
Scanner sc=new Scanner(System.in);
String name=sc.next();
String id=sc.next();
int age=sc.nextInt();
long mnum=sc.nextLong();
String email=sc.next();
int month=sc.nextInt();
double amount=0;
if(id.contains("SINGLE"))
if(g.validatePolicyId())
//System.out.println(g.validatePolicyId());
amount=g.calculateInsuranceAmount(month);
System.out.println("Name :"+name);
System.out.println("Email Id :"+email);
else
}
else if(id.contains("FAMILY"))
if(g.validatePolicyId())
int num=sc.nextInt();
amount=g.calculateInsuranceAmount(month,num);
System.out.println("Name :"+name);
System.out.println("Email Id :"+email);
else
else if(id.contains("SENIOR"))
if(g.validatePolicyId())
int num=sc.nextInt();
amount=g.calculateInsuranceAmount(month,num);
System.out.println("Name :"+name);
System.out.println("Email Id :"+email);
else
}
else
}
Travel Request System
TraveRequestDao.java*
package com.cts.travelrequest.dao;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.*;
import java.util.*;
//import java.util.Properties;
import com.cts.travelrequest.vo.TravelRequest;
class DB{
//ENSURE YOU DON'T CHANGE THE BELOW CODE WHEN YOU SUBMIT
try{
props.load(fis);
Class.forName(props.getProperty("DB_DRIVER_CLASS"));
catch(IOException e){
e.printStackTrace();
return con;
/**
* @return list
*/
try{
Connection con=DB.getConnection();
PreparedStatement ps=con.prepareStatement(query);
ps.setString(1,sourceCity);
ps.setString(2,destinationCity);
ResultSet rs=ps.executeQuery();
while(rs.next()){
String tid=rs.getString("travelReqId");
java.sql.Date date=rs.getDate("travelDate");
String apstat=rs.getString("approvalStatus");
String sour=rs.getString("sourceCity");
String des=rs.getString("destinationCity");
double cost=rs.getDouble("travelCost");
catch(ClassNotFoundException e){
e.printStackTrace();
catch(SQLException e ){
e.printStackTrace();
/**
* @return list
*/
double amount=0;
try{
Connection con=DB.getConnection();
PreparedStatement ps1=con.prepareStatement(query);
ps1.setString(1,approvalStatus);
ResultSet rs1=ps1.executeQuery();
while(rs1.next()){
amount+=rs1.getDouble("travelCost");
catch(ClassNotFoundException e){
e.printStackTrace();
}
catch(SQLException e){
e.printStackTrace();
TravelRequestService.java*
package com.cts.travelrequest.service;
import java.util.List;
import com.cts.travelrequest.dao.TravelRequestDao;
import com.cts.travelrequest.vo.TravelRequest;
/**
* @return status
*/
if(approvalStatus.equalsIgnoreCase("Approved")||approvalStatus.equalsIgnoreCase("Pending")){
return "valid";
/**
* @return status
*/
if(!sourceCity.equalsIgnoreCase(destinationCity)){
if(sourceCity.equalsIgnoreCase("Pune")|| sourceCity.equalsIgnoreCase("Mumbai")||
sourceCity.equalsIgnoreCase("Chennai")|| sourceCity.equalsIgnoreCase("Bangalore")||
sourceCity.equalsIgnoreCase("Hydrabad")){
if(destinationCity.equalsIgnoreCase("Pune")||
destinationCity.equalsIgnoreCase("Mumbai")||destinationCity.equalsIgnoreCase("Chennai")||
destinationCity.equalsIgnoreCase("Bangalore")|| destinationCity.equalsIgnoreCase("Hydrabad")){
return "valid";
else{
return "invalid";
else{
return "invalid";
else{
return "invalid";
/**
* @return listOfTravelRequest
*/
if(this.validateSourceAndDestination(sourceCity,destinationCity).contentEquals("valid")){
return TravelRequestDao.getTravelDetails(sourceCity,destinationCity);
else{
return null;
}
}
/**
* @return totalCost
*/
if(this.validateApprovalStatus(approvalStatus).equals("valid")){
return TravelRequestDao.calculateTotalTravelCost(approvalStatus);
else{
return -1;
SkeletonValidator.java*
package com.cts.travelrequest.skeletonvalidator;
import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author t-aarti3
* This class is used to verify if the Code Skeleton is intact and not
* */
public SkeletonValidator() {
validateClassName("com.cts.travelrequest.service.TravelRequestService");
validateClassName("com.cts.travelrequest.vo.TravelRequest");
validateMethodSignature(
"validateApprovalStatus:java.lang.String,validateSourceAndDestination:java.lang.String,getTravelDetails:java
.util.List,calculateTotalTravelCost:double",
"com.cts.travelrequest.service.TravelRequestService");
try {
Class.forName(className);
iscorrect = true;
} catch (ClassNotFoundException e) {
LOG.log(Level.SEVERE, "You have changed either the " + "class name/package. Use the
correct package "
} catch (Exception e) {
LOG.log(Level.SEVERE,
"There is an error in validating the " + "Class Name. Please manually verify
that the "
return iscorrect;
try {
String[] methodSignature;
methodSignature = singleMethod.split(":");
methodName = methodSignature[0];
returnType = methodSignature[1];
cls = Class.forName(className);
if (methodName.equals(findMethod.getName())) {
foundMethod = true;
if (!(findMethod.getReturnType().getName().equals(returnType))) {
errorFlag = true;
} else {
if (!foundMethod) {
errorFlag = true;
+ ". Do not change the " + "given public method name. " +
"Verify it with the skeleton");
}
if (!errorFlag) {
} catch (Exception e) {
LOG.log(Level.SEVERE,
" There is an error in validating the " + "method structure. Please manually
verify that the "
TravelRequest.java*
package com.cts.travelrequest.vo;
import java.util.Date;
// member variables
public TravelRequest() {
super();
// parameterized constructor
super();
this.travelReqId = travelReqId;
this.travelDate = travelDate;
this.approvalStatus = approvalStatus;
this.sourceCity = sourceCity;
this.destinationCity = destinationCity;
this.travelCost = travelCost;
// setter, getter
/**
*/
return travelReqId;
/**
* @param travelReqId
*/
this.travelReqId = travelReqId;
/**
*/
return travelDate;
/**
* @param travelDate
*/
this.travelDate = travelDate;
/**
*/
return approvalStatus;
/**
* @param approvalStatus
*/
this.approvalStatus = approvalStatus;
/**
*/
return sourceCity;
/**
* @param sourceCity
*/
this.sourceCity = sourceCity;
/**
return destinationCity;
/**
* @param destinationCity
*/
this.destinationCity = destinationCity;
/**
*/
return travelCost;
/**
* @param travelCost
*/
this.travelCost = travelCost;
Main.java*
package com.cts.travelrequest.main;
import java.sql.*;
import java.util.*;
import java.text.SimpleDateFormat;
import com.cts.travelrequest.service.TravelRequestService;
import com.cts.travelrequest.skeletonvalidator.SkeletonValidator;
import com.cts.travelrequest.vo.TravelRequest;
new SkeletonValidator();
String sourceCity=sc.next();
String destinationCity=sc.next();
String status=sc.next();
if(service.validateSourceAndDestination(sourceCity,destinationCity).equals("valid")){
if(ltr.isEmpty()){
System.out.println("No travel request raised for given source and destination cities");
else{
for(TravelRequest t:ltr){
String d=sd.format(t.getTravelDate());
}
else{
if(service.validateApprovalStatus(status).contentEquals("valid")){
System.out.println(service.calculateTotalTravelCost(status));
else{