0% found this document useful (0 votes)
360 views19 pages

COMSCPBTech498771rObjrPr - Second Module Pgms

The document lists 5 programs related to strings, string buffers, arrays, and matrices in Java. Program 1 performs string operations like getting characters, checking for equality, concatenating, etc. Program 2 inserts values into a string buffer. Program 3 checks coupon numbers for palindromes to identify winners of a lucky dip. Program 4 uses matrices to track books and magazines read by a student each month and calculates totals. Program 5 multiplies matrices of equipment lists for 2 softball teams by cost to calculate total equipment costs.

Uploaded by

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

COMSCPBTech498771rObjrPr - Second Module Pgms

The document lists 5 programs related to strings, string buffers, arrays, and matrices in Java. Program 1 performs string operations like getting characters, checking for equality, concatenating, etc. Program 2 inserts values into a string buffer. Program 3 checks coupon numbers for palindromes to identify winners of a lucky dip. Program 4 uses matrices to track books and magazines read by a student each month and calculates totals. Program 5 multiplies matrices of equipment lists for 2 softball teams by cost to calculate total equipment costs.

Uploaded by

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

List of module 2 programs

1. Create two Strings str1 and str2, using String functions find the
a) Character at index 5 for str1
b) Check if the str2 starts with “k”
c) Find the length of str1 and str2
d) Find if str1 and str2 are equal
e) Find the substring of str1 for index 1:4
f) Find the substring of str2 for index 2:6
g) Use getchars function to add characters to a character array dst and display
it( dst[0] and dst[1] have “a”,”b” respectively).
h) Concatenate str2 with presidency University

public class StringExample


{
public static void main(String[] args)
{
String str1 = "Computer";
String str2= "Science";
System.out.println(str1.charAt(5));
System.out.println(str2.startsWith("k"));
System.out.println(str1.length());
System.out.println(str2.length());

if(str1.equals(str2))
{
System.out.println("the strings are equal");
}
else
{
System.out.println("Strings are not equal");}
String s2 = str1.substring(1,4);
String s3 = str2.substring(2,6);
System.out.println("The SubString of str1"+s2);
System.out.println("The SubString of str2"+s3);
String s4;
s4 = str1.concat("Presidency University");
System.out.println("The concatination of 2 strings are"+s4);

char[] dst=new char[20];


dst[0]='a';
dst[1]='b';
dst[2]='c';

str1.getChars(0,4,dst,0);
System.out.println(dst);
}
}
2) Create a String “ScienceTechnologyusing StringBuffer, Perform the following
operations
a)insert string “for” at location 7
b) insert 0 at location 2
c) insert “true” at location 3
d) insert a character array

import java.io.*;
public class Stringexample
{
public static void main(String[] args)
{
StringBuffer s = new StringBuffer("ScienceTechnology");
s.insert(7, "for");
System.out.println(s);
s.insert(0, 2);
System.out.println(s);
s.insert(3, "true");
System.out.println(s);

char str_arr[] = { 'c', 'o', 'm','p', 'u', 't', 'e', 'r' };

s.insert(2, str_arr);
System.out.println(s);
}
}

3. The company has announced a lucky dip for the employees for Diwali
festival. It is released coupons with unique number printed on it. The criteria
to win the prize are the first and last number should match and there is a
chance of winning only 3 prizes. On the festival day, 5 employees with
different coupon id entered into the final round. Now identify the 3 employees
who will win the lucky dip out of 5.

Palindrome Definition:
If the number is equal to it's reversed number, then the given number is a palindrome
number.
For example, 121 is a palindrome number while 12 is not.
public class PallindromeExample {
public static void main(String[] args) {

//array of numbers to be checked


int numbers[] = new int[]{121,13,34,11,22};

//iterate through the numbers


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

int number = numbers[i];


int reversedNumber = 0;
int temp=0;

//reverse the number


while(number > 0){
temp = number % 10;
number = number / 10;
reversedNumber = reversedNumber * 10 + temp;
}

if(numbers[i] == reversedNumber)
System.out.println("The employee with coupon
number"+" "+ numbers[i]+" "+ "won the lucky dip");
else
System.out.println("The employee with coupon number"+"
"+numbers[i] +" "+"didn’t won the lucky dip");

}
}
Two Dimensional Array [Matrix Addition]

4. A student visits the university library and in the month of June, July, and
August he read fiction and non-fiction books, and magazines, both in paper
copies and online. You want to keep track of how many different types of
books and magazines he read, and store that information in matrices. Here is
the information below:

June
PAPER ONLINE
Fiction 2 4
Non-fiction 3 1
Magazines 4 5
July
PAPER ONLINE
Fiction 3 2
Non-fiction 1 1
Magazines 5 3

August
PAPER ONLINE
Fiction 1 3
Non-fiction 2 3
Magazines 4 6

Matrix form :(June) Matrix form:(July) Matrix form:(August)


Solution for Matrix Addition:
import java.util.Scanner;

class AddTwoMatrix
{
public static void main(String args[])
{
int m, n, i, j;
Scanner in = new Scanner(System.in);

System.out.println("Enter the number of rows and columns of matrix");


m = in.nextInt();
n = in.nextInt();

int first[][] = new int[m][n];


int second[][] = new int[m][n];
int third[][]=new int[m][n];
int sum[][] = new int[m][n];

System.out.println("Enter the books which the student read in the month of June and it's
matrix form is");

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


for (j = 0; j < n; j++)
first[i][j] = in.nextInt();

System.out.println("Enter the books which the student read in the month of July and it's
matrix form is");

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


for (j = 0; j < n; j++)
second[i][j] = in.nextInt();

System.out.println("Enter the books which the student read in the month of August and it's
matrix form is");

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


for (j = 0; j < n; j++)
third[i][j] = in.nextInt();

//Sum of matrices is:


for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
sum[i][j] = first[i][j] + second[i][j]+third[i][j];

System.out.println("Total number of differ


rent types of books and magazines he read is");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
System.out.print(sum[i][j]+"\t");

System.out.println();
}
System.out.println("Total 6 paper fiction books the student has read");
System.out.println("Total 9 online fiction books the student has read");
System.out.println("Total 6 paper non-fiction books the student has read");
System.out.println("Total 5 online non- fiction books the student has read");
System.out.println("Total 13 papers the student has read");
System.out.println("Total 14 online magzines the student has read");

}
}

Output:
Enter the number of rows and columns of matrix
3
2
Enter the books which the student read in the month of June and it's matrix form is
2
4
3
1
4
5
Enter the books which the student read in the month of July and it's matrix form is
3
2
1
1
5
3
Enter the books which the student read in the month of August and it's matrix form is
1
3
2
3
4
6
Total number of different types of books and magazines he read is
6 9
6 5
13 14
Total 6 paper fiction books the student has read
Total 9 online fiction books the student has read
Total 6 paper non-fiction books the student has read
Total 5 online non- fiction books the student has read
Total 13 papers the student has read
Total 14 online magzines the student has read

5. Two softball teams submit equipment lists to their sponsors. The equipment
lists for Team A and Team B are as follows:

Teams Balls Bats Gloves

Team -A 12 45 15

Team -B 15 38 17

Equipment Name Cost

Balls 9$

Bats 80$

Gloves 60$

Find the total cost of the equipment for each team.


Solution for Matrix Multiplication:
import java.util.Scanner;

class MatrixMultiplication
{
public static void main(String args[])
{
int m, n, p, q, sum = 0, c, d, k;

Scanner in = new Scanner(System.in);


System.out.println("Enter the number of rows and columns of first matrix");
m = in.nextInt();
n = in.nextInt();

int first[][] = new int[m][n];

System.out.println("Enter the equipment lists for Team-A");

for (c= 0; c < m; c++)


for (d = 0; d < n; d++)
first[c][d] = in.nextInt();

System.out.println("Enter the number of rows and columns of second matrix");


p = in.nextInt();
q = in.nextInt();

if (n != p)
System.out.println("The matrices can't be multiplied with each other.");
else
{
int second[][] = new int[p][q];
int multiply[][] = new int[m][q];

System.out.println("Enter the equipment lists for Team-B");

for (c = 0; c < p; c++)


for (d = 0; d < q; d++)
second[c][d] = in.nextInt();

for (c = 0; c < m; c++)


{
for (d = 0; d < q; d++)
{
for (k = 0; k < p; k++)
{
sum = sum + first[c][k]*second[k][d];
}
multiply[c][d] = sum;
sum = 0;
}
}

System.out.println("The total cost of the equipment for Team-A and Team-B are:");

for (c = 0; c < m; c++)


{
for (d = 0; d < q; d++)
System.out.print(multiply[c][d]+"\t");

System.out.print("\n");
}

}
}
}

Output:
Enter the number of rows and columns of first matrix
2
3
Enter the equipment lists for Team-A
12
45
15
15
38
17
Enter the number of rows and columns of second matrix
3
1
Enter elements of second matrix
9
80
60
The total cost of the equipment for Team-A and Team-B are:
4608
4195
6. Mr. John has joined the CGI Company as Database Administrator and his major
role is to maintain the Employee database which includes Employee Id, Employee
Name, Age and Employee Salary. The criteria for maintaining is that he needs to
store all the records in one single table. How Mr. John is going to access all the
records which he has stored?

Solution:
import java.util.Scanner;

class Employee
{
int Id;
String Name;
int Age;
long Salary;

void GetData() // Defining GetData()


{

Scanner sc = new Scanner(System.in);

System.out.print("\n\tEnter Employee Id : ");


Id = sc.nextInt();

System.out.print("\n\tEnter Employee Name : ");


Name = sc.next();

System.out.print("\n\tEnter Employee Age : ");


Age = sc.nextInt();

System.out.print("\n\tEnter Employee Salary : ");


Salary = sc.nextLong();

void PutData() // Defining PutData()


{
System.out.print("\n\t" + Id + "\t" +Name + "\t" +Age + "\t" +Salary);
}

public static void main(String args[])


{

Employee[] Emp = new Employee[3];


int i;

for(i=0;i<3;i++)
Emp[i] = new Employee(); // Allocating memory to each object

for(i=0;i<3;i++)
{
System.out.print("\nEnter details of "+ (i+1) +" Employee\n");

Emp[i].GetData();
}

System.out.print("\nDetails of Employees\n");
for(i=0;i<3;i++)
Emp[i].PutData();

}
}

Output:
Enter details of 1 Employee

Enter Employee Id : 34

Enter Employee Name : Geetha

Enter Employee Age : 23

Enter Employee Salary : 45000

Enter details of 2 Employee

Enter Employee Id : 35

Enter Employee Name : Seetha

Enter Employee Age : 24

Enter Employee Salary : 50000

Enter details of 3 Employee

Enter Employee Id : 25

Enter Employee Name : Vineetha


Enter Employee Age : 28

Enter Employee Salary : 55000

Details of Employees

34 Geetha 23 45000
35 Seetha 24 50000
25 Vineetha28 55000

7) In Presidency University, all the lecturers of CSE has to report to the head
of the department, where HOD is the base class with the data members as
college name and work() method. The sub class is the Lecturers who are
teaching different subjects will extends the properties from the base class.

class HOD{

String collegeName = "Presidency University";


void work(){
System.out.println(“Teaching”);
}
}
public class JavaLecturer extends HOD{
String mainSubject = "OOPS with JAVA";
public static void main(String args[]){
JavaLecturer obj = new JavaLecturer ();
System.out.println(obj.collegeName);
System.out.println(obj.mainSubject);
obj.work();
}
}

8) Create a base class Area with data members x(dimension) and


y(dimension). Create class Square and Rectangle and compute the area of
square and rectangle by using the data members of the class Area. Hint:
Inheritance, use switch case to find the area of square or rectangle.

package javaapplication6;
import java.util.Scanner;
class Area
{
double x=0.0;
double y=0.0;

public void calculateArea()


{
 System.out.println("Invoking specific methods on their objects");
}
}

class Square extends Area


{
    Scanner sc=new Scanner(System.in);
    public
    void calculateArea()
  {
    super.calculateArea();
    System.out.println("Initial value of x is " + super.x);
    System.out.println("Enter Value of X");
    x=sc.nextInt();
    System.out.println("the area of the square is " +Math.pow(x, 2)+ " sq units ");
  
  }
}
class circle extends Area

    Scanner sc=new Scanner(System.in);
    public
    void calculateArea()
  {
super.calculateArea();
        System.out.println("Initial value of x is " + super.x);
        System.out.println("Enter Value of radius ");
x=sc.nextInt();
        System.out.println("the area of the rectangle is " + 3.14*x*x + "sq units");
  }
}
class Rectangle extends Area

    Scanner sc=new Scanner(System.in);
    public
    void calculateArea()
  { 
        System.out.println("Initial value of x and y are " + super.x +" and "+ super.y);
System.out.println("Enter Value of X");
x=sc.nextInt();
        System.out.println("Enter Value of Y");
        y=sc.nextInt();
        System.out.println("the area of the triangle is " + x*y + "sq units");
  }
}

class JavaApplication6
{
     public static void main(String args[])
{
      
            Scanner sc=new Scanner(System.in);
            System.out.println("Enter 1. To Find Area of Square");
            System.out.println("Enter 2. To Find Area of Rectangle");
            System.out.println("Enter 3. To Find Area of Circle");
            int Choice=sc.nextInt();
            switch(Choice)
      {
                case 1:  Square a = new Square();
                         a.calculateArea();
                         break;

                case 2:  Rectangle b = new Rectangle();


                         b.calculateArea();
                         break;
         
                case 3:  circle c = new circle();
                         c.calculateArea();
                         break;
    }
}
}

9. The marklist of the students is with the teacher. One of the student has
asked to share her marks. The teacher is worried that if she shares the marks
the student may edit. So help her to share the marks with the students without
letting her to edit
Hint: Final keyword

class Teacher
{
final int marks=75;
void show()
{
System.out.println("Maximum of marks for ech subject is 50");
}
}
class Student extends Teacher
{
void show()
{
Scanner input=new Scanner(System.in);
super.show();
System.out.println("Student:"+marks);
}
}
class finalKey
{
public static void main(String args[])
{
Teacher t=new Teacher();
Teacher s=new Student();
t.show();
s.show();
}
}

10)A delivery agent is talking to the customer who is working in one


organization. The delivery agent want to know the address to deliver the
product. The customer gives the address of both organization and home.
The delivery agent want to store these address in his application but there
is only one column. Help him to store both addresses without override the
values.
Hint: Run time Polymorphism

class Customerorganisation
{
void address()
{
System.out.println("Rajankunte,Bengaluru");
}
}

class Customerhome extends organisation


{
void address()
{
System.out.println("Hebbal,Bengaluru");
}
}

class methodOverride
{
public static void main(String args[])
{
customerorganisation o=new customerorganisation();
customerorganisation e=new customerhome();
o.address();
e.address();
}
}

You might also like