0% found this document useful (0 votes)
103 views

Java Gaand Mardi

The document contains code for multiple questions related to Java concepts like interfaces, packages, exception handling, multithreading, I/O streams and collections. For question 1, the code defines an interface with encrypt and decrypt methods and a CaesarCipher class that implements these methods to perform encryption and decryption of strings. For question 2, the code defines classes to check for prime numbers and find twin prime numbers.

Uploaded by

mic joseph
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
103 views

Java Gaand Mardi

The document contains code for multiple questions related to Java concepts like interfaces, packages, exception handling, multithreading, I/O streams and collections. For question 1, the code defines an interface with encrypt and decrypt methods and a CaesarCipher class that implements these methods to perform encryption and decryption of strings. For question 2, the code defines classes to check for prime numbers and find twin prime numbers.

Uploaded by

mic joseph
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 70

BHAVAY ARORA

19BIT0355

INTERFACE AND PACKAGES-


Q1.
Q1
CODE:
import java.util.*;
interface EncryptDecrypt
{
public void encrypt();
public void decrypt();
}

class SpaceElimination
{
public static String space(String s)
{
s=s.replaceAll("\\s","");
return s;
}
}

class CaesarCipher extends SpaceElimination implements


EncryptDecrypt
{
public void encrypt()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the string for encryption");
int a=3;
StringBuffer result=new StringBuffer();
String str=sc.nextLine();
String str1=space(str);
for(int i=0;i<str1.length();i++)
{
if(Character.isUpperCase(str1.charAt(i)))
{
char ch=(char)(((int)str1.charAt(i)+a-65)%26+65);
result.append(ch);
}
else
{
char ch=(char)(((int)str1.charAt(i)+a-97)%26+97);
result.append(ch);
}
}
System.out.println(result);
}
public void decrypt()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the string for decryption");
int a=23;
StringBuffer result=new StringBuffer();
String str=sc.nextLine();
String str1=space(str);
for(int i=0;i<str1.length();i++)
{
if(Character.isUpperCase(str1.charAt(i)))
{
char ch=(char)(((int)str1.charAt(i)+a-65)%26+65);
result.append(ch);
}
else
{
char ch=(char)(((int)str1.charAt(i)+a-97)%26+97);
result.append(ch);
}
}
System.out.println(result);
}
}
class Q1_19BIT0355
{
public static void main(String[] args)
{
int x=100;
Scanner sc=new Scanner(System.in);
CaesarCipher c=new CaesarCipher();
while(x!=0)
{
System.out.println("Press 1 to encrypt, 2 to decrypt, 0 to exit");
x=sc.nextInt();
if(x==1)
{
c.encrypt();
}
else if(x==2)
{
c.decrypt();
}
}
}
}

OUTPUT-:
Q2
CODE:

File: Primes.java
package primespackage;

public class Primes{

public static boolean checkForPrime(int a){

if(a<4) return a>1;

for(int i=2;i<a/2;i++) if (a%i==0) return false;

return true;
}

File: TwinPrimes.java

CODE-:

import java.util.*;

import java.io.*;

import primespackage.Primes;

class TwinPrimes{

public static void main(String[] args){

Scanner in=new Scanner(System.in);

System.out.println("input limit to check for twin primes till:");

int n=in.nextInt();
if (n<5) return;

for(int i=3;i+1<n;i+=4){

if(Primes.checkForPrime(i)&&Primes.checkForPrime(i+2))
System.out.println(i+", "+(i+2));

if(i+2<n&&Primes.checkForPrime(i+1)&&Primes.checkForPrime(i+3))
System.out.println((i+1)+", "+(i+3));

}
NEXT PAGE-
VarArgs_Abstract Classes Question-:
Q1
CODE:
import java.util.*;
class StudentGrade_19BIT0355 {
public static void determineGrade(int n)
{
Scanner sc=new Scanner(System.in);
for(int i=0;i<n;i++)
{
int sgrades=0;
System.out.println("Input registration no:");
String s=sc.next();
System.out.println("How many courses:");
int x=sc.nextInt();
for(int j=0;j<x;j++)
{
System.out.println("Enter Marks:");
float mark=sc.nextFloat();
if(mark>90.0 && mark<=100.0)
{System.out.println("Grade=S");
sgrades++;}
else if(mark>=80.0 && mark<90.0)
System.out.println("Grade=A");
else if(mark>=70.0 && mark<80.0)
System.out.println("Grade=B");
else if(mark>=60.0 && mark<70.0)
System.out.println("Grade=C");
else if(mark>=55.0 && mark<60.0)
System.out.println("Grade=D");
else if(mark>=50.0 && mark<55.0)
System.out.println("Grade=E");
else
System.out.println("Grade=F");
}
System.out.println("Count of S Grades:"+sgrades);
}
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("No. of the Students:");
int n=sc.nextInt();
determineGrade(n);
}
}
Q2
CODE:
import java.io.*;
import java.util.Scanner;
import java.util.Vector;
import java.util.Arrays;
import java.util.Iterator;
abstract class themepark{
public int total_cost(int m,int n){
return 500*n+300*m;
}
abstract void playGame();
}
class Queensland extends themepark{
public void playGame(){
Scanner in=new Scanner(System.in);
boolean[] Games=new boolean[30];
Arrays.fill(Games, false);
boolean wtp=true;
while(wtp){
System.out.println("which game do you want to play? (1-30). 0 to
quit");
int x=in.nextInt();
if(x==0) wtp=false;
else if(x>30 || x<1) System.out.println("please input valid number");
else if(Games[x]==true) System.out.println("Warning! play each game
atmost once.");
else{
System.out.println("Sucessfully played game "+x);
Games[x]=true;
}
}
}
}
class Wonderla extends themepark{
public void playGame(){
Scanner in=new Scanner(System.in);
int[] Games=new int[40];
Arrays.fill(Games, 0);
boolean wtp=true;
while(wtp){
System.out.println("which game do you want to play? (1-40). 0 to
quit");
int x=in.nextInt();
if(x==0) wtp=false;
else if(x>40 || x<1) System.out.println("please input valid number");
else{
System.out.println("Sucessfully played game "+x);
Games[x]++;
}
}
System.out.println("Games repeated=");
for(int i=0;i<40;i++) if(Games[i]>1) System.out.print(i+", ");
System.out.println("\nGames not played=");
for(int i=0;i<40;i++) if(Games[i]==0) System.out.print(i+", ");
System.out.println("\nGames played once=");
for(int i=0;i<40;i++) if(Games[i]==1) System.out.print(i+", ");
}
}
public class themeprk_19BIT0355{
public static void main(String[] args) {
System.out.println("\n\nQueensland:");
new Queensland().playGame();
System.out.println("\n\nWonderla:");
new Wonderla().playGame();
}
}
Exception Handling, Multithreading, I/O Streams, Collections
Q1
CODE:
import java.util.*;

public class ExceptionHandling_q1


{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
try
{
System.out.println("Enter your Registration Number:");
String reg = sc.next();
System.out.println("Enter your Mobile Number:");
String mob = sc.next();
char[] ch = reg.toCharArray();
char[] ch1 = mob.toCharArray();
if(ch.length!=9 || ch1.length!=10)
{
throw new IllegalArgumentException();
}
for(int i=0;i<ch1.length;i++)
{
if(!Character.isDigit(ch1[i]))
{
throw new NumberFormatException();
}
}
for(int i=0;i<ch.length;i++)
{
if(!Character.isDigit(ch[i]) && !Character.isLetter(ch[i]))
{
throw new NoSuchElementException();
}
}
System.out.println("Valid");
}
catch(NumberFormatException e)
{
System.out.println("Invalid");
}
catch(IllegalArgumentException e)
{
System.out.println("Invalid");
}
catch(NoSuchElementException e)
{
System.out.println("Invalid");
}
}
}

Q2
CODE:
import java.util.*;

class InvalidEmployeeCode extends Exception


{
InvalidEmployeeCode(String s)
{
super(s);
}
}

class Employee
{
String empid;
String name;
int birth;
public Employee(String empid,String name,int birth)
{
this.empid=empid;
this.name=name;
this.birth=birth;
}
void display() throws InvalidEmployeeCode
{
String num="1234567890";
String de="FS";
if(empid.length()!=8)
{
throw new InvalidEmployeeCode("Invalid");
}
String x[]=empid.split("-");
if(x[0].length()!=2 || x[1].length()!=1 || x[2].length()!=3)
{
throw new InvalidEmployeeCode("Invalid");
}
if(!de.contains(x[1]))
{
throw new InvalidEmployeeCode("Invalid");
}
String y=x[0];
for(int i=0;i<y.length();i++)
{
String y1=String.valueOf(y.charAt(i));
if(!num.contains(y1))
throw new InvalidEmployeeCode("Invalid");
}
for(int i=0;i<x[2].length();i++)
{
String z=String.valueOf(x[2].charAt(i));
if(!num.contains(z))
{
throw new InvalidEmployeeCode("Invalid");
}
}
System.out.println("Employee id: "+empid+"; Name: "+name+";
Year of birth: "+birth);
}
}

public class ExceptionHandling19BIT0355_q2


{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter EmpID:");
String empid=sc.next();
System.out.println("Enter Employee Name:");
String name=sc.next();
System.out.println("Enter year of birth:");
int birth=sc.nextInt();
Employee E=new Employee(empid,name,birth);
try
{
E.display();
}
catch(Exception e)
{
System.out.println(e);
}}}

Q3
CODE:
import java.util.*;
class SameColorBallException extends Exception
{
SameColorBallException()
{
System.out.println("SameColorBallException");
}
}
public class ExceptionHandling19BIT0355_q3
{
public static void main(String[] args)
{
int i;
int red_count=0,green_count=0,yellow_count=0,blue_count=0;
for(int j=0;j<10;j++){ i=(int)((Math.random()*4)+1);
if(i==1)
red_count++;
else if(i==2)
green_count++;
else if(i==3)
blue_count++;
else if(i==4)
yellow_count++;
try
{
if(red_count>3 || green_count>3 || blue_count>3 ||
yellow_count>3)
{

throw new SameColorBallException();


}
}
catch(SameColorBallException e)
{

}
}
System.out.println("\nNumber of red balls:
"+red_count+"\nNumber of blue balls: "+blue_count+"\nNumber of
green balls: "+green_count+"\nNumber of yellow balls:
"+yellow_count);
}
}

Q4
CODE:
import java.util;
import java.io;
import java.lang.*;
class Main19BIT0355
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
PrintVote PV = new PrintVote();
ThreadVote t1 = new ThreadVote("Thread1",PV,0,60); ThreadVote t2
= new ThreadVote("Thread2",PV,60,120); ThreadVote t3 = new
ThreadVote("Thread3",PV,120,180); ThreadVote t4 = new
ThreadVote("Thread4",PV,180,240); try

{
t1.join();
t2.join();
t3.join();
t4.join();
}
catch(InterruptedException e)
{
System.out.println(e);
}
int a[] = PV.getVote();
int max = Integer.MIN_VALUE;
int index = -1;
for(int i=0;i<3;i++)
{
if(a[i]>max)
{
max = a[i];
index = i;
}
}
for(int i=0;i<3;i++)
{
System.out.println((char)(65+i)+" "+a[i]);
}
char ch = (char)(65+index); System.out.println("Winner is "+ch+"
"+max);
}
}
class ThreadVote extends Thread
{
static int r[] = new int[240];
static
{
for(int i=0;i<240;i++)
{
r[i] = (int)Math.floor(Math.random()*(3-1+1)+1); }
}
Thread t;
String threadName;

PrintVote PV;
int low;
int high;
ThreadVote(String name,PrintVote pv,int l,int h) {
threadName = name; PV = pv;
low = l;
high = h;
start();
}
public void run()
{
synchronized(PV)
{
System.out.println(threadName +" starting"); PV.printVote(r,low,high);
System.out.println(threadName +" exiting"); }
}
}
class PrintVote
{
static int res[] = new int[3];
public void printVote(int num[],int l,int h)
{
int count1 = 0;
int count2 = 0;
int count3 = 0;
for(int i=l;i<h;i++)
{
if(num[i]==1)
{
count1++;
}
else if(num[i]==2)
{
count2++;
}
else
{

count3++;
}
}
res[0] = res[0] + count1; res[1] = res[1] + count2; res[2] = res[2] +
count3; }
int[] getVote() {
return res;
}
}
Q5
CODE:
import java.util.*;
import java.io.*;
class Fibonacci extends Thread
{
private PipedWriter PW = new PipedWriter();
public PipedWriter getPipedWriter()
{
return PW;
}
public void run()
{
Thread t = Thread.currentThread();
t.setName("Fibonacci");
System.out.println(t.getName() + " thread started");
int a=0,b=1,c=0;
while(true)
{
try
{
c=a+b;
if(c>100000)
{
PW.close();
break;
}
PW.write(c);
sleep(100);
}
catch(Exception e)
{
System.out.println("Fibonacci:"+e);
}
a=b;
b=c;
}
System.out.println(t.getName() + " thread exiting");
}
}
class Prime extends Thread
{
private PipedWriter PW1 = new PipedWriter();
public PipedWriter getPipedWriter()
{
return PW1;
}
public void run()
{
Thread t= Thread.currentThread();
t.setName("Prime");
System.out.println(t.getName() + " thread Started...");
int prime=1;
while(true)
{
try
{
if(prime>100000)
{
PW1.close();
break;
}
if(isPrime(prime))
PW1.write(prime);
prime++;
sleep(0);
}
catch(Exception e)
{
System.out.println(t.getName() + " thread exiting.");
System.exit(0);
}
}
}
public boolean isPrime(int n)
{
int m=(int)Math.round(Math.sqrt(n));
if(n==1 || n==2)
return true;
for(int i=2;i<=m;i++)
if(n%i==0)
return false;
return true;
}
}
public class Multithreading_q1
{
public static void main(String[] args) throws Exception
{
Thread t=Thread.currentThread();
t.setName("Main");
System.out.println(t.getName() + " thread Started...");
Fibonacci fibonacci = new Fibonacci();
Prime prime = new Prime();
PipedReader fpr = new PipedReader(fibonacci.getPipedWriter());
PipedReader ppr = new PipedReader(prime.getPipedWriter());
fibonacci.start();
prime.start();
int fib=fpr.read(), prm=ppr.read();
System.out.println("The numbers common to PRIME and
FIBONACCI:");
while((fib!=-1) && (prm!=-1))
{
while(prm<=fib)
{
if(fib==prm)
System.out.println(prm);
prm=ppr.read();
}
fib=fpr.read();
}
System.out.println(t.getName() + " thread exiting");
}
}
Q6
CODE:
import java.util.*;
import java.io.*;
class Factor implements Runnable
{
long j,c;
Scanner sc=new Scanner(System.in);
long x=sc.nextLong();
Factor()
{
super();
c=0;
}
static long factorial(long n)
{
if(n==0)
return 1;
return n*factorial(n-1);
}
public void run()
{
System.out.println("Factorial of "+x+": "+factorial(x));
}
}

class Fib extends Factor implements Runnable


{
long a,b,c,n;
Fib()
{
a=c=n=0; b=1;
}
public void run()
{
while(n++<x)
{
System.out.println(n+"th" +" Fib no: = "+a);
c=a+b;
a=b;
b=c;
try
{
if(n==10)
{
System.out.println("Thread fibonacci is put into sleep.");
Thread.sleep(500);
}
}
catch(InterruptedException e)
{
System.out.println("Error : " + e);
}
}
}

}
public class MultiThreading19BIT0355_q2
{
public static void main(String[] args)
{
Thread ct=Thread.currentThread();
System.out.println("Main thread name : "+ct.getName());
Factor p=new Factor();
Fib f=new Fib();
Thread fib=new Thread(f,"fibonacci");
Thread factor=new Thread(p,"factorial");
fib.start();
System.out.println("Thread "+ fib.getName() + " started.");
factor.start();
System.out.println("Thread "+ factor.getName() + " started.");
}
}

Q7
CODE:
public class ProducerConsumer_19BIT0355
{
public static void main(String[] args)
{
Shop c = new Shop();
Producer p1 = new Producer(c, 1);
Consumer c1 = new Consumer(c, 1);
p1.start();
c1.start();
}
}
class Shop
{
private int materials;
private boolean available = false;
public synchronized int get()
{
while (available == false)
{
try
{
wait();
}
catch (InterruptedException ie)
{
}
}
available = false;
notifyAll();
return materials;
}
public synchronized void put(int value)
{
while (available == true)
{
try
{
wait();
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
materials = value;
available = true;
notifyAll();
}
}
class Consumer extends Thread
{
private Shop Shop;
private int number;
public Consumer(Shop c, int number)
{
Shop = c;
this.number = number;
}
public void run()
{
int value = 0;
for (int i = 0; i < 10; i++)
{
value = Shop.get();
System.out.println("Consumed value " + this.number+ "
got: " + value);
}
}
}
class Producer extends Thread
{
private Shop Shop;
private int number;

public Producer(Shop c, int number)


{
Shop = c;
this.number = number;
}
public void run()
{
for (int i = 0; i < 10; i++)
{
Shop.put(i);
System.out.println("Produced value " + this.number+ " put:
" + i);
try
{
sleep((int)(Math.random() * 100));
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
}
}
Q8
CODE:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Files19BIT0355_q1


{
public static void main(String[] args)
{
try
{
File infile =new File("Infile.txt");
File outfile =new File("Outfile.txt");

FileInputStream instream = new FileInputStream(infile);


FileOutputStream outstream = new FileOutputStream(outfile);

byte[] buffer = new byte[10];


int length;
while ((length = instream.read(buffer)) > 0)
{
outstream.write(buffer, 0, length);
}

instream.close();
outstream.close();
System.out.println("File copied successfully!!");

}
catch(IOException ioe)
{
ioe.printStackTrace();
}}}
Q9
CODE:
import java.io.*;
import java.text.ParseException; import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar; import java.util.Scanner;
class Donor implements Serializable { String name, address, bgroup;
Date dold;
int age;
Donor(String name, String address, String bgroup, Date dold, int age)
{ this.name = name;
this.address = address;
this.bgroup = bgroup;
this.dold = dold;
this.age = age; }

public void display() {


System.out.println("name:" + name + ",address:" + address +
",bgroup:" + bgroup +
",dold:" + dold + ",age:" + age); }
}
public class Donations {
public static int getMonths(Date start, Date end){
Calendar startCal = new GregorianCalendar(); startCal.setTime(start);
Calendar endCal = new GregorianCalendar(); endCal.setTime(end);
int diffYear = endCal.get(Calendar.YEAR) -
startCal.get(Calendar.YEAR);
int diffMonth = diffYear * 12 + endCal.get(Calendar.MONTH) -
startCal.get(Calendar.MONTH);
return diffMonth; }
public static void main(String[] args) { Scanner sc = new
Scanner(System.in); Donor donors[] = new Donor[3];
try{

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");


donors[0] = new Donor("Anuradha", "2172", "O+ve",
sdf.parse("13/09/2018"), 21); donors[1] = new Donor("Uday", "2012",
"AB+ve",sdf.parse("12/05/2018"), 21); donors[2] = new
Donor("Kaviya", "0888", "A+ve", sdf.parse("12/04/2018"), 21);
}catch (ParseException e){ System.out.println(e);
}
String filename = "donations.txt"; try{
FileOutputStream fos = new FileOutputStream(filename);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(donors); oos.close();
fos.close();
}catch(FileNotFoundException e){ System.out.println(e);
}catch(IOException e){ System.out.println(e);
}
try{
FileInputStream fis = new FileInputStream(filename);
ObjectInputStream ois = new ObjectInputStream(fis);
Donor[] savedDonors = (Donor[])ois.readObject();

fis.close(); ois.close();
System.out.println("Donors with A+ve and Last date of Donation >
6mths: "); for(Donor d: savedDonors) {
if(getMonths(d.dold,new Date()) > 6 && d.bgroup.equals("A+ve"))
d.display();
} }catch(FileNotFoundException e){
System.out.println(e); }catch(IOException e){
System.out.println(e);
} catch (ClassNotFoundException e) {
e.printStackTrace(); }
}}

Q10
CODE:
import java.util.*;

class Book
{
int id;
String Name, Author, Publisher;

public Book(int id, String name, String author, String pub)


{
this.Name = name;
this.Author = author;
this.Publisher = pub;
this.id = id;
}
}

public class Collections19BIT0355_q1


{

public static void display_details(LinkedList<Book> dir, String


search, Integer choice)
{
for (int i = 0; i < dir.size(); i++)
{
Book temp;
temp = dir.get(i);
String x;
switch(choice)
{
case 1:
x = temp.Author;
if (x.equals(search))
{
System.out.println("Details :\nID: " + temp.id + "\nName: "
+ temp.Name + " \nAuthor: " + temp.Author + " \nPublisher: " +
temp.Publisher);
}
case 2:
x = temp.Publisher;
if (x.equals(search))
{
System.out.println("Details :\nID: " + temp.id + "\nName: "
+ temp.Name + " \nAuthor: " + temp.Author + " \nPublisher: " +
temp.Publisher);
}
case 3:
x = temp.Name;
if (x.equals(search))
{
System.out.println("Details :\nID: " + temp.id + "\nName: "
+ temp.Name + " \nAuthor: " + temp.Author + " \nPublisher: " +
temp.Publisher);
}

}
}

public static void main(String[] args) {

Book b1 = new Book(101, "Java Programming", "James",


"Microsoft");
Book b2 = new Book(202, "Programming with C", "Thomas",
"Quark");
Book b3 = new Book(303, "C++", "Noble", "LucidPress");
Book b4 = new Book(404, "PYTHON For You", "Jospeh",
"Quark");

LinkedList<Book> dir = new LinkedList<>();


dir.add(b1);
dir.add(b2);
dir.add(b3);
dir.add(b4);
int i;
Scanner sc = new Scanner(System.in);
do
{
System.out.println("Search for book, Enter choice:\n1. To
search by author\n2. To search by publisher\n3. To search by name");
Integer choice;
choice = sc.nextInt();
sc.nextLine();

String search;
switch (choice)
{

case 1:
System.out.println("Enter the name of author to be searched
:");
search = sc.nextLine();
display_details(dir, search, choice);
break;

case 2:
System.out.println("Enter the name of publisher to be
searched :");
search = sc.nextLine();
display_details(dir, search, choice);
break;

case 3:
System.out.println("Enter the name of book to be searched
:");
search = sc.nextLine();
display_details(dir, search, choice);
break;

default:
System.out.println("Please enter a valid choice");

}
System.out.println("Want to search anything else? Enter 1 for
'Yes' and 0 for 'No'");
i=sc.nextInt();
}while(i!=0);

}
}
INHERITANCE(PREVIOUS DA QUESTIONS)
Q11

Create a class Film with string objects which stores name, language
and lead_actor and category (action/drama/fiction/comedy). Also
include an integer data member that stores the duration of the film.
Include parameterized constructor, default constructor and accessory
functions to film class. Flim objects can be initialized either using a
constructor or accessor functions. Create a class FilmMain that
includes a main function. In the main function create an array of
objects that stores the information about the film. Also write suitable
methods to display the following

a. The English film(s) that has Arnold as its lead actor and that runs
for shortest duration.

b. The Tamil film(s) with "x" as lead actor. ("x" can be read as input
from the user.

c. All the comedy movies.

CODE-:

import java.io.*;
import java.util.Scanner;
import java.util.Vector;
import java.util.Iterator;
class Film{
public String name, lang, lead_actor, category;
public int dur;
public Film(){
name="";
lang="";
lead_actor="";
category="";
dur=0;
}
public Film(String a,String b,String c,String d, int e){
this.set(a,b,c,d,e);
}
public void set(String a,String b,String c,String d, int e){
name=a;
lang=b;
lead_actor=c;
category=d;
dur=e;
}
public void prnt(){
System.out.println(name+", "+lang+", "+lead_actor+", "+category+", "+dur);
}
}
public class Example12_19BIT0355{
public static void main(String[] args){
Scanner in=new Scanner(System.in);
Vector<Film> v = new Vector<Film>();
v.add(new Film("Terminator","English","Arnold","action",123));
v.add(new Film("Apdi123","Tamil","Rajini","comedy",123));
v.add(new Film("Terminator:outtakes","English","Arnold","comedy",11));
Iterator<Film> it1=v.iterator();
Iterator<Film> it2=v.iterator();
Iterator<Film> it3=v.iterator();
System.out.println("\n\na. The English film(s) that has Arnold as its lead
actor and that runs for shortest duration.=");
int s=999;
Film y=new Film();
while(it1.hasNext()){
Film x=it1.next();
if (x.lead_actor.equalsIgnoreCase("arnold") && x.dur<s){
s=x.dur;
y=x;
}
}
y.prnt();
System.out.println("\n\nb. The Tamil film(s) with Rajini as lead actor.=");
while(it2.hasNext()){
Film x=it2.next();
if (x.lead_actor.equalsIgnoreCase("rajini")) x.prnt();
}
System.out.println("\n\nc. All the comedy movies.=");
while(it3.hasNext()){
Film x=it3.next();
if (x.category.equalsIgnoreCase("comedy")) x.prnt();
}
}
}

Q12.
Write a program to demonstrate the knowledge of students in String handling.

Eg., Write a program to read a chemical equation and find out the count of the reactants and the
products. Also display the count of the number of molecules of each reactant and product.

Eg., For the equation, 2NaOH + H2SO4 -> Na2SO4+ 2H2O, the O/P should be as follows.
Reactants are 2 moles of NaOH, 1 mole of H2SO4.

CODE-:

import java.io.*;

import java.util.Scanner;

class Example13_19BIT0355{

public static void main(String[] args){

Scanner in=new Scanner(System.in);

String e=in.nextLine();

int i;

System.out.print("Reactants are:");

for(String p : e.split("-")[0].split(" ")){

if(p.charAt(0)>='A' && p.charAt(0)<='Z') System.out.print("1 mole of "+p);

else if(p.charAt(0)>='0' && p.charAt(0)<='9'){

for(i=0;i<p.length() && p.charAt(i)>='0' && p.charAt(i)<='9';i++);

System.out.print(p.substring(0,i));

System.out.print(" mole of "+p.substring(i)+", ");

System.out.print("\n Products are:");

for(String p : e.split("-")[1].split(" ")){

if(p.charAt(0)>='A' && p.charAt(0)<='Z') System.out.print("1 mole of "+p);


else if(p.charAt(0)>='0' && p.charAt(0)<='9'){

for(i=0;i<p.length() && p.charAt(i)>='0' && p.charAt(i)<='9';i++);

System.out.print(p.substring(0,i));

System.out.print(" mole of "+p.substring(i)+", ");

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

Q13.

Write a program to demonstrate the knowledge of students in


advanced concepts of Java string handling.

Eg., (Bioinformatics: finding genes) Biologists use a sequence of


letters A, C, T, and G to model a genome. A gene is a substring of a
genome that starts after a triplet ATG and ends before a triplet TAG,
TAA, or TGA. Furthermore, the length of a gene string is a multiple of
3 and the gene does not contain any of the triplets ATG, TAG, TAA,
and TGA. Write a program that prompts the user to enter a genome
and displays all genes in the genome. If no gene is found in the input
sequence, displays no gene. Here are the sample runs:

Enter a genome string: TTATGTTTTAAGGATGGGGCGTTAGTT

O/P: TTT

GGGCGT

CODE-:
import java.io.*;

import java.util.Scanner;

class Example14_19BIT0355 {

public static void main(String[] args){

Scanner in=new Scanner(System.in);

String e=in.nextLine(), g="",a="",b="",c="";

int i;

boolean x = false;

for(String p : e.split("ATG")){

i=p.length();

a=p.split("TAG")[0];

b=p.split("TAA")[0];

c=p.split("TGA")[0];
if(a.length()!=p.length() && a.length()%3==0) {i=a.length(); g=a;}

if(b.length()!=p.length() && b.length()%3==0 && b.length()<i)


{i=b.length(); g=b;}

if(c.length()!=p.length() && c.length()%3==0 && c.length()<i)


{i=c.length(); g=c;}

if (i<p.length()) System.out.println(g);

Q14

A training centre conducts a total of 7 tests for its students. Students


are allowed to skip few tests. Let there be 25 students in the batch. So
in the main class for every student, read the number of tests taken
and the marks scored in each test. A class ‘TestDetails’ should be
defined with a 2D array of float type to store the marks of all the
students. Define a method ‘storeMarks()’ that will receive the following
details for every student from the main class and create in the 2D
array, those many columns equal to the number of tests, so as to store
the marks. There is no need to store the number of tests. Define
another method ‘displayMarks()’ to print the details.

Also the training centre wishes to keep those students in notice period
who have taken < 3 tests and those who have not scored ≥ 50 in at
least 3 tests. Derive another class ‘NoticePeriod’ from ‘TestDetails’
that includes a method to count and print the number of students in
bench. Also it should print the ID of those students assuming the row
index of the array to be their ID. While checking do not proceed to
check the marks in all tests, if the student has already scored more
than 50 in 3 tests. Instantiate this class from the main class and do the
required processing.

CODE-:

import java.util.Scanner;

public class Main {

public static void main(String[] args)

NoticePeriod notice = new NoticePeriod();

float marks[][] = new float[25][];

Scanner scan = new Scanner(System.in);

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

System.out.print("Enter the number of marks for Student: "+i+" (max 7


marks): ");

int numMarks = scan.nextInt(); marks[i] = new float[numMarks];


for(int j=0;j<marks[i].length;j++)

System.out.print("Enter marks: "+(i+1)+" : "); marks[i][j] = scan.nextFloat();

}notice.storeMarks(marks); notice.displayMarks();

System.out.println();

notice.printBench(); scan.close();

class NoticePeriod extends TestDetails{

public void printBench()

System.out.print("Students ID who are on the bench : ");

int benchStudents = 0;

int countAbove50;

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

if(marks[i].length < 3)

benchStudents++;

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

else {

countAbove50 = 0;

for(int j=0;j<marks[i].length;j++)

if(marks[i][j] >= 50) countAbove50++;

if(countAbove50 >= 3)

break;

if(countAbove50 < 3)

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

benchStudents++;

System.out.println("\nTotal Students on a bench : "+benchStudents);

import java.util.*;

import java.util.Scanner;
class TestDetails {

protected float marks[][];

public TestDetails()

{ marks=null;

public void storeMarks(float inMarks[][])

{ marks = new float[inMarks.length][];

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

marks[i] = new float[inMarks[i].length];

for(int j=0;j<inMarks[i].length;j++) marks[i][j] = inMarks[i][j];

public void displayMarks()

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

System.out.print("\nStudent "+i+" : ");

for(int j=0;j<marks[i].length-1;j++)

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

System.out.print(marks[i][marks[i].length-1]);
}

System.out.println();

}
Q15

Create an inheritance hierarchy in java using following information


given below that a bank might use to represent customers’ bank
accounts.

Base class Account should include one data member of type double to
represent account balance. The class should provide constructor that
receives an initial balance and uses it to initialize the data member.
The constructor should validate the initial balance to ensure that it is
greater than or equal to 0.If not the balance is set to 0.0 and the
constructor should display an error message indicating that the initial
balance was invalid. The class also provides three member functions
credit, debit (debit amount should not exceed the account balance)
and enquiry. Derived class SavingsAccount should inherit the
functionality of an Account, but also include data member of type
double indicating the interest rate assigned to the Account.
SavingsAccount constructor should receive the initial balance, as well
as an initial value for SavingsAccount’s interest rate. SavingsAccount
should provide public member function calculateInterest that returns
double indicating the amount of interest earned by an account. The
method calculateInterest should determine this amount by multiplying
the interest rate by the account balance. SavingsAccount function
should inherit member functions credit, debit and enquiry without
redefining them. Derived class CheckingAccount should inherit the
functionality of an Account, but also include data member of type
double that represents the fee charged per transaction.
CheckingAccount constructor should receive the initial balance, as
well as parameter indicating fee amount. Class CheckingAccount
should redefine credit and debit function so that they subtract the fee
from account balance whenever either transaction is performed.
CheckingAccount’s debit function should charge a fee only if the
money is actually withdrawn (debit amount should not exceed the
account balance).After defining the class hierarchy, write program that
creates object of each class and tests their member functions. Add
interest to SavingAccount object by first

invoking its calculateInterest function, then passing the returned


interest amount to object’s credit function.

CODE-:

import java.util.*;

import java.util.Scanner;

class Account

double balance;

Account(double balance)

if(balance>=0)

this.balance=balance;

else {

System.out.println("Initial balance was invalid");

this.balance=0.0;

}
}void credit(double amount)

balance=balance+amount;

System.out.println(amount+" credited to Account");

}void debit(double amount)

if(amount<=balance)

balance=balance-amount;

System.out.println(amount+" debited from Account");

else {

System.out.println("Insufficient balance");

void enquiry()

System.out.println("Balance is : "+balance);

}
}

class SavingsAccount extends Account

double interestrate;

SavingsAccount(double balance,double interestrate)

super(balance);

this.interestrate=interestrate;

public double calculateInterest()

return ((balance*4.5)/100);

class CheckingAccount extends Account

double feeamount;

CheckingAccount(double balance,double feeamount)

{
super(balance);

this.feeamount=feeamount;

}void credit(double amount)

balance=balance+amount-feeamount;

System.out.println(amount+" credited to Checking Account");

void debit(double amount)

if((amount+feeamount)<=balance)

balance=balance-amount-feeamount;

System.out.println(amount+" debited from Checking Account");

else {

System.out.println("Insufficient balance");

}
public class MainBank_19BIT0355

public static void main(String[] args) {

System.out.println("Performing operations on account\n");

Account ac1=new Account(2000); ac1.credit(1500); ac1.enquiry();


ac1.debit(3000); ac1.debit(1000); ac1.enquiry();

System.out.println("\n\nPerforming operations on savings


account\n");

SavingsAccount sac=new SavingsAccount(1200,4.5);

double interest=sac.calculateInterest();

System.out.println("Interest for savings account is : "+interest);


sac.credit(interest); sac.enquiry();

System.out.println("\n\nPerforming operations on checking


account\n");

CheckingAccount ca=new CheckingAccount(2700,50);


ca.credit(600); ca.enquiry(); ca.debit(1300); ca.enquiry();

You might also like