You are on page 1of 94

#include<iostream>

using namespace std;


#include<string.h>

void professor(int empid1)


{
int salary;
salary=15000+(30/100)*(15000);
string dependent_name;
string dependent_DOB;
int phonenumber;
cin>>dependent_name>>dependent_DOB>>phonenumber;
cout<<salary<<dependent_name<<dependent_DOB<<phonenumber;
}
void associate_professor(int empid2)
{
int salary;
salary=120000+(20/100)*(100000);
string dependent_name;
string dependent_DOB;
int phonenumber;
cin>>dependent_name>>dependent_DOB>>phonenumber;
cout<<salary<<dependent_name<<dependent_DOB<<phonenumber;
}
void assistant_professor(int empid3)
{
int salary;
salary=100000+(10/100)*(100000);
string dependent_name;
string dependent_DOB;
int phonenumber;
cin>>dependent_name>>dependent_DOB>>phonenumber;
cout<<salary<<dependent_name<<dependent_DOB<<phonenumber;
}
void TRP(int empid4)
{
int salary;
salary=20000;
string dependent_name;
string dependent_DOB;
int phonenumber;
cin>>dependent_name>>dependent_DOB>>phonenumber;
cout<<salary<<dependent_name<<dependent_DOB<<phonenumber;
}
int main()
{
int emp1,emp2,emp3,emp4,i;
cout<<"no. of employee be";
for(i=1;i<=emp1;i++)
{
cin>>emp1;
professor(emp1);
}
for(i=1;i<=emp2;i++)
{
cin>>emp2;
associate_professor(emp2);
}
for(i=1;i<=emp3;i++)
{
cin>>emp3;
assistant_professor(emp3);
}
for(i=1;i<=emp4;i++)
{
cin>>emp4;
TRP(emp4);
}
}
YASH RAJ SINGH
19BCE0288
Q1
import java.util.Scanner;

public class Main

public static void main(String[] args) {

Scanner reader = new Scanner(System.in);

System.out.print("Enter a number: ");

int num = reader.nextInt();

if(num % 2 == 0)

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

else

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

Q2
import java.util.Scanner;

public class Main

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

int r;

double pi = 3.14, area;

Scanner s = new Scanner(System.in);

System.out.print("Enter radius of circle:");

r = s.nextInt();

area = pi * r * r;

System.out.println("Area of circle:"+area);

Q3
import java.util.Scanner;

public class Main

public static void main(String[] args) {

int year;

Scanner scan = new Scanner(System.in);

System.out.println("Enter any Year:");

year = scan.nextInt();
scan.close();

boolean isLeap = false;

if(year % 4 == 0)

if( year % 100 == 0)

if ( year % 400 == 0)

isLeap = true;

else

isLeap = false;

else

isLeap = true;

else {

isLeap = false;

if(isLeap==true)

System.out.println(year + " is a Leap Year.");

else

System.out.println(year + " is not a Leap Year.");

}
Q5
import java.util.Scanner;

public class Main

public static void main(String[] args) {

int num, count, total = 0;

System.out.println("Enter the value of n:");

Scanner scan = new Scanner(System.in);

num = scan.nextInt();

scan.close();

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

total = total + count;

System.out.println("Sum of first "+num+" natural numbers is: "+total);

}
Q6
import java.util.Scanner;

public class Main

public static void main(String[] args) {

Scanner s = new Scanner(System.in);

System.out.print("Enter number:");

int n=s.nextInt();

for(int i=1; i <= 10; i++)

System.out.println(n+" * "+i+" = "+n*i);

}
Q7
import java.util.Scanner;

public class Main

public static void main(String[] args) {

Scanner readme = new Scanner(System.in);

System.out.println("Enter Two Numbers (Press Enter after each):");

//two variables to hold numbers

double n1, n2, n3;

n1 = readme.nextDouble();

n2 = readme.nextDouble();

n3 = n1 + n2;

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

}
Q12
public class Main

public static void main(String[] args) {

int number = 502356997;

int firstDigit = 0;

int lastDigit = 0;

lastDigit = number%10;

System.out.println("Last digit: "+lastDigit);

while(number!=0) {

firstDigit = number%10;
number /= 10;

System.out.println("First digit: "+firstDigit);

Q13

public class Main

static int getSum(int n)

int sum = 0;

while (n != 0)

sum = sum + n % 10;


n = n/10;

return sum;

public static void main(String[] args)

int n = 687;

System.out.println(getSum(n));

Q11
public class Main
{

static void PrintReverseOrder(int N)

for (int i = N; i > 0; i--)

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

public static void main(String[] args)

int N = 5;

PrintReverseOrder(N);

Q10
import java.util.*;

public class Main


{

public static void main(String[])

Scanner sc = new Scanner(System.in);

int num = sc.nextInt();

int original = num;

int sum = 0;

int reversed = 0;

while(num != 0) {

int digit = num % 10;

reversed = reversed * 10 + digit;

num /= 10;

sum = original + reversed;

if(sum % 2 == 0)
System.out.println("No Odd Sum");

else

System.out.println("Odd Sum");

Q8

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

int n = sc.nextInt();
int prime=0,odd=0,even=0;

while(n!=0) {

int r = n%10;

if(r%2==0)

even++;

else

odd++;

boolean flag=true;

for(int i=2;i<=(int)Math.sqrt(r);i++)

if(r%i==0) {

flag=false;

break;

if(flag==true && r!=1)

prime++;

n=n/10;

System.out.println("Even digit "+even);

System.out.println("Odd digit "+odd);

System.out.println("Prime digit "+prime);

}
Q4
import java.util.Scanner;

public class Main

public static void main(String args[])

Scanner s = new Scanner(System.in);

System.out.print("Enter room number : ");

int a = s.nextInt();

if (a==823) {

System.out.println("Java

Programming");

else if (a==824) {

System.out.println("Python

Programming");

else {

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

Q9 NOT DONE DOUBT


22ND FEB ASSIGNMENT JAVA

Raghav Dabra

19BCE2269

Q1

package com.raghav;

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

// write your code here

// write your code here

// write your code here

Scanner s = new Scanner(System.in);

System.out.println("Enter the side of the Triangle:");

int a = s.nextInt();

double area = (Math.sqrt(3) / 4) * (a * a);

System.out.println("Area of Triangle is: " + area);


}

Q2

package com.raghav;

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

// write your code here


// write your code here

// write your code here

System.out.println("Enter number of lines");

Scanner input = new Scanner(System.in);

int num_lines = input.nextInt();

for (int i = 1; i <= num_lines; i++) {

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

System.out.print("*");

System.out.println();

}
Q3

package com.raghav;

public class Main {

public static void main(String[] args) {

// write your code here

// write your code here

for (int i = 1; i <= 5; i++) //This is the code of first part

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


System.out.print(j);

System.out.println();

for (int i = 4; i >= 1; i--) //This is the code of second part

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

System.out.print(j);

System.out.println();

}
Q4

package com.raghav;

import java.util.Scanner;

public class Main {

public static void main(String[] args) {


// write your code here
// write y
// Function to remove duplicate elements
// This function returns new size of modified
// array.

Scanner sc = new Scanner(System.in); int[] n = new int[5];


System.out.println("Enter the 5 numbers: "); for (int i = 0; i < 5;
i++)
n[i] = sc.nextInt(); int temp = 0;
for (int i = 0; i < 5; i++) {
for (int j = 1; j < (5 - i); j++) {
if (n[j - 1] > n[j]) { temp = n[j - 1]; n[j - 1] = n[j];
n[j] = temp;
}
}
}
System.out.print("Sorted Array = "); for (int i = 0; i < 5; i++)
System.out.print(n[i] + " "); sc.close();
}
}

Q5
package com.raghav;

import java.util.Scanner;

public class Main {

public static void main(String[] args) {


// write your code here
// write y
// Function to remove duplicate elements
// This function returns new size of modified
// array.
Scanner sc = new Scanner(System.in); int[] n = new int[5];
System.out.println("Enter the 5 numbers: "); for (int i = 0; i < 5; i++)
n[i] = sc.nextInt(); int temp = 0;
for (int i = 0; i < 5; i++) {
for (int j = 1; j < (5 - i); j++) {
if (n[j - 1] > n[j]) { temp = n[j - 1]; n[j - 1] = n[j]; n[j] = temp;
}

}
}
System.out.print("Distinct Array = " + n[0]); for (int i = 1; i < 5; i++) {
if (n[i] == n[i - 1]) continue;
else
System.out.print(" " + n[i]);

}
sc.close();
}
}
Q6
package com.raghav;

import java.util.Scanner;

public class Main {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in); int[] n = new int[5];
System.out.println("Enter the 5 numbers: "); for (int i = 0; i < 5; i++)
n[i] = sc.nextInt();

int ind = 4;
for (int i = 0; i < 5 / 2; i++) { int temp = n[i];
n[i] = n[ind]; n[ind] = temp; ind--;
}
System.out.print("Reverse Array ="); for (int i = 0; i < 5; i++) {
System.out.print(" " + n[i]);

}
sc.close();
}
}
Q7
package com.raghav;

import java.util.Scanner;

public class Main {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in); int[] n = new int[5];
System.out.println("Enter the 5 numbers: "); for (int i = 0; i < 5; i++)
n[i] = sc.nextInt();

System.out.println("Enter the element to be searched: "); int num = sc.nextInt();


int flag = 0;
for (int i = 0; i < 5; i++) { if (n[i] == num) {
System.out.println("Element found at position: " + (i + 1)); flag++;
break;
}
}
if (flag == 0)
System.out.println("Element not found"); sc.close();
}
}

Q8
package com.raghav;

import java.util.Scanner;

public class Main {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.println("Enter the order of the matrix: ");
int n = sc.nextInt();
int[][] ar = new int[n][n]; System.out.println("Enter the elements: "); for (int i = 0;
i < n; i++)
for (int j = 0; j < n; j++) ar[i][j] = sc.nextInt();

int flag = 0;
for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) {
if (i == j) {
if (ar[i][j] != 1) { flag++;
}
} else {
if (ar[i][j] != 0) { flag++;
}
}
}
}
if (flag > 0)
System.out.print("Not an Identity Matrix"); else
System.out.println("It is an Identity Matrix");
}
}
Q9

Without input
package com.raghav;

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

// write your code here

// write y

// Function to remove duplicate elements

// This function returns new size of modified

// array.

{//creating a matrix

int original[][] = {{1, 3, 4}, {2, 4, 3}, {3, 4, 5}};

//creating another matrix to store transpose of a matrix

int transpose[][] = new int[3][3]; //3 rows and 3 columns

//Code to transpose a matrix

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

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

transpose[i][j] = original[j][i];

System.out.println("Printing Matrix without transpose:");

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


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

System.out.print(original[i][j] + " ");

System.out.println();//new line

System.out.println("Printing Matrix After Transpose:");

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

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

System.out.print(transpose[i][j] + " ");

System.out.println();//new line

}
With input
package com.raghav;

import java.util.Scanner;

public class Main {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.println("Enter the order of the matrix: "); int r = sc.nextInt();
int c = sc.nextInt();

int[][] ar = new int[r][c];


int[][] tr = new int[c][r];

System.out.println("Enter the elements: "); for (int i = 0; i < r; i++)


for (int j = 0; j < c; j++) ar[i][j] = sc.nextInt();

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


tr[j][i] = ar[i][j];
}
}
System.out.println("Tanspose Matrix: "); for (int i = 0; i < c; i++) {
for (int j = 0; j < r; j++) System.out.print(tr[i][j] + " ");
System.out.println();
}
sc.close();
}
}
Q10

Individual sum

package com.raghav;

import java.util.Scanner;
public class Main {

public static void main(String[] args) {

// write your code here

// write y

// Function to remove duplicate elements

// This function returns new size of modified

// array.

int rows, cols, sumRow, sumCol;

//Initialize matrix a

int a[][] = {

{1, 2, 3},

{4, 5, 6},

{7, 8, 9}

};

//Calculates number of rows and columns present in given matrix

rows = a.length;

cols = a[0].length;

//Calculates sum of each row of given matrix

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

sumRow = 0;

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


sumRow = sumRow + a[i][j];

System.out.println("Sum of " + (i + 1) + " row: " + sumRow);

//Calculates sum of each column of given matrix

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

sumCol = 0;

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

sumCol = sumCol + a[j][i];

System.out.println("Sum of " + (i + 1) + " column: " + sumCol);

}
}

Matrix sum
package com.raghav;

import java.util.Scanner;

public class Main {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.println("Enter the order of the matrix: "); int r = sc.nextInt();

int[][] ar = new int[r][r];

System.out.println("Enter the elements: "); for (int i = 0; i < r; i++)


for (int j = 0; j < r; j++) ar[i][j] = sc.nextInt();

int sum = 0;
for (int i = 0; i < r; i++) { for (int j = 0; j < r; j++) {
sum += ar[i][j];
}
}
System.out.println("Sum = " + sum); sc.close();
}
}
Q11

Old code

package com.raghav;
import java.util.Scanner;

public class Main {

public static void main(String[] args) {

// write your code here

// write y

// Function to remove duplicate elements

// This function returns new size of modified

// array.

int a[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

int b[][] = {{1, 1, 1}, {1, 1, 1}, {1, 1, 1}};

int c[][] = new int[3][3];

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

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

c[i][j] = a[i][j] + b[i][j];

System.out.print(c[i][j] + " ");

System.out.println();

}
Redefined code

package com.raghav;

import java.util.Scanner;

public class Main {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.println("Enter the order of the matrix: "); int r = sc.nextInt();
int c = sc.nextInt(); int[][] a = new int[r][c];
int[][] b = new int[r][c];

System.out.println("Enter the elements of Matrix A: "); for (int i = 0; i


< r; i++)
for (int j = 0; j < c; j++) a[i][j] = sc.nextInt();
System.out.println("Enter the elements of Matrix B: "); for (int i = 0; i
< r; i++)
for (int j = 0; j < c; j++) b[i][j] = sc.nextInt();

int[][] sum = new int[r][c]; for (int i = 0; i < r; i++)


for (int j = 0; j < c; j++) sum[i][j] = a[i][j] + b[i][j];

System.out.println("Sum of Matrices = "); for (int i = 0; i < r; i++) {


for (int j = 0; j < c; j++) System.out.print(sum[i][j] + " ");
System.out.println();
}
}
}
JAVA LAB 15 MARCH EXERCISES

Name : Sarthak Choudhary

Reg. No: 19BCE0528

Question 1
Accept username, password and confirm password and perform the following
• Check if the username and password is empty
• Password should be minimum 8 characters in length
• Check if the password contains the username
• Check if the password matches the confirm password

import java.util.*;
public class Main{
public static void main(String []args){
System.out.println("Sarthak 15-03-2021");
Scanner input = new Scanner(System.in);
System.out.println("Welcome :");
String user = "";
String pwd = "";
String cpwd = "";
char c = 'y';
int f = 0;
String msg = "";
while(true)
{
msg = "";
System.out.println("Enter username:");
user = input.next();
System.out.println("Enter password:");
pwd = input.next();
System.out.println("confirm password:");
cpwd= input.next();
f=1;
if(user.length() == 0 || pwd.length() == 0
||cpwd.length() ==0 )
{
f=0;
msg += "Username, password and confirm
password should notempty!\n";
}
if(pwd.length()<8)
{
f=0;
msg += "Password length should be more than or
equal to 8.\n";
}
if
(pwd.contains(user))
{
f=0;
msg+="Password should not contain
username\n";
}
if(!pwd.equals(cpwd)) {
f=0;
msg+="Password and confirm password should
match\n";
}
if(f==1)break;
}
System.out.println("Thankyou!");
}
}

Output:
Question 2
• Read an array of 5 registration numbers that are Strings. Do not accept the
registration numbers of students who are not from BEC branch. After reading
in 5 registration numbers display the sorted registration numbers to the user.

import java.util.*;
public class Main {
public static void main (String[] args)
{System.out.println("Sarthak 19BCE0528 15-03-
2021");
Scanner sc = new Scanner(System.in);
String arr[] = new String[5];
int i = 0;
String temp = "";
System.out.println("Enter 5 Regno. :");
while (true)
{
if (i == 5)
{
break;
}
String str = sc.next();
if (str.contains("BEC"))
{
arr[i] = str;
i++;
}
else { System.out.println("Not BEC!");
}
}
for (int k = 0;
k < arr.length - 1;
k++
)
{ for (int j = 0;
j < arr.length - k - 1;
j++)
{
if (arr[j].compareTo(arr[j + 1]) > 0)
{ temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
System.out.println("The sorted list of Reg.
Number is :");
for (String k : arr)
{ System.out.print(k + " ");
}
}
}

Output:

Question 3
• Reverse every word in a string and display the result to the user.(If Input is
satish teaches Java then output should be hsitas sehcaet avaJ)

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the line : ");
String line = in.nextLine();
String words[] = line.split(" ");
String ans = "", temp ="";
for(int i=0; i< line.length(); i++)
{
if(line.charAt(i) == ' ')
{
ans += temp + " ";
temp = "";
}
else temp = line.charAt(i) + temp;
}
ans += temp + " ";
System.out.println("The reversed string is
: " + ans);
}
}
Output:

Question 4
• Count the number of times every word occurs in a given sentence

import java.util.HashMap;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String words[] = in.nextLine().split(" ");
HashMap<String, Integer> frequencyOfWords
= new HashMap<>();
for (String word : words) {
if
(frequencyOfWords.containsKey(word))frequencyOfWor
ds.replace(word, frequencyOfWords.get(word)+1);
else frequencyOfWords.put(word, 1);
}
System.out.println("---Count of words in
the given sentence ---");
for (String word :
frequencyOfWords.keySet())
{System.out.println(word + " : " +
frequencyOfWords.get(word));
}
}}

Output:

Question 5
• Count the number of vowels that is present in a string

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String sentence = in.nextLine();
int noOfVowels = 0;
for (char ch :
sentence.toLowerCase().toCharArray())
{
if (ch == 'a' || ch == 'e' || ch ==
'i' || ch == 'o' || ch == 'u')noOfVowels++;
}
System.out.println("No. of Vowels : " +
noOfVowels);
}
}

Output:

Question 6
Read a string and represent that in binary. Convert the string to hexadecimal
characters and convert the hexadecimal characters to binary.

import java.util.Scanner;
public class Main {
public static String
stringToHexadecimal(String str)
{
String hexadecimal = "";
for (char ch : str.toCharArray()) {
int ascii = ch;
String temp = "", hexaTemp;
while (ascii > 0)
{if (ascii%16 == 10)hexaTemp = "A";
else if (ascii%16 == 11)hexaTemp =
"B";
else if (ascii%16 == 12)hexaTemp =
"C";
else if (ascii%16 == 13)hexaTemp =
"D";
else if (ascii%16 == 14)hexaTemp =
"E";
else if (ascii%16 == 15)hexaTemp =
"F";
else hexaTemp =
Integer.toString(ascii%16);
temp = hexaTemp + temp;
ascii /= 16;
}
hexadecimal += temp;
}
return hexadecimal;
}public static String
hexadecimalToBinary(String str)
{String binary = "";
String hexToBinary[] =
{"0000","0001","0010","0011","0100","0101","0110",
"0111","1000","1001","1010","1011","1100","1101","
1110","1111"};
for(char ch : str.toCharArray()) {
if (ch >= 65 && ch <= 70)binary +=
hexToBinary[ch-65+10];
else binary += hexToBinary[ch-'0'];
}
return binary;
}
public static void main(String[] args)
{Scanner in = new Scanner(System.in);
String str = in.nextLine();
String hexadecimal = stringToHexadecimal(str);
System.out.println(hexadecimal);
String binary =
hexadecimalToBinary(hexadecimal);
System.out.println(binary);
}
}

Output:
Question 7
• Read username and password. Check if any three characters of the username
in the same order is present in the password. If yes then display weak
password to the user. For instance if the user name is test and password is
rest. Since three characters est is from the user name is present in the
password we should display weak password to the user

import java.util.Scanner;
public class Main {
public static int longestSubstring(char
username[], char password[])
{int m = username.length, n =
password.length;int memo[][] = new int[m + 1][n +
1];
int result = 0;
for (int i = 0; i <= m; i++) {
for (int j = 0; j <= n; j++) {
if (i == 0 || j == 0) {memo[i][j] = 0;
}
else if (username[i -1] == password[j
-1]) {
memo[i][j] = memo[i -1][j -1] + 1;
result = Math.max(result,
memo[i][j]);
}
else {memo[i][j] = 0;
}
}
}
return result;
}
public static void main(String[] args)
{Scanner in = new Scanner(System.in);
System.out.print("Enter the username : ");
char username[] =in.nextLine().toCharArray();
System.out.print("Enter the password : ");
char password[] = in.nextLine().toCharArray();
int longestSubstringLength =
longestSubstring(username, password);
if (longestSubstringLength >=
3)System.out.println("The entered password is
Weak!");
else System.out.println("The entered password
is Strong!");
}
}

Output:

Question 8
• Read an array of 5 names from the user. The input name format is Dr.Satish,
Dr.Mohan, Dr.Sendhil
• Read search name from the user. The user may enter just the name like
Satish,Mohan and Sendhil
• Check if the name entered by the user is present in the array of names
• If the name is found then display “Name Found” or else display “Name not
Found”

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the no. of names :
");
int n = in.nextInt(), flag=0;
in.nextLine();
System.out.println("---Enter the Names ---
");
String names[] = new String[n];
for (int i=0; i<n; i++)
names[i] = in.nextLine();
System.out.print("Enter the Search String
: ");
String searchString = in.nextLine();
for (String name:names)
if (name.contains(searchString)) {
flag =1;break;
}
if (flag == 1)
System.out.println("Search name
found!");
else System.out.println("Search namenot
found!");
}
}

Output:

Question 9
• Identity and implement different classes(Atleast 10 classes) along with its data
members and member functions for an University Management System for
VIT
Question 10
Create an array of Products objects – 5 product objects minimum. Products have the
following attributes
• Product id – String
• Product name – String
• Product serialnumber – Int
• Product Company – String
• Product ManufacturedDate – String 27july2020
• Product Price – int
Demonstrate the following for the array of product objects using Java code
Methods
• Display all products that are manufactured by Samsung
• Display all products manufactured between year 2012 and 2019
• Display the details of all products whose price is greater than 10000
• Display only products that has laptop in their name
Output:
Question 11
.
Use Switch case statement to perform the following in Java
Read the Country Name from the user as a string and display the Capital name for the
Country. Demonstrate how switch case can be used to display capital names of at least five
countries. If the user enters an invalid Country name then display the message “Please check
your Country Name to the User”

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Please enterthe Country
Name : ");
String isCountry = in.nextLine();
switch (isCountry)
{case "India":System.out.println("Delhi");
break;
case
"China":System.out.println("Beijing");
break;
case "Germany":System.out.println("Bonn");
break;case
"France":System.out.println("Paris");
break;case
"Spain":System.out.println("Madrid");
break;
default:System.out.println("Please check
your Country Name to the User");
break;
}
}
}

Output:

Question 12
Read an array of 5 Registration Numbers from the user. Display the count of students who
are from SCOPE and SENSE school by processing the registration numbers. The registration
numbers of students from SCOPE school will contain BCE to be part of the registration
number and the registration numbers of students from SENSE school will contain BEC to be
part of the registration numbers. If the user doesn’t enter any registration number
corresponding to SCOPE or SENSE school then display the message that “There are no
Students from SCOPE and SENSE school”.
Sample registration numbers for SCOPE School – 11BCE2333, 12BCE9877
Sample registration numbers for SENSE School – 11BEC4423, 12BEC7655

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in =new Scanner(System.in);
System.out.print("Enter the no. of
students : ");
int n = in.nextInt();
in.nextLine();
int countSCOPE = 0, countSENSE = 0;
String regNos[] = new String[n];
for(int i=0; i<n; i++)
{
System.out.print("Enter the
registration number : ");
regNos[i] = in.nextLine();
if
(regNos[i].toLowerCase().contains("bce"))countSCOP
E++;
else if
(regNos[i].toLowerCase().contains("bec"))countSENS
E++;
}
if (countSCOPE == 0 && countSENSE == 0)
System.out.println("There are no
Students from SCOPE and SENSE school");
else {System.out.println("No. of SCOPE
Students : " + countSCOPE);
System.out.println("No. of SENSE Students
: " + countSENSE);
}
}
}
Output:
Question 13
Read a sentence from the user and display the count of the word VIT used in the
sentence. If the word VIT is not present in the sentence then display the message “No such
word in the Sentence” Message

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String[] strings = in.nextLine().split("
");
int countVIT = 0;
for (String str : strings)
if(str.equals("VIT"))countVIT++;
if(countVIT >
0)System.out.println("Count : " + countVIT);
else System.out.println("No such word
in the Sentence");
}
}
Output:

Question 14
Write a Method that receives a jagged array containing marks scored by a student in various
semesters. For instance the marks in the jagged array are as shown below
40 80 30 99
20 55
31 44 55 67
87 45 66
Receive the jagged array in a method and write code to display the number of subjects the
student has passed (marks >= 40) and the number of subjects the student has failed (marks
<40). Use an enhanced for loop in the code
import java.util.Scanner;
public class Main {
public static void func(int marks[][])
{
int passed = 0, failed = 0;
for (int[] row : marks)
{
for(int mark : row)
{
if (mark >= 40)passed++;
else failed++;
}
}System.out.println("No. of subjects
passed : " + passed);
System.out.println("No. of subjects failed
: " + failed);
}
public static void main(String[] args)
{
int marks[][] = {{40, 10, 30, 99}, {20,
15}, {21, 66, 55, 67}, {87, 45, 66}};
func(marks);
}
}
Output:
Question 15
Consider the class for a mobile phone given below
Data Members
o Model Name
o Company Name
o Price
o Year of Manufacture
Methods
o set_mobileDetails() - Method to set data for the object
o sort_mobileDetails() - Method receives an array of mobile
phone objects and
sorts them
o display_mobileDetails() – display the data inside the array
of objects.
Create an array of five mobile phone objects by reading the
data from the user. Use the static
method sort_mobileDetails() to read the array of mobile
objects and sort them according to
the company name. Display the sorted array of objects using
the display_mobileDetails()
Method
Output:

Question 16
Consider the class for a course given below
Data Members
o Course Name
o Course ID
o Course Type (UE, PE or PC)
o Offered By (School that offers the course)
Methods
o Set_courseDetails() - Method to set data for the object
o search_courseDetails() - Method receives an array of course objects and
searches them
o display_courseDetails() – display the count of courses based on course type.
Create an array of five course objects by reading the data from the user. Use the static method
search_courseDetails() to read the array of course objects and count the number of UE, PE
and PC courses in the array of course objects. Display the count of UE, PE and PC courses
using the display_courseDetails() method.
Output:
Question 17
Sphere, Cylinder, Cone and Cube are classes that inherit from the abstract class shape. Shape
has an abstract method compute_volume(). Demonstrate with code on how dynamic
polymorphism and upcasting can be used to compute the volume of the different shapes.
Output:

Question 18
Identify the issues with the given code and rewrite the code such that the details of the
professor is displayed by the display_professor() method.
public class javalabclass {
public static void main(String[] args) {
professor satish = new
professor("satish","vellore","111","a06");
satish.display_professor();
}
}
final class person
{
protected String name;
protected String address;
public final void display_vitadd();
}
class faculty extends person
{
public String empid;
public void display_faculty() {
System.out.println(name+address+empid);
}
}
class professor extends faculty , extends person
{
public String cabinno;
public void display_professor() {
System.out.println(name+address+empid+cabinno);
}

CORRECTED CODE:

public class Main {


public static void main(String[] args)
{professor satish = new
professor("satish","vellore","111","a06");
satish.display_professor();
}
}
abstract class person{
protected String name;
protected String address;
public abstract void display_vitadd();
}
class faculty extends person{
public String empid;
public faculty(String empid, String name,
String address)
{this.empid = empid;
this.name = name;
this.address = address;
}
public void display_vitadd()
{System.out.println(name+address+empid);
}
}
class professor extends faculty{
public String cabinno;
public professor(String name, String address,
String empid, String cabinno)
{super(empid, name, address);
this.cabinno = cabinno;
}
public void display_professor()

{System.out.println(name+address+empid+cabinno);
}
}

Output:
JAVA 22 MARCH EXERCISES
Name:Sarthak Choudhary
Reg. No : 19BCE0528
Q1

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Customer c[] = new Customer[10];
Scanner input = new Scanner(System.in);
System.out.println("Enter names and
favourite food for " + c.length+ " people:");
for (int i = 0; i < c.length; i++)
{
String name = input.nextLine();
String food = input.nextLine();
c[i] = new Customer(name, food);
}
System.out.print("Enter fav food: ");
String favFood = input.nextLine();
input.close();
Customer.findCommons(c, favFood);
}
}
class Customer {
private String name;
private String favFood;
public Customer(String name, String favFood) {
this.name = name;
this.favFood = favFood;
}
public static void findCommons(Customer
customers[], String food) {
System.out.println("\nCustomers who have "
+ food + " as their favourite food:");
for (int i = 0; i < customers.length; i++)
{
if (customers[i].favFood.equals(food))
{
System.out.println(customers[i].name);
}
}
}
}

Output:

Q2. Read an array of integers in your overloaded main method and determine how many
numbers are prime numbers and composite numbers.
Output:
Q3.

import java.util.Scanner;
public class Main {public static void
main(String[] args) {
Scanner input = new
Scanner(System.in);System.out.println("\nEnter
faculty name, their id, and number of their
degrees:");String name = input.nextLine();String
id = input.nextLine();int n =
Integer.parseInt(input.nextLine());Faculty f1 =
new Faculty(name,
id);f1.display_faculty_data();for (int i = 0; i <
n; i++) {System.out.println("Enter degree name,
awarded year, and by which university:");String
dname = input.nextLine();String dyear =
input.nextLine();String duni =
input.nextLine();f1.new Degree(dname, dyear,
duni).display_degree_details();}
input.close();}}class Faculty {private String
name;private String empid;public Faculty(String
name, String empid) {this.name = name;this.empid =
empid;}public void display_faculty_data()
{System.out.println("\n----------------------
");System.out.println("Faculty name: " + name +
"\nFaculty id: " +empid);System.out.println("-----
-----------------\n");}public class Degree {String
degree_name;String awarded_year;String
awarded_by_university;public Degree(String name,
String year, String uni) {degree_name =
name;awarded_year = year;awarded_by_university =
uni;}public void display_degree_details()
{System.out.println("\n----------------------
");System.out.println(degree_name + " " +
awarded_year + " " +awarded_by_university);
System.out.println("----------------------
\n");}}}
Output:

Q4:

import java.util.Scanner;

class Faculty {
public static class EligibleLeave {
public static int EL = 12, ML = 20, CL =
10; public static void displayLeaveCategories() {
System.out.println("Eligible Leave(
EL=" + EL + ", ML=" + ML + ", CL=" + CL+")");
}
}
public int id; public String name;

public void display() {


System.out.print("Id = " + this.id + ",
"); System.out.print("Name = " + this.name + ",
"); EligibleLeave.displayLeaveCategories();
}
}

public class Main {


public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the no. of
faculties : "); int n = in.nextInt();
in.nextLine();

Faculty faculties[] = new Faculty[n]; for


(int i=0; i<n; i++) {
faculties[i] = new Faculty();
System.out.println("--- Faculty " +
(i+1) + " ---"); System.out.print("ID : ");
faculties[i].id = in.nextInt();
in.nextLine(); System.out.print("Name : ");
faculties[i].name = in.nextLine();
}

System.out.println();
for (Faculty faculty : faculties)
faculty.display();
}
}

Output:
Q5. Create an array of 5 3d shape objects. Compute the volume of the fiveshapes using the
concept of upcasting and dynamic polymorphism.

import java.util.Scanner;

abstract class Shape3D { public String shape;


public float volume;

abstract void computeVolume();

void displayVolume() {
System.out.println("The volume of " +
this.shape + " is : " + this.volume);
}
}

class Cube extends Shape3D { public int side;

public Cube() { this.shape = "Cube";


}

public void computeVolume() {


Scanner in = new Scanner(System.in);
System.out.print("Enter the side of Cube : ");
this.side = in.nextInt();
this.volume = side*side*side;
}
}

class Cuboid extends Shape3D { public int length;


public int breadth; public int height;

public Cuboid() { this.shape = "Cuboid";


}

public void computeVolume() {


Scanner in = new Scanner(System.in);
System.out.print("Enter the length of Cuboid : ");
this.length = in.nextInt();
System.out.print("Enter the breadth of
Cuboid : "); this.breadth = in.nextInt();
System.out.print("Enter the height of Cuboid : ");
this.height = in.nextInt();
this.volume = length*breadth*height;
}
}

class Cylinder extends Shape3D { public int


radius;
public int height;

public Cylinder() { this.shape = "Cylinder";


}

public void computeVolume() {


Scanner in = new Scanner(System.in);
System.out.print("Enter the radius of Cylinder :
"); this.radius = in.nextInt();
System.out.print("Enter the height of
Cylinder : ");
this.height = in.nextInt();
this.volume = (float)
(2*3.14*radius*radius*height);
}
}

public class Main {


public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter no. of shapes : "); int n
= in.nextInt();
in.nextLine();
Shape3D shape3Ds[] = new Shape3D[n]; for
(int i=0; i<n; i++) {
System.out.print("Which Shape you want
to calculate volume? (Cube | Cuboid | Cylinder) :
");
String type = in.nextLine();
if (type.toLowerCase().equals("cube"))
shape3Ds[i] = new Cube();
else if
(type.toLowerCase().equals("cuboid")) shape3Ds[i]
= new Cuboid();
else if
(type.toLowerCase().equals("cylinder"))
shape3Ds[i] = new Cylinder();
shape3Ds[i].computeVolume();
shape3Ds[i].displayVolume();
}
}
}

OutpuT:

Q6. Create a superclass with variable a (initialize a with a parameterizedconstructor) . A


subclass extends superclass and contains variableb(initialize b with a parameterized
constructor) A subsubclass extendssubclass and contains variable c(initialize c with a
parameterizedconstructor). Create an object for subsubclass and demonstrate how all
thesuperclass variables are initialized.

import java.util.Scanner;

class SuperClass { public int a;


public SuperClass(int a) { this.a = a;
}
}

class SubClass extends SuperClass { public int b;


public SubClass(int a, int b) { super(a);
this.b = b;
}
}

class SubSubClass extends SubClass { public int c;


public SubSubClass(int a, int b, int c) {
super(a, b);
this.c = c;
}

@Override
public String toString() {
return "SubSubClass{" + "a=" + a + ", b="
+ b + ", c=" + c + '}';
}
}

public class Main {


public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the value of a :
"); int a = in.nextInt(); System.out.print("Enter
the value of b : "); int b = in.nextInt();
System.out.print("Enter the value of c : "); int c
= in.nextInt();
SubSubClass subSubClass = new
SubSubClass(a, b, c);
System.out.print("SubSubClass : " + subSubClass);
}
}

Output:
Q7. Create a class student and class guardian. Class student has a composition relationship
with guardian class. A student can have many guardians (Max3). For any given student
registration number display all the guardian details.

import java.util.ArrayList; import


java.util.Scanner;

class Guardian {
public String name; public String address;
public String phoneNo;
}

class Student {
public String name; public String regNo;
public ArrayList<Guardian> guardians = new
ArrayList<>();

public static void displayGuardians(Guardian


guardians[]) { for (int i=0; i<guardians.length;
i++) {
System.out.println("--- Guardian" + (i+1)
+ "---"); System.out.println("Guardian Name : " +
guardians[i].name); System.out.println("Guardian
Phone No. : " + guardians[i].phoneNo);
System.out.println("Guardian Address : " +
guardians[i].address);
}
}

public static Student searchStudent(Student


students[], String regNo) { for (Student student :
students)
if
(student.regNo.toLowerCase().equals(regNo.toLowerC
ase())) return student;
return null;
}
}
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the no. of
students : "); int n = in.nextInt();
in.nextLine();
Student students[] = new Student[n]; for
(int i=0; i<n; i++) {
System.out.println("--- Student " +
(i+1) + "---"); students[i] = new Student();
System.out.print("Enter Student Name : ");
students[i].name = in.nextLine();
System.out.print("Enter Student
Registration No. : "); students[i].regNo =
in.nextLine();
System.out.print("Do you want to enter
Guardian Details? (Y/N) : "); char ch =
in.next().charAt(0);
in.nextLine(); int j=1;
while (ch == 'y' || ch == 'Y') {
Guardian guardian = new Guardian();
if (students[i].guardians.size() <
3) { System.out.println("--- Guardian " + (j) + "-
--"); System.out.print("Enter the Guardian Name :
"); guardian.name = in.nextLine();
System.out.print("Enter the Guardian Address : ");
guardian.address = in.nextLine();
System.out.print("Enter the
Guardian Phone number : "); guardian.phoneNo =
in.nextLine();
students[i].guardians.add(guardian);
j++;
System.out.print("Do you want
to enter details of Guardians? (Y/N) : ");
ch = in.next().charAt(0);
in.nextLine();
}
else {
ch = 'N';
System.out.println("Sorry!
only max of 3 can be entered.");
}
}
}
System.out.println();
System.out.print("Enter the Registration
Number to be searched : "); String regNoToSearch =
in.nextLine();
Student student =
Student.searchStudent(students, regNoToSearch); if
(student != null) {
System.out.println("Student Name : " +
student.name); System.out.println("Student
Registration Number : " + student.regNo); for (int
i=0; i<student.guardians.size(); i++) {
System.out.println("--- Guardian "
+ (i+1) + " ---"); System.out.println("Guardian
Name : " + student.guardians.get(i).name);
System.out.println("Guardian Address : " +
student.guardians.get(i).address);
System.out.println("Guardian Phone Number : " +

student.guardians.get(i).phoneNo);
}
}
}
}
Output:

Q8.Read an array of 5 names from the user. The input name format is Dr.Satish,Dr.Mohan,
Dr.Sendhil.Read search name from the user. The user may enter just the name
likeSatish,Mohan and Sendhil.Check if the name entered by the user is present in the array
of namesIf the name is found then display “Name Found” or else display “Name notFound”.
import java.util.Scanner;

public class Main {


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

System.out.print("Enter no. of names : ");


int n = in.nextInt(), flag=0;
in.nextLine();

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


String names[] = new String[n];
for (int i=0; i<n; i++) names[i] =
in.nextLine();

System.out.print("Enter the Search String


: "); String searchString = in.nextLine();
for (String name:names)
if (name.contains(searchString)) {
flag = 1;
break;
}
if (flag == 1)
System.out.println("Search name
found!"); else
System.out.println("Search name not
found!");
}
}

Output:
Q9. Read an array of five car brand names from the user. Pass the array of
brandnames to a static method by name brandSort() . Within the methodbrandSort()
sort the brand names in the descending order. Display the sortednames to the user.
For instance if the user enters Kia, Maruti, Toyota, Hyundai,Nissan then the output
should Toyota, Nissan, Maruti, Kia, Hyundai (Do not use any inbuilt methods for
Sorting the array)

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String brands[] = new String[5];
System.out.println("\nEnter 5 car brand
names:");
for (int i = 0; i < brands.length; i++) {
brands[i] =
input.nextLine();}brandSort(brands);
}
public static void brandSort(String arr[]) {
for (int i = 0; i < arr.length - 1; i++){
for (int j = 0; j < arr.length-1-i;
j++){
if (arr[j].compareTo(arr[j+1]) <
0){
String temp = arr[j];arr[j] =
arr[j+1];
arr[j+1] = temp;
}
}
}
System.out.println(" Sorted names in
descending order ");
for (String brand: arr) {
System.out.println(brand);
}
}
}
Output:

Q10. An employee has multiple instances of addresses. Every address has datamembers
like Street, City, District, State, Country and Zip Code. Demonstrateusing Nested classes
how you will track the multiple address instances for anemployee. The code should display
the multiple address objects (nested classobjects) for any given employee.

import java.util.ArrayList; import


java.util.Scanner;

class Employee {
public static class Address { public String
street; public String city; public String
district; public String state; public String
country; public String zipCode;

public Address(String street, String city,


String district, String state, String country,
String zipCode) {
this.street = street; this.city =
city; this.district = district; this.state =
state; this.country = country; this.zipCode =
zipCode;
}

@Override
public String toString() {
return street + ", " + city + ", " +
district + ", " + state + ", " + country + " - " +
zipCode + ".";
}
}
public String name;
public ArrayList<Address> addresses = new
ArrayList<>();

public static Employee searchEmployee(Employee


employees[], String name) { for (Employee employee
: employees)
if
(employee.name.toLowerCase().equals(name.toLowerCa
se())) return employee;
return null;
}
}

public class Main {


public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of
Employees : "); int noOfEmployees = in.nextInt();
in.nextLine();
Employee employees[] = new
Employee[noOfEmployees]; String street, city,
district, state, country, zipCode; for (int i=0;
i<noOfEmployees; i++) {
employees[i] = new Employee();
System.out.print("Enter the employee name : ");
employees[i].name = in.nextLine();
System.out.print("Do you want to add
address? (Y/N) : "); char ch =
in.next().charAt(0);
in.nextLine();
while (ch == 'y' || ch == 'Y') {
System.out.print("Enter the Street : "); street =
in.nextLine(); System.out.print("Enter the City :
"); city = in.nextLine(); System.out.print("Enter
the District : "); district = in.nextLine();
System.out.print("Enter the State : ");
state = in.nextLine();
System.out.print("Enter the Country : "); country
= in.nextLine(); System.out.print("Enter the Zip
Code : "); zipCode = in.nextLine();
employees[i].addresses.add(new
Employee.Address(street, city, district, state,
country, zipCode));
System.out.print("Do you want to
add another address? (Y/N) : "); ch =
in.next().charAt(0);
in.nextLine();
}
}
System.out.println();
System.out.print("Enter the Employee name
to get address : "); String employeeName =
in.nextLine();
Employee employee =
Employee.searchEmployee(employees, employeeName);
if (employee != null) {
System.out.println("Employee Name : "
+ employee.name); for (int i=0;
i<employee.addresses.size(); i++)
System.out.println("Address " +
(i+1) + " : " + employee.addresses.get(i));
}
else {
System.out.println("Sorry! Employee
not present.");
}
}
}

Output:
Q11. A department is considered to exist in multiple locations. Each location isdefined by
attributes like locationId, locationName, longitude, latitude.Location is maintained as nested
class in department. Write a Java programthat displays the details of the various location
instances(nested class objects)for a given department name.

import java.util.ArrayList; import


java.util.Scanner;

class Department {
public static class Location { public int
locationId; public String locationName;
public float longitude, latitude;

public Location(int locationId, String


locationName, float longitude, float latitude) {
this.locationId = locationId;
this.locationName = locationName;
this.longitude = longitude; this.latitude =
latitude;
}

@Override
public String toString() {
return "Location{" + "locationId=" +
locationId + ", locationName='" + locationName
+
'\'' + ", longitude=" +
longitude + ", latitude=" + latitude + '}';
}
}
public String name;
public ArrayList<Location> locations = new
ArrayList<>();

public static Department


searchDepartment(Department departments[], String
name) { for (Department department : departments)
if
(department.name.toLowerCase().equals(name.toLower
Case())) return department;
return null;
}
}

public class Main {


public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of
Department : "); int noOfDepartments =
in.nextInt();
in.nextLine();
Department departments[] = new
Department[noOfDepartments]; int id;
String locationName;
float longitude, latitude;
for (int i=0; i<noOfDepartments; i++) {
departments[i] = new Department();
System.out.print("Enter the Department name : ");
departments[i].name = in.nextLine();
System.out.print("Do you want to add
location? (Y/N) : "); char ch =
in.next().charAt(0);
in.nextLine();
while (ch == 'y' || ch == 'Y') {
System.out.print("Enter the Location ID : "); id =
in.nextInt();
in.nextLine();
System.out.print("Enter the
Location Name : "); locationName = in.nextLine();
System.out.print("Enter the Longitude : ");
longitude = in.nextFloat();
in.nextLine();
System.out.print("Enter the
Latitude : "); latitude = in.nextFloat();
in.nextLine();
departments[i].locations.add(new
Department.Location(id, locationName, longitude,
latitude));
System.out.print("Do you want to
add another location? (Y/N) : "); ch =
in.next().charAt(0);
in.nextLine();
}
}
System.out.println();
System.out.print("Enter the Department
name to get location : "); String departmentName =
in.nextLine();
Department department =
Department.searchDepartment(departments,
departmentName); if (department != null) {
System.out.println("Department Name :
" + department.name); for (int i=0;
i<department.locations.size(); i++)
System.out.println("Location " +
(i+1) + " : " + department.locations.get(i));
}
else {
System.out.println("Sorry! Department
not present.");
}
}
}
Output:

You might also like