0% found this document useful (0 votes)
26 views49 pages

E TR 7 V HGCsy Cbei A2 RP 5 H A9

The document contains multiple Java programming tasks, including array compatibility checks, exception handling for array operations, student grade calculations, bill generation for snacks, fuel consumption calculations, and character display based on ASCII values. Each task includes sample input and output to illustrate expected functionality. The programs emphasize user input validation and proper handling of exceptions.

Uploaded by

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

E TR 7 V HGCsy Cbei A2 RP 5 H A9

The document contains multiple Java programming tasks, including array compatibility checks, exception handling for array operations, student grade calculations, bill generation for snacks, fuel consumption calculations, and character display based on ASCII values. Each task includes sample input and output to illustrate expected functionality. The programs emphasize user input validation and proper handling of exceptions.

Uploaded by

Varad Page
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

1.

​ Array Compatiblilty
Two arrays are said to be compatible if they are of the same size and if the ith element in the
first array is greater than or equal to the ith element in the second array for all i elements.If
the array size is zero or lesser then display the message "Invalid array size".Write a Java
program to find whether 2 arrays are compatible or not.If the arrays are compatible display
the message as "Arrays are Compatible" ,if not then display the message as "Arrays are Not
Compatible".
Sample Input 1:
Enter the size for First array:
5
Enter the elements for First array:
5
14
17
19
15
Enter the size for Second array:
5
Enter the elements for Second array:
2
5
9
15
7
Sample Output 1:
Arrays are Compatible
Sample Input 2:
Enter the size for First array:
3
Enter the elements for First array:
1
4
7
Enter the size for Second array:
5
Enter the elements for Second array:
2
5
9
5
7
Sample Output 2:
Arrays are Not Compatible
Sample Input 3:
Enter the size for First array:
-2
Sample Output 3:
Invalid array size
Program
import java.util.Scanner;
class CompatibleArrays {
private static void test(int size) {
if (size <= 0) {
System.out.println("Invalid array size");
System.exit(0);
}
}

private static boolean isCompatible(int[] arr1, int[] arr2) {


if (arr1.length != arr2.length) {
return false;
}

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


if (arr1[i] < arr2[i]) {
return false;
}
}

return true;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
int m, n;
int[] arr1, arr2;

System.out.println("Enter the size for First array:");


m = scanner.nextInt();
test(m);
arr1 = new int[m];

System.out.println("Enter the elements for First array:");

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


arr1[i] = scanner.nextInt();
}

System.out.println("Enter the size for Second array:");


n = scanner.nextInt();
test(n);
arr2 = new int[n];

System.out.println("Enter the elements for Second array:");

for (int j = 0; j < n; ++j) {


arr2[j] = scanner.nextInt();
}

if (isCompatible(arr1, arr2)) {
System.out.println("Arrays are Compatible");
} else {
System.out.println("Arrays are Not Compatible");
}
}
}

2.​ Array Manipulation - Use try with multi catch


Tom wants to store the price details of the products that he purchased from the
departmental store. Help him do this by using the concept of Arrays.
To do this create a public class ArrayException with a method getPriceDetails as :
public String getPriceDetails() - This method should do the following
Get the size of an array as input and then get the elements of the array(all elements are int)
as input.
Next, user should provide the index of the array. This method should return the element at
that index as “The array element is “+
This program may generate ArrayIndexOutOfBoundsException / InputMismatchException
In case of ArrayIndexOutOfBoundsException, the function should return “Array index is out
of range”.
When providing the input, if the input is not an integer, it will generate
InputMismatchException. In this case the function should return “Input was not in the
correct format”.
Use exception handling mechanism to handle the exception. Use separate catch block for
handling each exception. In the catch block, return the appropriate message.
Write a main method and test the above function.
Sample Input 1:
Enter the number of elements in the array
5
Enter the price details
50
80
60
70
40
Enter the index of the array element you want to access
1
Sample Output 1:
The array element is 80

Sample Input 2:
Enter the number of elements in the array
2
Enter the price details
50
80
Enter the index of the array element you want to access
9
Sample Output 2:
Array index is out of range
Sample Input 3:
Enter the number of elements in the array
2
Enter the price details
30
j
Sample Output 3:
Input was not in the correct format
Program
import java.util.InputMismatchException;
import java.util.Scanner;

public class ArrayException {


public String getPriceDetails() {
Scanner scanner = new Scanner(System.in);

System.out.println("Enter the number of elements in the array");


int n = scanner.nextInt();
int[] arr = new int[n];

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

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


try {
arr[i] = scanner.nextInt();
} catch (InputMismatchException ignore) {
return "Input was not in the correct format";
}
}
System.out.println("Enter the index of the array element you want to access");

try {
int index = scanner.nextInt();
return "The array element is " + arr[index];
} catch (InputMismatchException ignore) {
return "Input was not in the correct format";
} catch (ArrayIndexOutOfBoundsException ignore) {
return "Array index is out of range";
}
}

public static void main(String[] args) {


System.out.println(new ArrayException().getPriceDetails());
}
}

3.​ Average and Grade Calculation


Develop a smart application as Student Grade Calculator(SGC).
Create a class Student with following private attribute :
int id, String name, marks(integer array), float average and char grade. Include appropriate
getters and setters methods and constructor.
public void calculateAvg()- This method should calculate average and set average mark for
the current student.
public void findGrade()- This method should set the grade based on the average calculated.
If the average is between 80 and 100 then, then return grade as 'O', else 'A' .If the student
gets less than 50 in any of the subjects then return grade as 'F'. Using appropriate setter
method set the grade to the student.
(Note : number of subject should be greater than zero, if not display as 'Invalid number of
subject' and get number of subject again, Assume mark for a subject should be in the range
0 - 100. If not display a message "Invalid Mark" and get the mark again)
Write a class StudentMain and write the main method.
In this class, write a method
public static Student getStudentDetails() - this method should get the input from the user for
a student, create a student object with those details and return that object.
In main create student’s object by invoking the getStudentDetails method. Also calculate
average and grade for that student object using appropriate methods.
SGC app should get the input and display the output as specified in the snapshot:
Sample Input 1:
Enter the id:
123
Enter the name:
Tom
Enter the no of subjects:
3
Enter mark for subject 1:
95
Enter mark for subject 2:
80
Enter mark for subject 3:
75
Sample Output 1:
Id:123
Name:Tom
Average:83.33
Grade:O

Sample Input 2:
Enter the id:
123
Enter the name:
Tom
Enter the no of subjects:
0
Invalid number of subject
Enter the no of subjects:
3
Enter mark for subject 1:
75
Enter mark for subject 2:
49
Enter mark for subject 3:
90
Sample Output 2:
Id:123
Name:Tom
Average:71.33
Grade:F
Program:
public class Student {
private int id;
private String name;
private int[] marks;
private float average;
private char grade;

public Student(int id, String name, int[] marks) {


this.id = id;
this.name = name;
this.marks = marks;
}

public int getId() {


return id;
}

public void setId(int id) {


this.id = id;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public int[] getMarks() {


return marks;
}

public void setMarks(int[] marks) {


this.marks = marks;
}

public float getAverage() {


return average;
}

public void setAverage(float average) {


this.average = average;
}

public char getGrade() {


return grade;
}

public void setGrade(char grade) {


this.grade = grade;
}

public void calculateAvg() {


int totalMarks = 0;

for (int mark : marks) {


totalMarks += mark;
}

average = (float) totalMarks / (float) marks.length;


}

public void findGrade() {


if (average <= 100 && average >= 80) {
grade = 'O';
} else if (average < 80 && average >= 50) {
grade = 'A';
}

for (int mark : marks) {


if (mark < 50) {
grade = 'F';
}
}
}
}

4.​ Bill Generation


Tom went to a movie with his friends in a multiplex theatre and during break time he bought pizzas,
puffs and cool drinks. Consider the following prices :

Rs.100/pizza Rs.20/puffs Rs.10/cooldrink Generate a bill for What Tom has bought.

Sample Input 1:

Enter the no of pizzas bought:10

Enter the no of puffs bought:12

Enter the no of cool drinks bought:5

Sample Output 1:

Bill Details

No of pizzas:10

No of puffs:12

No of cooldrinks:5

Total price=1290

ENJOY THE SHOW!!!

Program:

import java.util.*;

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

Scanner scanner = new Scanner(System.in);

int pizza = 100;

int puff = 20;

int coolDrink = 10;

System.out.println("Enter the no of pizzas bought:");

int pizzaCount = scanner.nextInt();

System.out.println("Enter the no of puffs bought:");

int puffCount = scanner.nextInt();

System.out.println("Enter the no of cool drinks bought:");

int coolDrinkCount = scanner.nextInt();

long price = pizza * pizzaCount + puff * puffCount + coolDrink * coolDrinkCount;

System.out.println("Bill Details");

System.out.println("No of pizzas:" + pizzaCount);

System.out.println("No of puffs:" + puffCount);

System.out.println("No of cooldrinks:" + coolDrinkCount);

System.out.println("Total price=" + price);

System.out.println("ENJOY THE SHOW!!!");

5.​ Question 5

Problem Statement – Write a program to calculate the fuel consumption of your truck.The program
should ask the user to enter the quantity of diesel to fill up the tank and the distance covered till the
tank goes dry.Calculate the fuel consumption and display it in the format (liters per 100 kilometers).

Convert the same result to the U.S. style of miles per gallon and display the result. If the quantity or
distance is zero or negative display ” is an Invalid Input”.

[Note: The US approach of fuel consumption calculation (distance / fuel) is the inverse of the
European approach (fuel / distance ). Also note that 1 kilometer is 0.6214 miles, and 1 liter is 0.2642
gallons.]
The result should be with two decimal place.To get two decimal place refer the below-mentioned
print statement :

float cost=670.23;

System.out.printf(“You need a sum of Rs.%.2f to cover the trip”,cost);

Sample Input 1:

●​ Enter the no of liters to fill the tank

20

●​ Enter the distance covered

150

Sample Output 1:

●​ Liters/100KM

13.33

●​ Miles/gallons

17.64

Explanation:

●​ For 150 KM fuel consumption is 20 liters,

●​ Then for 100 KM fuel consumption would be (20/150)*100=13.33,

●​ Distance is given in KM, we have to convert it to miles (150*0.6214)=93.21,

●​ Fuel consumption is given in liters, we have to convert it to gallons (20*0.2642)=5.284,

●​ Then find (miles/gallons)=(93.21/5.284)=17.64

Sample Input 2:

●​ Enter the no of liters to fill the tank

-5

Sample Output 2:

●​ -5 is an Invalid Input

Sample Input 3:

●​ Enter the no of liters to fill the tank

25

●​ Enter the distance covered

-21

Sample Output 3:
●​ -21 is an Invalid Input

Java

import java.util.*;

import java.text.*;

class Main{

public static void main (String[] args) {

DecimalFormat df2 =new DecimalFormat("0.00");

Scanner sc= new Scanner (System.in);

System.out.println("Enter the no of liters to fill the tank");

int ltt =sc.nextInt();

double lt= (ltt*1.00);

if(ltt<1){

System.out.println(ltt+" is an Invalid Input");

System.exit(0);

System.out.println("Enter the distance covered");

int diss =sc.nextInt();

double dis= (diss*1.00);

if(diss<1){

System.out.println(diss+" is an Invalid Input");

System.exit(0);

double hundered = ((lt/dis)*100);

System.out.println("Liters/100KM");

System.out.println(df2.format(hundered));

double miles = (dis*0.6214);


double gallons =(lt*0.2642);

double mg = miles/gallons;

System.out.println("Miles/gallons");

System.out.println(df2.format(mg));

6.​ Question

Problem Statement – Vohra went to a movie with his friends in a Wave theatre and during break
time he bought pizzas, puffs and cool drinks. Consider the following prices :

●​ Rs.100/pizza

●​ Rs.20/puffs

●​ Rs.10/cooldrink

Generate a bill for What Vohra has bought.

Sample Input 1:

●​ Enter the no of pizzas bought:10

●​ Enter the no of puffs bought:12

●​ Enter the no of cool drinks bought:5

Sample Output 1:

Bill Details

●​ No of pizzas:10

●​ No of puffs:12

●​ No of cooldrinks:5

●​ Total price=1290

ENJOY THE SHOW!!!

Java

import java.util.Scanner;

public class Main

public static void main (String[]args)

{
int totalprice;

Scanner sc = new Scanner (System.in);

System.out.print ("Enter the no of pizzas bought:");

int pizza = sc.nextInt ();

System.out.print ("Enter the no of puffs bought:");

int puffs = sc.nextInt ();

System.out.print ("Enter the no of cool drinks bought:");

int coolDrinks = sc.nextInt ();

int pizzaa = Math.abs (pizza) * 100;

int puffss = Math.abs (puffs) * 20;

int coolDrinkss = Math.abs (coolDrinks) * 10;

System.out.println ("Bill Details");

System.out.println ("No of pizzas:" + pizza);

System.out.println ("No of puffs:" + puffs);

System.out.println ("No of cooldrinks:" + coolDrinks);

totalprice = pizzaa + puffss + coolDrinkss;

System.out.println ("Total price=" + totalprice);

System.out.println ("ENJOY THE SHOW!!!");

7.​ Question

Problem Statement – Ritik wants a magic board, which displays a character for a corresponding
number for his science project. Help him to develop such an application.​
For example when the digits 65,66,67,68 are entered, the alphabet ABCD are to be displayed.​
[Assume the number of inputs should be always 4 ]

Sample Input 1:
●​ Enter the digits:​
65​
66​
67​
68

Sample Output 1:

65-A​
66-B​
67-C​
68-D

Sample Input 2:

●​ Enter the digits:​


115​
116​
101​
112

Sample Output 2:

115-s​
116-t​
101-e​
112-p

import java.util.Scanner;

public class Main

public static void main (String args[])

Scanner in = new Scanner (System.in);

System.out.println ("Enter the digits: ");

int a = in.nextInt ();

int b = in.nextInt ();

int c = in.nextInt ();

int d = in.nextInt ();

char q = (char) a;

char w = (char) b;
char e = (char) c;

char r = (char) d;

System.out.println ();

System.out.print (a);

System.out.println ("-" + q);

System.out.print (b);

System.out.println ("-" + w);

System.out.print (c);

System.out.println ("-" + e);

System.out.print (d);

System.out.println ("-" + r);

8.​ Question

Problem Statement – FOE college wants to recognize the department which has succeeded in getting
the maximum number of placements for this academic year. The departments that have participated
in the recruitment drive are CSE,ECE, MECH. Help the college find the department getting maximum
placements. Check for all the possible output given in the sample snapshot

Note : If any input is negative, the output should be “Input is Invalid”. If all department has equal
number of placements, the output should be “None of the department has got the highest
placement”.

Sample Input 1:

●​ Enter the no of students placed in CSE:90

●​ Enter the no of students placed in ECE:45

●​ Enter the no of students placed in MECH:70

Sample Output 1:

●​ Highest placement

CSE

Sample Input 2:
●​ Enter the no of students placed in CSE:55

●​ Enter the no of students placed in ECE:85

●​ Enter the no of students placed in MECH:85

Sample Output 2:

●​ Highest placement

ECE

MECH

Sample Input 3:

●​ Enter the no of students placed in CSE:0

●​ Enter the no of students placed in ECE:0

●​ Enter the no of students placed in MECH:0

Sample Output 3:

●​ None of the department has got the highest placement

Sample Input 4:

●​ Enter the no of students placed in CSE:10

●​ Enter the no of students placed in ECE:-50

●​ Enter the no of students placed in MECH:40

Sample Output 4:

●​ Input is Invalid

import java.util.Scanner;

public class Main {

public static void main (String[]args) {

// Initialize Scanner object

Scanner sc = new Scanner (System.in);

// Take user input

System.out.print ("Enter the no. of students placed in CSE: ");

int cse = sc.nextInt ();

System.out.print ("Enter the no. of students placed in ECE: ");

int ece = sc.nextInt ();

System.out.print ("Enter the no. of students placed in MECH: ");

int mech = sc.nextInt ();


sc.close ();

// If any integer is negative, print message and exit

if (cse < 0 || ece < 0 || mech < 0){

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

// If all values are equal, print message and exit

else{

if (cse == ece && ece == mech && mech == cse){

​ System.out.println("None of the department has got the highest placement");

​ }

​ //System.out.println("Highest Placement:");

// First, check if any two values are equal and greater than the third

​ else if (cse == ece && cse > mech){

​ System.out.println ("Highest Placement:");

​ System.out.println ("CSE");

​ System.out.println ("ECE");

​ }

​ else if (cse == mech && cse > ece){

​ System.out.println ("Highest Placement:");

​ System.out.println ("CSE");

​ System.out.println ("MECH");

​ }

​ else if (ece == mech && ece > cse) {

​ System.out.println ("Highest Placement:");

​ System.out.println ("ECE");

​ System.out.println ("MECH");

​ }

​ // Now, if we reached here, all values are distinct

// Check if one value is greater than both

​ else if (cse > ece && cse > mech){


​ System.out.println ("Highest Placement:");

​ System.out.println ("CSE");

​ }

​ else if (ece > mech){

​ System.out.println ("Highest Placement:");

​ System.out.println ("ECE");

​ }

​ else{

​ System.out.println ("Highest Placement:");

​ System.out.println ("MECH");

​ }

9.​ Question

Problem Statement – In a theater, there is a discount scheme announced where one gets a 10%
discount on the total cost of tickets when there is a bulk booking of more than 20 tickets, and a
discount of 2% on the total cost of tickets if a special coupon card is submitted. Develop a program to
find the total cost as per the scheme. The cost of the k class ticket is Rs.75 and q class is Rs.150.
Refreshments can also be opted by paying an additional of Rs. 50 per member.

Hint: k and q and You have to book minimum of 5 tickets and maximum of 40 at a time. If fails
display “Minimum of 5 and Maximum of 40 Tickets”. If circle is given a value other than ‘k’ or ‘q’
the output should be “Invalid Input”.

The ticket cost should be printed exactly to two decimal places.

Sample Input 1:

●​ Enter the no of ticket:35

●​ Do you want refreshment:y

●​ Do you have coupon code:y

●​ Enter the circle:k

Sample Output 1:

●​ Ticket cost:4065.25

Sample Input 2:
●​ Enter the no of ticket:1

Sample Output 2:

●​ Minimum of 5 and Maximum of 40 Tickets

import java.util.Scanner;

import java.text.DecimalFormat;

public class Main

public static void main (String[]args)

int noTicket;

double total = 0, cost;

String ref, co, circle;

Scanner s = new Scanner (System.in);

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

noTicket = s.nextInt ();

if (noTicket < 5 || noTicket > 40){

​ System.out.println ("Minimum of 5 and Maximum of 40 tickets");

​ System.exit (0);

System.out.println ("Do you want refreshment:");

ref = s.next ();

System.out.println ("Do you have coupon code:");

co = s.next ();

System.out.println ("Enter the circle:");

circle = s.next ();

if (circle.charAt (0) == 'k') cost = 75 * noTicket;

else if (circle.charAt (0) == 'q') cost = 150 * noTicket;

else {

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


​ return;

total = cost;

if (noTicket > 20)

cost = cost - ((0.1) * cost);

total = cost;

if (co.charAt (0) == 'y')

total = cost - ((0.02) * cost);

if (ref.charAt (0) == 'y')

total += (noTicket * 50);

System.out.format ("Ticket cost:%.2f", total);

10.​Question

Problem Statement – Rhea Pandey’s teacher has asked her to prepare well for the lesson on seasons.
When her teacher tells a month, she needs to say the season corresponding to that month. Write a
program to solve the above task.

●​ Spring – March to May,

●​ Summer – June to August,

●​ Autumn – September to November and,

●​ Winter – December to February.

Month should be in the range 1 to 12. If not the output should be “Invalid month”.

Sample Input 1:

●​ Enter the month:11

Sample Output 1:

●​ Season:Autumn

Sample Input 2:
●​ Enter the month:13

Sample Output 2:

●​ Invalid month

import java.util.Scanner;

public class Main {

public static void main (String args[]) {

System.out.print ("Enter the month:");

Scanner s = new Scanner (System.in);

int entry = s.nextInt ();

switch (entry){

case 12:

case 1:

case 2:

System.out.println ("Season:Winter");

break;

case 3:

case 4:

case 5:

System.out.println ("Season:Spring");

break;

case 6:

case 7:

case 8:

System.out.println ("Season:Summer");

break;

case 9:

case 10:

case 11:

System.out.println ("Season:Autumn");

break;
default:

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

11.​Question

Problem Statement – To speed up his composition of generating unpredictable rhythms, Blue Bandit
wants the list of prime numbers available in a range of numbers.Can you help him out?

Write a java program to print all prime numbers in the interval [a,b] (a and b, both inclusive).

Note

●​ Input 1 should be lesser than Input 2. Both the inputs should be positive.

●​ Range must always be greater than zero.

●​ If any of the condition mentioned above fails, then display “Provide valid input”

●​ Use a minimum of one for loop and one while loop

Sample Input 1:

15

Sample Output 1:

2 3 5 7 11 13

Sample Input 2:

Sample Output 2:

●​ Provide valid input

import java.util.*;

public class Main

public static void main (String[] args) {

Scanner sc=new Scanner(System.in);


int a=sc.nextInt();

int b=sc.nextInt();

int flag;

if(a<=0 || b<=0 || a>=b)

System.out.println("Provide valid input");

else{

Inner:

while(a<=b){

if(a==2)

System.out.print(a+" ");

else if(a==1){

a++;

continue;

else{

flag=0;

outer:

for(int i=2;i<=a/2;i++){

if(a%i==0){

flag=1;

break outer;

if(flag==0)

System.out.print(a+" ");

a++;

}
}

12.​Question

Problem Statement – Goutam and Tanul plays by telling numbers. Goutam says a number to
Tanul. Tanul should first reverse the number and check if it is same as the original. If yes, Tanul
should say “Palindrome”. If not, he should say “Not a Palindrome”. If the number is negative, print
“Invalid Input”. Help Tanul by writing a program.

Sample Input 1 :

21212

Sample Output 1 :

Palindrome

Sample Input 2 :

6186

Sample Output 2 :

Not a Palindrome

import java.util.Scanner;

public class Main

public static void main (String args[])

Scanner in = new Scanner (System.in);

int n = in.nextInt ();

int sum = 0, r;

int temp = n;

if (n > -1)

​ while (n > 0)

​ {

​ r = n % 10;

​ sum = (sum * 10) + r;


​ n = n / 10;

​ }

​ if (temp == sum)

​ System.out.println ("Palindrome");

​ else

​ System.out.println ("Not a Palindrome");

else

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

13.​Question

XYZ Technologies is in the process of increment the salary of the employees. This increment is done
based on their salary and their performance appraisal rating.

1.​ If the appraisal rating is between 1 and 3, the increment is 10% of the salary.

2.​ If the appraisal rating is between 3.1 and 4, the increment is 25% of the salary.

3.​ If the appraisal rating is between 4.1 and 5, the increment is 30% of the salary.

Help them to do this, by writing a program that displays the incremented salary. Write a class
“IncrementCalculation.java” and write the main method in it.

Note : If either the salary is 0 or negative (or) if the appraisal rating is not in the range 1 to 5
(inclusive), then the output should be “Invalid Input”.

Sample Input 1 :

●​ Enter the salary

8000

●​ Enter the Performance appraisal rating

Sample Output 1 :

8800

Sample Input 2 :

●​ Enter the salary


7500

●​ Enter the Performance appraisal rating

4.3

Sample Output 2 :

9750

Sample Input 3 :

●​ Enter the salary

-5000

●​ Enter the Performance appraisal rating

Sample Output 3 :

●​ Invalid Input

import java.util.*;

class Main{

public static void main (String[] args) {

Scanner sc = new Scanner (System.in);

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

int salary = sc.nextInt();

System.out.println("Enter the Performance appraisal rating");

float rating = sc.nextFloat();

if(salary<1||rating<1.0||rating>5.0){

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

System.exit(0);
}

else if(rating>=1&&rating<=3){

salary=salary+(int)(0.1*salary);

System.out.println(salary);

} else if(rating>3&&rating<=4){

salary=salary+(int)(0.25*salary);

System.out.println(salary);

Else

/*if(rating>4&&rating<=5)*/

salary=salary+(int)(0.3*salary);

System.out.println(salary);

14.​Question-10

Problem Statement – Chaman planned to choose a four digit lucky number for his car. His lucky
numbers are 3,5 and 7. Help him find the number, whose sum is divisible by 3 or 5 or 7. Provide a
valid car number, Fails to provide a valid input then display that number is not a valid car number.

Note : The input other than 4 digit positive number[includes negative and 0] is considered as invalid.

Refer the samples, to read and display the data.

Sample Input 1:

●​ Enter the car no:1234


Sample Output 1:

●​ Lucky Number

Sample Input 2:

●​ Enter the car no:1214

Sample Output 2:

●​ Sorry its not my lucky number

Sample Input 3:

●​ Enter the car no:14

Sample Output 3:

●​ 14 is not a valid car number

import java.util.*;

class Main {

public static void main (String[]args)

int sum = 0;

Scanner sc = new Scanner (System.in);

System.out.print ("Enter the car no:");

int carNum = sc.nextInt ();

if (carNum < 1000 || carNum > 9999)

​ System.out.println (carNum + " is not a valid car number");

else

while (carNum != 0)

​ {

​ int l = carNum % 10;

​ sum = sum + l;

​ carNum = carNum / 10;

​ }
if (sum % 3 == 0 || sum % 5 == 0 || sum % 7 == 0)

​ {

​ System.out.println ("Lucky Number");

​ }

​ else

​ {

​ System.out.println ("Sorry its not my lucky number");

​ }

15.​Question
Problem Statement –

IIHM institution is offering a variety of courses to students. Students have a facility to check whether
a particular course is available in the institution. Write a program to help the institution accomplish
this task. If the number is less than or equal to zero display “Invalid Range”.

Assume maximum number of courses is 20.

Sample Input 1:

●​ Enter no of course:

●​ Enter course names:

Java

Oracle

C++

Mysql

Dotnet

●​ Enter the course to be searched:

C++

Sample Output 1:

C++ course is available


Sample Input 2:

●​ Enter no of course:

●​ Enter course names:

●​ Enter the course to be searched:

C++

Sample Output 2:

C++ course is not available

Sample Input 3:

●​ Enter no of course:

Sample Output 3:

Invalid Range

import java.util.*;

class Main

public static void main(String[] args)

int n=0,flag=0;

String courseSearch;

Scanner sc = new Scanner (System.in);

System.out.println("Enter no of course:");

n= sc.nextInt();

if(n<=0||n>20){

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

System.exit(0);

System.out.println("Enter course names:");

String[] course = new String[n];

sc.nextLine();
for (int i = 0; i < course.length; i++) {

course[i] = sc.nextLine();

System.out.println("Enter the course to be searched:");

courseSearch=sc.nextLine();

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

if(course[i].equals(courseSearch))

flag=1;

if(flag==1){

System.out.println(courseSearch+" course is available");

else {

System.out.println(courseSearch+" course is not available");

16.​Question

Problem Statement – Mayuri buys “N” no of products from a shop. The shop offers a different
percentage of discount on each item. She wants to know the item that has the minimum discount
offer, so that she can avoid buying that and save money.​
[Input Format: The first input refers to the no of items; the second input is the item name, price and
discount percentage separated by comma(,)]​
Assume the minimum discount offer is in the form of Integer.

Note: There can be more than one product with a minimum discount.

Sample Input 1:

4
mobile,10000,20

shoe,5000,10

watch,6000,15

laptop,35000,5

Sample Output 1:

shoe

Explanation: The discount on the mobile is 2000, the discount on the shoe is 500, the discount on
the watch is 900 and the discount on the laptop is 1750. So the discount on the shoe is the minimum.

Sample Input 2:

Mobile,5000,10

shoe,5000,10

WATCH,5000,10

Laptop,5000,10

Sample Output 2:

Mobile

shoe

WATCH

Laptop

import java.util.*;

import java.io.*;

public class Main{

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

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

Scanner sc=new Scanner(System.in);

int num = Integer.parseInt(br.readLine());

int itemPrice[] = new int[num];

int itemDis[] = new int[num];

String itemName[] = new String[num];

//String[] values;
float dis[] = new float[num];

String[] input = new String[num];

for(int i=0;i< num;i++)

String s[]= br.readLine().split(",");

itemName[i] =s[0];

//System.out.println(itemName[i]);

itemPrice[i]=Integer.parseInt(s[1]);

// System.out.println(itemPrice[i]);

itemDis[i]=Integer.parseInt(s[2]);

// System.out.println(itemDis[i]);

//float x = itemDis[i]

dis[i]=(float)((itemDis[i]*itemPrice[i])/100);

// System.out.println(dis[i]);

int idx[]=new int[num];

int j=0;

float min= Float.MAX_VALUE;

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

if(dis[i]<=min)

min=dis[i];

idx[j++]=i;

//System.out.println(min);

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

System.out.println(itemName[idx[i]]);

//System.out.println(idx[i]);

}
}

17.​Question

Problem Statement – Raj wants to know the maximum marks scored by him in each semester. The
mark should be between 0 to 100 ,if goes beyond the range display “You have entered invalid mark.”

Sample Input 1:

●​ Enter no of semester:

●​ Enter no of subjects in 1 semester:

●​ Enter no of subjects in 2 semester:

●​ Enter no of subjects in 3 semester:

●​ Marks obtained in semester 1:

50​
60​
70

●​ Marks obtained in semester 2:

90​
98​
76​
67

●​ Marks obtained in semester 3:

89​
76

Sample Output 1:

●​ Maximum mark in 1 semester:70

●​ Maximum mark in 2 semester:98

●​ Maximum mark in 3 semester:89

Sample Input 2:
●​ Enter no of semester:

●​ Enter no of subjects in 1 semester:

●​ Enter no of subjects in 2 semester:

●​ Enter no of subjects in 3 semester:

●​ Marks obtained in semester 1:

55​
67​
98

●​ Marks obtained in semester 2:

67​
-98

Sample Output 2:

You have entered invalid mark.

import java.util.*;

import java.lang.*;

import java.io.*;

class Main{

public static void main (String[] args) throws java.lang.Exception{

Scanner sc = new Scanner (System.in);

System.out.println("Enter no of semester:");

int sems = sc.nextInt();

boolean incorrect = false;

int arr[] = new int [sems];

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

System.out.println("Enter no of subjects in "+(i+1)+" semester:");

arr[i]=sc.nextInt();

}
int maxMarks[] = new int[sems];

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

System.out.println("Marks obtained in semester "+(i+1)+":");

int max = sc.nextInt();

if(max<0||max>100) {

System.out.println("You have entered invalid mark.");

System.exit(0);

for(int j=1;j< arr[i];j++) {

int marks=sc.nextInt();

if(marks<0||marks>100)

System.out.println("You have entered invalid mark.");

System.exit(0);

if(max< marks)

max=marks;

maxMarks[i]= max;

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

System.out.println("Maximum mark in "+(i+1)+" semester:"+maxMarks[i]);

}
18.​Question

Problem Statement – Bela teaches her daughter to find the factors of a given number. When she
provides a number to her daughter, she should tell the factors of that number. Help her to do this, by
writing a program. Write a class FindFactor.java and write the main method in it.​
Note :

●​ If the input provided is negative, ignore the sign and provide the output. If the input is zero

●​ If the input is zero the output should be “No Factors”.

Sample Input 1 :

54

Sample Output 1 :

1, 2, 3, 6, 9, 18, 27, 54

Sample Input 2 :

-1869

Sample Output 2 :

1, 3, 7, 21, 89, 267, 623, 1869

import java.util.*;

public class Main{

public static void main(String[] args){

int i;

Scanner sc = new Scanner (System.in);

int num = sc.nextInt();

if(num==0){

System.out.println("No Factors");

else if(num>0){

for(i=1;i< num;i++){

if(num%i==0){

System.out.print(i+", ");

System.out.println(num);
}

else{

num=num*-1;

for(i=1;i< num;i++){

if(num%i==0){

System.out.print(i+", ");

System.out.println(num);

19.​Book Manipulation

The district central library needs an application to store book details of their library. The clerk who
has all the rights to add a new book,search for any book,display the book details and should update
the count of total number of books.

You are provided with a Book with the following private attributes:

●​ int isbnno

●​ String bookName

●​ String author

Needed getters and setters are written.

Create a class Library with the following private attribute:

●​ ArrayList bookList = new ArrayList();

Also provide the necessary setter and getter methods.​


Include the following public methods:

●​ void addBook(Book bobj) - This method should add the book object to the booklist.

●​ boolean isEmpty() - This method should return true if the booklist is empty else return false.

●​ ArrayList<Book> viewAllBooks() - This method should return the list of books maintained in
the library.
●​ ArrayList<Book> viewBooksByAuthor(String author) - This method should return a list of
books written by the author passed as argument. When you display an empty list it should
print the message "The list is empty".

●​ int countnoofbook(String bname) - this method should return the count of books with the
name passed as argument.

Write a Main class to test the above functionalities.

Sample Input and Output:

1.Add Book

2.Display all book details

3.Search Book by author

4.Count number of books - by book name

5.Exit

Enter your choice:

Enter the isbn no:

123

Enter the book name:

Java

Enter the author name:

Bruce Eckel

1.Add Book

2.Display all book details

3.Search Book by author

4.Count number of books - by book name

5.Exit

Enter your choice:

Enter the isbn no:

124

Enter the book name:

C++

Enter the author name:


Eric Nagler

1.Add Book

2.Display all book details

3.Search Book by author

4.Count number of books - by book name

5.Exit

Enter your choice:

Enter the author name:

Henry

None of the book published by the author Henry

1.Add Book

2.Display all book details

3.Search Book by author

4.Count number of books - by book name

5.Exit

Enter your choice:

Enter the author name:

Eric Nagler

ISBN no: 124

Book name: C++

Author name: Eric Nagler

1.Add Book

2.Display all book details

3.Search Book by author

4.Count number of books - by book name

5.Exit

Enter your choice:

5
Program

import java.util.List;

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

Library library = new Library();

while (true) {

System.out.println("1.Add Book\n" +

"2.Display all book details\n" +

"3.Search Book by author \n" +

"4.Count number of books - by book name\n" +

"5.Exit\n" +

"Enter your choice:");

int choice = Integer.parseInt(scanner.nextLine());

switch (choice) {

case 1: {

System.out.println("Enter the isbn no:");

int isbn = Integer.parseInt(scanner.nextLine());

System.out.println("Enter the book name:");

String bookName = scanner.nextLine();

System.out.println("Enter author name:");

String authorName = scanner.nextLine();

Book book = new Book();

book.setIsbnno(isbn);
book.setBookName(bookName);

book.setAuthor(authorName);

library.addBook(book);

break;

case 2: {

for (Book book : library.getBookList()) {

System.out.println("ISBN no: " + book.getIsbnno());

System.out.println("Book name: " + book.getBookName());

System.out.println("Author name: " + book.getAuthor());

break;

case 3: {

System.out.println("Enter the author name:");

String authorName = scanner.nextLine();

List<Book> books = library.viewBooksByAuthor(authorName);

if (books.isEmpty()) {

System.out.println("None of the book published by the author " + authorName);

} else {

for (Book book : books) {

System.out.println("ISBN no: " + book.getIsbnno());

System.out.println("Book name: " + book.getBookName());

System.out.println("Author name: " + book.getAuthor());

break;
}

case 4: {

System.out.println("Enter the book name:");

String bookName = scanner.nextLine();

int count = library.countnoofbook(bookName);

System.out.println(count);

case 5: {

System.exit(0);

20.​Check Number Type

Samir wants to play a mind game with his father. The game is – when Sameer calls out a number his
father should say whether that number is odd or even. Since his father doesn't like Mathematics
much he needs some help to play the game.

Help his father to identify whether the called out number is odd or even by using the Lambda
Expressions.

Requirement 1: Check the Number Type

Samir's father has to identify whether the number is odd or even. By using the method
checkNumberType the given number is identified as odd or even.

Component Specification: NumberType Interface – This is a Functional Interface.

Type(Interface
Methods Responsibilities
)

public boolean This method is used to check whether


NumberType checkNumberType(int the number passed as argument is odd
number) or not.

Component Specification: NumberTypeUtility Class


Component
Type(Class) Methods Responsibilities
Name

This method is a static method


public static
Check NumberTypeUtilit which returns true if the number
NumberType
Number Type y passed as parameter is odd, else
isOdd()
return false.

Don’t create an object for NumberType. Use the lambda expression. In the NumberTypeUtility class
write the main method and perform the given steps :

Get the value for a number.

Invoke the isOdd method

Capture the object of NumberType returned by the static method.

Invoke the checkNumberType method for the number received as input from the user.

Display the result as shown in the sample output.

Sample Input 1 :

58

Sample Output 1 :

58 is not odd

Sample Input 2 :

77

Sample Output 2 :

77 is odd

Program

import java.util.Scanner;

public class NumberTypeUtility {

public static NumberType idOdd() {

return (num) -> num % 2 != 0;

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);


int num = scanner.nextInt();

if (idOdd().checkNumber(num)) {

System.out.println(num + " is odd");

} else {

System.out.println(num + " is not odd");

You might also like