Java Gaand Mardi
Java Gaand Mardi
19BIT0355
class SpaceElimination
{
public static String space(String s)
{
s=s.replaceAll("\\s","");
return s;
}
}
OUTPUT-:
Q2
CODE:
File: Primes.java
package primespackage;
return true;
}
File: TwinPrimes.java
CODE-:
import java.util.*;
import java.io.*;
import primespackage.Primes;
class TwinPrimes{
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.*;
Q2
CODE:
import java.util.*;
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);
}
}
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)
{
}
}
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));
}
}
}
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;
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; }
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;
}
}
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.
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{
String e=in.nextLine();
int i;
System.out.print("Reactants are:");
System.out.print(p.substring(0,i));
System.out.print(p.substring(0,i));
System.out.print("\n");
Q13.
O/P: TTT
GGGCGT
CODE-:
import java.io.*;
import java.util.Scanner;
class Example14_19BIT0355 {
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 (i<p.length()) System.out.println(g);
Q14
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;
for(int i=0;i<marks.length;i++)
}notice.storeMarks(marks); notice.displayMarks();
System.out.println();
notice.printBench(); scan.close();
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(countAbove50 >= 3)
break;
if(countAbove50 < 3)
System.out.print(i+" ");
benchStudents++;
import java.util.*;
import java.util.Scanner;
class TestDetails {
public TestDetails()
{ marks=null;
for(int i=0;i<inMarks.length;i++)
for(int i=0;i<marks.length;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
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
CODE-:
import java.util.*;
import java.util.Scanner;
class Account
double balance;
Account(double balance)
if(balance>=0)
this.balance=balance;
else {
this.balance=0.0;
}
}void credit(double amount)
balance=balance+amount;
if(amount<=balance)
balance=balance-amount;
else {
System.out.println("Insufficient balance");
void enquiry()
System.out.println("Balance is : "+balance);
}
}
double interestrate;
super(balance);
this.interestrate=interestrate;
return ((balance*4.5)/100);
double feeamount;
{
super(balance);
this.feeamount=feeamount;
balance=balance+amount-feeamount;
if((amount+feeamount)<=balance)
balance=balance-amount-feeamount;
else {
System.out.println("Insufficient balance");
}
public class MainBank_19BIT0355
double interest=sac.calculateInterest();