0% found this document useful (0 votes)
8 views52 pages

1

The document contains multiple Java programs that demonstrate various concepts such as complex number arithmetic, publication management, employee salary calculations, shape area calculations, vehicle interface implementations, and exception handling. Each section includes classes and methods for handling user input and performing specific operations. The programs are structured with main methods that provide user interaction through console input and output.

Uploaded by

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

1

The document contains multiple Java programs that demonstrate various concepts such as complex number arithmetic, publication management, employee salary calculations, shape area calculations, vehicle interface implementations, and exception handling. Each section includes classes and methods for handling user input and performing specific operations. The programs are structured with main methods that provide user interaction through console input and output.

Uploaded by

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

************ 1 *************

import java.util.*;

class Complex
{
float real;
float img;

Complex()
{
real=0; // default constructor
img=0;
}

Complex(float r,float i)
{
real=r;
img=i;
}

void addition(Complex s1,Complex s2)


{
float r,i;
r=s1.real+ s2.real;
i=s1.img +s2.img;
System.out.println(r+"+"+i+"i");
}

void subtraction(Complex s1,Complex s2)


{
float r,i;
r=s1.real- s2.real;
i=s1.img -s2.img;
System.out.println(r+"+"+"("+i+")"+"i");
}
void multiplication(Complex s1,Complex s2)
{
float r,i;
r=s1.real*s2.real-s1.img*s2.img;
i=s1.real*s2.img +s1.img*s2.real;
System.out.println(r+"+"+i+"i");
}
void division(Complex s1,Complex s2)
{
float r,i;
r=(s1.real*s2.real+ s1.img*s2.img)/(s2.real*s2.real+s2.img*s2.img);
i=(s1.img*s2.real -s1.real*s2.img)/(s2.real*s2.real+s2.img*s2.img);
System.out.println(r+"+"+"("+i+")"+"i");
}
}

public class arithmetic


{
public static void main(String args[])
{
float r,i;
System.out.println("Enter real and imaginary part of 1st complex number: ");

Scanner sc=new Scanner(System.in);


r=sc.nextFloat();
i=sc.nextFloat();
Complex c1=new Complex(r,i);

System.out.println("Enter real and imaginary part of 2nd complex number: ");


r=sc.nextFloat();
i=sc.nextFloat();
Complex c2=new Complex(r,i);
Complex c3=new Complex();

while(true)
{
System.out.println(" Enter choice for\n 1. Addition \n 2. Sub \n 3. Mult \n 4. Div \n
System.out.println(" Enter choice for\n 1. Addition \n 2. Sub \n 3. Mult \n 4. Div \n
5. For exit");

int ch;
ch=sc.nextInt();
switch(ch)
{
case 1:
c3.addition(c1,c2);
break;
case 2:
c3.subtraction(c1,c2);
break;
case 3:
c3.multiplication(c1,c2);
break;
case 4:
c3.division(c1,c2);
break;
case 5:
System.exit(0);
default:
System.out.println("Enter proper choice");

****** 2 *******
import java.util.*;
class Publication
{
String title=null;
float price=0;
int copy=0;

void get() //to get the data from user


{
Scanner sc=new Scanner(System.in);

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


title=sc.nextLine();

System.out.println("Enter price of 1: ");


price=sc.nextFloat();

System.out.println("Enter number of copies: ");


copy=sc.nextInt();
}

void display() //to display the data


{
System.out.println("The title is: "+title);
System.out.println("The price is: "+price);
System.out.println("Number of copies are: "+copy);
}

void sale() //sale of product


{
float tot;
int x;
int z;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number of copies sold: ");
x=sc.nextInt();
tot=price*x;
z=copy-x;
z=copy-x;
System.out.println("The sale is: "+tot);
System.out.println("Available copies are: "+z);
}
}

class Book extends Publication


{
String author;

void books()
{
Scanner sc=new Scanner(System.in);

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


author=sc.nextLine();
System.out.println("Author of the book is: "+author);
}
}

class Magazine extends Publication


{
int ordqty;
String currentissue;

void magazines()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number of copies sold: ");
ordqty=sc.nextInt();
}

void issue()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the date to be displayed in manner: day/month/year");
currentissue=sc.nextLine();
System.out.println("The issue date of magazine is: ");
System.out.println("The issue date of magazine is: ");
System.out.println(currentissue);
}
}

public class Main


{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to the Publication");
while(true)
{
System.out.println("Press according to your choice 1. Books 2. Magazines 3. EXIT");
int ch;
ch=sc.nextInt();
switch(ch)
{
case 1:
System.out.println("Book Operation");
Book b1 = new Book();
b1.get();
b1.books();
b1.display();
b1.sale();
break;

case 2:
System.out.println("Magazine Operation");
Magazine m1 = new Magazine();
m1.get();
m1.magazines();
m1.display();
m1.sale();
m1.issue();
break;
case 3:
System.out.println("Thank you");
System.exit(0);
break;

default:
System.out.println("Enter proper choice: ");
}
}
}
}

****** 3 *******

import java.util.*;
class Employee
{
String emp_name, address, mail_id;
long mobile_no;
int emp_id;
double basic_pay;
void getdata()
{
System.out.println("Enter the following data:\n");
System.out.println("Employee name: ");
Scanner s1 = new Scanner(System.in);
emp_name= s1.nextLine();
System.out.println("Employee ID: ");
Scanner s2 = new Scanner(System.in);
emp_id= s2.nextInt();
System.out.println("Employee address: ");
Scanner s3 = new Scanner(System.in);
address= s3.nextLine();
System.out.println("Employee Mail: ");
Scanner s4 = new Scanner(System.in);
mail_id= s4.nextLine();
System.out.println("Employee Mobile number: ");
Scanner s5 = new Scanner(System.in);
mobile_no= s5.nextLong();

}
void display()
{
System.out.println("Employee name: "+emp_name+"\nEmployee ID: "+emp_id+"\nEmployee
address: "+address+"\nEmployee Mail: "+mail_id+"\nEmployee Mobile number:
"+mobile_no+"\n");
}
}
class Programmer extends Employee
{
double basic_pay,da,hra,pf,scf,net,gross;
void cal()
{
System.out.println("Employee Basic Pay: ");
Scanner s6 = new Scanner(System.in);
basic_pay= s6.nextDouble();
da=0.97*basic_pay;
hra=0.1*basic_pay;
pf=0.12*basic_pay;
scf=0.01*basic_pay;
gross= basic_pay+ da +hra;
net= gross-pf-scf;
}
void displayinfo()
{
System.out.println("Gross Salary"+gross+"\nNet Salary: " +net);
}
}
class TeamLead extends Employee
{
double basic_pay,da,hra,pf,scf,net,gross;
void cal()
{
System.out.println("Employee Basic Pay: ");
Scanner s7 = new Scanner(System.in);
basic_pay= s7.nextDouble();
da=0.97*basic_pay;
hra=0.1*basic_pay;
pf=0.12*basic_pay;
scf=0.01*basic_pay;
gross= basic_pay+ da +hra;
net= gross-pf-scf;
}
void displayinfo()
{
System.out.println("Gross Salary"+gross+"\nNet Salary: " +net);
}
}
class ProjectManager extends Employee
{
double basic_pay,da,hra,pf,scf,net,gross;
void cal()
{
System.out.println("Employee Basic Pay: ");
Scanner s8 = new Scanner(System.in);
basic_pay= s8.nextDouble();
da=0.97*basic_pay;
hra=0.1*basic_pay;
pf=0.12*basic_pay;
scf=0.01*basic_pay;
gross= basic_pay+ da +hra;
net= gross-pf-scf;
}
void displayinfo()
{
System.out.println("Gross Salary"+gross+"\nNet Salary: " +net);
}
}
class AssistantProjectManager extends Employee
{

double basic_pay,da,hra,pf,scf,net,gross;
void cal()
{
System.out.println("Employee Basic Pay: ");
Scanner s8 = new Scanner(System.in);
basic_pay= s8.nextDouble();
da=0.97*basic_pay;
hra=0.1*basic_pay;
pf=0.12*basic_pay;
scf=0.01*basic_pay;
gross= basic_pay+ da +hra;
net= gross-pf-scf;
}
void displayinfo()
{
System.out.println("Gross Salary"+gross+"\nNet Salary: " +net);
}
}
public class assign3
{
public static void main(String args[])
{

while(true)
{
System.out.println(" \nEnter your choice for \n 1.Programmer \n 2.TeamLead \n
3.ProjectManager \n 4.AssistantProjectManager\n 5.Exit");
Scanner sc= new Scanner(System.in);
int ch;
ch=sc.nextInt();
switch(ch)
{
case 1:
Programmer obj1 = new Programmer();
obj1.getdata();
obj1.display();
obj1.cal();
obj1.displayinfo();
break;

case 2:
TeamLead obj2 = new TeamLead();
obj2.getdata();
obj2.display();
obj2.cal();
obj2.displayinfo();
break;

case 3:
ProjectManager obj3 = new ProjectManager();
obj3.getdata();
obj3.display();
obj3.cal();
obj3.displayinfo();
break;

case 4:
AssistantProjectManager obj4 = new AssistantProjectManager();
obj4.getdata();
obj4.display();
obj4.cal();
obj4.displayinfo();
break;

case 5:
System.exit(0);
default:
System.out.println( " Enter proper choice ");
}
}
}
}
/*Enter your choice for
1.Programmer
2.TeamLead
3.ProjectManager
4.AssistantProjectManager
5.Exit
1
Enter the following data:

Employee name:
mal
Employee ID:
123
Employee address:
were
Employee Mail:
[email protected]
Employee Mobile number:
729374920
Employee name: mal
Employee ID: 123
Employee address: were
Employee Mail: [email protected]
Employee Mobile number: 729374920

Employee Basic Pay:


5000
Gross Salary10350.0
Net Salary: 9700.0

Enter your choice for


1.Programmer
2.TeamLead
3.ProjectManager
4.AssistantProjectManager
5.Exit
5
/*

***** 4 ******

import java.util.*;
abstract class shape
{double x,y;
public void getdata()
{Scanner sc=new Scanner(System.in);
System.out.print("enter the base=");
x=sc.nextDouble();
System.out.print("enter the height=");
y=sc.nextDouble();
}

abstract void area();

}
class rectangle extends shape
{
void area()
{this.x=x;
this.y=y;
double a=x*y;
System.out.println("area="+a);}}
class triangle extends shape
{
void area(){
this.x=x;
this.y=y;
double a=0.5*x*y;
System.out.println("area="+a);}
}
public class a4
{public static void main(String args[])
{
int o;
while(true)
{System.out.println("enter your choice\n1.rectangle \n2.triangle\n3.exit");
Scanner sc1=new Scanner(System.in);
o=sc1.nextInt();

switch (o)
{case 1:
{
shape s1=new rectangle();
s1.getdata();
s1.area();
break;}
case 2:
{shape s2=new triangle();
s2.getdata();
s2.area();
break;}
case 3:
{System.out.println("thank you");
System.exit(0);
break;}
default:
{System.out.println("Enter appropriate choice");
}
}}}}
/*enter your choice
1.rectangle
2.triangle
3.exit
1
enter the base=3
enter the height=7
area=21.0
enter your choice
1.rectangle
2.triangle
3.exit
2
enter the base=4
enter the height=7
area=14.0
enter your choice
1.rectangle
2.triangle
3.exit
3
thank you
*/

****. 5. *******
import java.util.*;
import java.util.Scanner;
interface vehicle
{
void changegear(int x);
void speedup(int y);
void brakes(int z);
}
class car implements vehicle
{
Scanner sc=new Scanner(System.in);
int gear;
int speed;
int brake;
public void changegear(int x)
{
System.out.println("enter the gear to be changed:");
gear=sc.nextInt();
System.out.println("the gear is changed:"+gear);
}
public void speedup(int y)
{
System.out.println("enter the speed to be changed:");
speed=sc.nextInt();
System.out.println("the speed is changed to"+speed+"km/hr");
}
public void brakes(int z)
{
System.out.println("enter the speed to be lowered:");
brake=sc.nextInt();
System.out.println("the speed has been lowered to"+brake+"km/hr");
}
}
class bike implements vehicle
{
Scanner sc=new Scanner(System.in);
int gear;
int speed;
int brake;
public void changegear(int x)
{
System.out.println("enter the gear to be changed:");
gear=sc.nextInt();
System.out.println("the gear is changed:"+gear);
}
public void speedup(int y)
{
System.out.println("enter the speed to be changed:");
speed=sc.nextInt();
System.out.println("the speed is changed to"+speed+"km/hr");
}
public void brakes(int z)
{
System.out.println("enter the speed to be lowered:");
brake=sc.nextInt();
System.out.println("the speed has been lowered to"+brake+"km/hr");
}
}
class bicycle implements vehicle
{
Scanner sc=new Scanner(System.in);
int gear;
int speed;
int brake;
public void changegear(int x)
{

System.out.println("enter the gear to be changed:");


gear=sc.nextInt();
System.out.println("the gear is changed:"+gear);
}
public void speedup(int y)
{
System.out.println("enter the speed to be changed:");
speed=sc.nextInt();
System.out.println("the speed is changed to"+speed+"km/hr");
}
public void brakes(int z)
{
System.out.println("enter the speed to be lowered:");
brake=sc.nextInt();
System.out.println("the speed has been lowered to"+brake+"km/hr");
}
}
class interfacedemo
{
public static void main(String args[])
{
int x;
Scanner sc=new Scanner(System.in);
do
{
System.out.println("\t"+"MENU");
System.out.println("Choose the vehicle:");
System.out.println("\t"+"1.CAR");
System.out.println("\t"+"2.BIKE");
System.out.println("\t"+"3.BICYCLE");
System.out.println("\t"+"4.EXIT");
x=sc.nextInt();
switch(x)
{
case 1:
car o1=new car();
o1.changegear(4);
o1.speedup(70);
o1.brakes(50);
break;
case 2:
bike o2=new bike();
o2.changegear(3);
o2.speedup(54);
o2.brakes(40);
break;
case 3:
bicycle o3=new bicycle();
o3.changegear(2);
o3.speedup(10);
o3.brakes(5);
break;
case 4:
break;
}
}while(true);
}

******. 6. ********
java lab assignment no.6
name:Ashwini Mohan Giri roll np.22

package Exception;
import java.util.*;
class ExceptionEx{
public void Arithmatic(){
int num1 , num2;
int result;
Scanner sc = new Scanner(System.in);
System.out.println("Enter Two Numbers ::");
try{
num1=sc.nextInt();
num2=sc.nextInt();
result=num1/num2;
System.out.println("The result is "+result);
}
catch(ArithmeticException e){
System.out.println("Number cannot be divided by zero");
}
}
public void InputMismatchFormat(){
int num1 , num2;
int result;
Scanner sc = new Scanner(System.in);
System.out.println("Enter Two Numbers ::");
try{
num1=sc.nextInt();
num2=sc.nextInt();
result=num1/num2;
System.out.println("The result is "+result);
}
catch(InputMismatchException e){
System.out.println("Enter only integer values ");
}
System.out.println(" \n successfully completed \n ");
}
public void ArrayOutOfBound(){
int a[]= new int[5];
int i=0;
int x;
Scanner sc = new Scanner(System.in);
System.out.println("Enter 5 values :");
Scanner ss= new Scanner(System.in);
try{
while(i<5){
a[i]=sc.nextInt();
i++; }
System.out.print("\nEnter the Index No. of Element which you want to print ::");
i=ss.nextInt();
System.out.println( a[i]+" is present at given index"); }
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index out of Bound");
}
System.out.println(" \n successfully completed \n ");
}
public void Numberformat() {
int number;
Scanner sc = new Scanner(System.in);
System.out.println("Enter any valid Integer: ");
try {
number = Integer.parseInt(sc.next());
System.out.println("You entered: "+ number);
} catch (NumberFormatException e){
System.out.println("NumberFormatException occurred");
}
System.out.println("\n successfully completed \n ") {
}
public class Excep{
public static void main(String[] args){
ExceptionEx e = new ExceptionEx();
Scanner sc=new Scanner(System.in);
int n;
do{
System.out.println("\n Enter the Choice which you want to check type of error "+"\n\t1]
Arithmaticexception"+"\n\t2] ArrayOutOfBound"+"\n\t3] NumberFormat"+"\n\t4] Input Mismatch
Exception " + "\n\t5 Exit");
n=sc.nextInt();
switch(n) {
case 1:
e.Arithmatic();
break;
case 2:
e.ArrayOutOfBound();
break;
case 3:
e.Numberformat();
break;
case 4:
e.InputMismatchFormat();
case 5:
n=0;
break; }
}while(n!=0); }
}

output:
Enter the Choice which you want to check type of error
1] Arithmaticexception
2] ArrayOutOfBound
3] NumberFormat
4] Input Mismatch Exception
5 Exit
1
Enter Two Numbers ::
10
2
The result is 5
Enter the Choice which you want to check type of error
1] Arithmaticexception
2] ArrayOutOfBound
3] NumberFormat
4] Input Mismatch Exception
5 Exit
2
Enter 5 values :
3
5
8
6
9
Enter the Index No. of Element which you want to print ::3
6 is present at given index
successfully completed

Enter the Choice which you want to check type of error


1] Arithmaticexception
2] ArrayOutOfBound
3] NumberFormat
4] Input Mismatch Exception
5 Exit
3
Enter any valid Integer:
34
You entered: 34

successfully completed

Enter the Choice which you want to check type of error


1] Arithmaticexception
2] ArrayOutOfBound
3] NumberFormat
4] Input Mismatch Exception
5 Exit
4
Enter Two Numbers ::
34
2
The result is 17
successfully completed

******7. ******
Assignment No 7 : Implement a generic program using any collection class to count the number
of elements in a
collection that have a specific property such as even numbers, odd number, prime
number and
palindromes.*/

import java.util.*;

public class genericOP


{
static<T> void count(String type, T[] a)
{

int even = 0;

if(type.equals("even")) //To check for even numbers


{
for(T value : a)
{
if(Integer.parseInt(value.toString())%2==0)
{
even++;
}
}
System.out.println("Total Even Numbers in array are: "+ even);
}

int odd = 0;
if(type.equals("odd")) //To check for odd numbers
{
for(T value : a)
{
if(Integer.parseInt(value.toString())%2!=0)
{
odd++;
}
}

System.out.println("Total Odd Numbers in array are: "+ odd);

int prime = 0;

if(type.equals("prime")) //To check for prime numbers


{
for(T value : a)
{
int n=Integer.parseInt(value.toString());
int flag=0;
for(int i=2;i<n;i++)
{
if(Integer.parseInt(value.toString())%i==0)
{
flag=1;
break;
}
}

if(flag==0)
{
prime++;
}
}
System.out.println("Total Prime Numbers in array are: "+ prime);

int palindrome = 0; //To check for Palindrome numbers

if(type.equals("palindrome"))
{
for(T value : a)
{
StringBuffer rev=new StringBuffer(value.toString());
if(value.toString().equals(new String(rev.reverse())))
{
palindrome++;
}
}
System.out.println("Total Palindrome Numbers in array are: "+ palindrome);
}
}

public static void main(String args []) // Main class


{
int k,i;
Scanner sc=new Scanner(System.in);
System.out.print("Enter Array Size:");
k=sc.nextInt();
Integer array[] = new Integer [k];
System.out.println("Enter Array elements: ");
for(i=0;i<k;i++)
{
array[i]=sc.nextInt();
}
count("even", array);
count("odd", array);
count("prime", array);
count("palindrome", array);
}

/* *************Output****************

Enter Array Size:6


Enter Array elements:
4 58 96 363 42 11
Total Even Numbers in array are: 4
Total Odd Numbers in array are: 2
Total Prime Numbers in array are: 1
Total Palindrome Numbers in array are: 3

*/

****** 8 ********

Assignment No 8 :Implement a program for maintaining a student records database using File
Handling. Student has
Student_id, name, Roll_no, Class, marks and address. Display the data for five
students.
i) Create Database
ii)Display Database
iii) Clear Records
iv)Modify record
v)Search Record.*/

import java.io.*;
import java.util.*;

class Database
{
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public void addRecords() throws IOException
{
PrintWriter pw = new PrintWriter(new BufferedWriter(new
FileWriter("sample.txt",true)));
String studentname,address,s,classname;
int studentid,rollno;
float marks;

boolean addMore = false;


do
{
System.out.print("\nEnter Student Name: ");
studentname = br.readLine();
System.out.print("Student Id: ");
studentid = Integer.parseInt(br.readLine());
System.out.print("Roll no: ");
rollno = Integer.parseInt(br.readLine());
System.out.print("Address: ");
address = br.readLine();
System.out.print("Class: ");
classname =(br.readLine());
System.out.print("Marks : ");
marks = Float.parseFloat(br.readLine());
pw.println(studentname+" "+studentid+" "+rollno+" "+address+" "+classname+"
"+marks);
System.out.print("\nRecords added successfully !\n\nDo you want to add more
records ? (y/n) : ");
s = br.readLine();
if (s.equalsIgnoreCase("y"))
{
addMore = true;
System.out.println();
}

else
addMore = false;
}
while (addMore);
pw.close();
}

public void readRecords() throws IOException


{
try
{
BufferedReader file = new BufferedReader(new FileReader("sample.txt"));
String name;
int i=1;
while ((name = file.readLine()) != null)
{
System.out.println(name);
System.out.println("");
}

file.close();
}

catch (FileNotFoundException e)
{
System.out.println("\nERROR : File not Found !!!");
}
}

public void searchRecords() throws IOException


{
try
{
BufferedReader file = new BufferedReader(new FileReader("sample.txt"));
String name;
int flag=0;
Scanner sc=new Scanner(System.in);
System.out.print("Enter an id of the student you want to search: ");
String searchname=sc.next();
while ((name = file.readLine()) != null)
{
String[] line = name.split(" ");

if (searchname.equalsIgnoreCase(line[1]))
{
System.out.println("Record found");
System.out.println(name);
System.out.println("");
flag=1;
break;
}
}

if (flag==0)
System.out.println("Record not found");
file.close();

catch (FileNotFoundException e)
{
System.out.println("\nERROR : File not Found !!!");
}
}

public void deleteRecords() throws IOException


{
try
{
BufferedReader file1 = new BufferedReader(new FileReader("sample.txt"));
PrintWriter pw = new PrintWriter(new BufferedWriter(new
FileWriter("new.txt",true)));
String name;
int flag=0;
Scanner sc=new Scanner(System.in);
System.out.print("Enter the name of the student you want to delete: ");
String searchname=sc.next();

while ((name = file1.readLine()) != null)


{
String[] line = name.split(" ");

if (!searchname.equalsIgnoreCase(line[0]))
{
pw.println(name);
flag=0;
}
else
{
System.out.println("Record found");
flag=1;
}
}
file1.close();
pw.close();

File delName =new File("sample.txt");


File oldName =new File("new.txt");
File newName =new File("sample.txt");

if (delName.delete())
System.out.println("deleted successfully");
else
System.out.println("Error");
if (oldName.renameTo(newName))
System.out.println("Renamed successfully");
else
System.out.println("Error");

}
catch (FileNotFoundException e)
{
System.out.println("\nERROR : File not Found !!!");
}
}

public void updateRecords() throws IOException


{
try
{

BufferedReader file1 = new BufferedReader(new FileReader("sample.txt"));


PrintWriter pw = new PrintWriter(new BufferedWriter(new
FileWriter("new.txt",true)));
String name;
int flag=0;
Scanner sc=new Scanner(System.in);
System.out.print("Enter the name of the student you want to update: ");
String searchname=sc.next();

while ((name = file1.readLine()) != null)


{
String[] line = name.split(" ");

if (!searchname.equalsIgnoreCase(line[0]))
{
pw.println(name);
flag=0;
}

else
{
System.out.println("Record found");
System.out.print("Enter updated marks: ");
String up_mark=sc.next();
pw.println(line[0]+" "+line[1]+" "+line[2]+" "+line[3]+" "+line[4]+"
"+up_mark);
flag=1;
}
}

file1.close();
pw.close();
File delName = new File("sample.txt");
File oldName = new File("new.txt");
File newName = new File("sample.txt");

if (delName.delete())
System.out.println("record updated successfully");
else
System.out.println("Error");
if (oldName.renameTo(newName))
System.out.println("Renamed successfully");
else
System.out.println("Error");

catch(FileNotFoundException e)
{
System.out.println("\nERROR : File not Found !!!");
}
}

public void clear(String filename) throws IOException


{
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(filename)));
pw.close();
System.out.println("\nAll Records cleared successfully !");
}

}
public class Fileoperation// Main Class
{
public static void main(String args[]) throws IOException
{
Database f = new Database();
Scanner sc =new Scanner(System.in);
System.out.println("");
while(true)
{
System.out.print("1. Add Records\n2. Display Records\n3. Clear All Records\n4.
Search Records"
+ "\n5. Delete Records\n6. Update Records \n7. Exit\n\nEnter your choice : ");
int ch = sc.nextInt();
System.out.println("");
switch(ch)
{
case 1:
f.addRecords();

System.out.println("\n====================================================\n");
break;

case 2:
f.readRecords();

System.out.println("\n====================================================\n");
break;

case 3:
f.clear("sample.txt");

System.out.println("\n====================================================\n");
break;

case 4:
f.searchRecords();

System.out.println("\n====================================================\n");
break;

case 5:
f.deleteRecords();

System.out.println("\n====================================================\n");
break;

case 6:
f.updateRecords();

System.out.println("\n====================================================\n");
break;

case 7:

System.out.println("\n====================================================\n");
System.exit(0);
break;

default:
System.out.println("\nInvalid Choice !");

System.out.println("\n====================================================\n");
break;
}
}
}
}

/************OUTPUT***********************
1. Add Records
2. Display Records
3. Clear All Records
4. Search Records
5. Delete Records
6. Update Records
7. Exit

Enter your choice : 1

Enter Student Name: harsh


Student Id: 25
Roll no: 20
Address: pune
Class: IT
Marks : 90

Records added successfully !

Do you want to add more records ? (y/n) : n

====================================================

1. Add Records
2. Display Records
3. Clear All Records
4. Search Records
5. Delete Records
6. Update Records
7. Exit

Enter your choice : 2

harsh 25 20 pune IT 90.0

====================================================

1. Add Records
2. Display Records
3. Clear All Records
4. Search Records
5. Delete Records
6. Update Records
7. Exit

Enter your choice : 4

Enter an id of the student you want to search: 25


Record found
harsh 25 20 pune IT 90.0

====================================================

1. Add Records
2. Display Records
3. Clear All Records
4. Search Records
5. Delete Records
6. Update Records
7. Exit

Enter your choice : 6

Enter the name of the student you want to update: harsh


Record found
Enter updated marks: 120
record updated successfully
Renamed successfully

====================================================

1. Add Records
2. Display Records
3. Clear All Records
4. Search Records
5. Delete Records
6. Update Records
7. Exit

Enter your choice : 1

Enter Student Name: yash


Student Id: 21
Roll no: 23
Address: pune
Class: IT
Marks : 114

Records added successfully !

Do you want to add more records ? (y/n) : n

====================================================

1. Add Records
2. Display Records
3. Clear All Records
4. Search Records
5. Delete Records
6. Update Records
7. Exit

Enter your choice : 5

Enter the name of the student you want to delete: yash


Record found
deleted successfully
Renamed successfully

====================================================

1. Add Records
2. Display Records
3. Clear All Records
4. Search Records
5. Delete Records
6. Update Records
7. Exit

Enter your choice : 3

All Records cleared successfully !

====================================================

1. Add Records
2. Display Records
3. Clear All Records
4. Search Records
5. Delete Records
6. Update Records
7. Exit

Enter your choice : 7


====================================================*/

******. 9. *******

package XYZ11;

import java.util.Scanner;

class Bank {
private String accno;
private String name;
private long balance;

Scanner KB = new Scanner(System.in);

//method to open an account


void openAccount() {
System.out.print("\nEnter Account No: ");
accno = KB.next();
System.out.print("Enter Name: ");
name = KB.next();
System.out.print("Enter Balance: ");
balance = KB.nextLong();
}

//method to display account details


void showAccount() {
System.out.println("\n"+accno + "," + name + "," + balance);
}

//method to deposit money


void deposit() {
long amt;
System.out.println("Enter Amount U Want to Deposit : ");
amt = KB.nextLong();
balance = balance + amt;
}

//method to withdraw money


void withdrawal() {
long amt;
System.out.println("WTHDRAWAL LIMIT IS 15000 RS\nEnter Amount U Want to withdraw :
");
amt = KB.nextLong();
if(amt<=15000)
{
if (balance >= amt) {
balance = balance - amt;
} else {
System.out.println("Less Balance..Transaction Failed..");
}
}
else{
System.out.println("Withdraw Limit Exceeded");
}
}

//method to search an account number


boolean search(String acn) {
if (accno.equals(acn)) {
showAccount();
return (true);
}
return (false);
}
}

public class Hello{


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

//create initial accounts


System.out.print("How Many Customer U Want to Input : ");
int n = KB.nextInt();
Bank C[] = new Bank[n];
for (int i = 0; i < C.length; i++) {
C[i] = new Bank();
C[i].openAccount();
}

//run loop until menu 5 is not pressed


int ch;
do {
System.out.println("\n***** Main Menu *****\n1. Display All\n2. Search By Account\n3.
Deposit\n4. Withdrawal\n5.Exit");
System.out.println("Ur Choice :"); ch = KB.nextInt();
switch (ch) {
case 1:
for (int i = 0; i < C.length; i++) {
C[i].showAccount();
}
break;

case 2:
System.out.print("Enter Account No U Want to Search...: ");
String acn = KB.next();
boolean found = false;
for (int i = 0; i < C.length; i++) {
found = C[i].search(acn);
if (found) {
break;
}
}
if (!found) {
System.out.println("Search Failed..Account Not Exist..");
}
break;

case 3:
System.out.print("Enter Account No : ");
acn = KB.next();
found = false;
for (int i = 0; i < C.length; i++) {
found = C[i].search(acn);
if (found) {
C[i].deposit();
break;
}
}
if (!found) {
System.out.println("Search Failed..Account Not Exist..");
}
break;

case 4:
System.out.print("Enter Account No : ");
acn = KB.next();
found = false;
for (int i = 0; i < C.length; i++) {
found = C[i].search(acn);
if (found) {
C[i].withdrawal();
break;
}
}
if (!found) {
System.out.println("Search Failed..Account Not Exist..");
}
break;

case 5:
System.out.println("Good Bye..");
break;
}
}
while (ch != 5);
}
}

******10 *********

import java.util.Scanner;

// Abstract class representing a generic Car


abstract class Car
{
private String model;

public Car(String model)


{
this.model = model;
arrangeParts();
}

private void arrangeParts() {


// Do one-time processing here
}

protected abstract void construct();

public String getModel()


{
return model;
}
}

class LuxuryCar extends Car


{
private String company, carName;
private double budget;

public LuxuryCar()
{
super("Luxury");
construct();
}

protected void construct()


{
System.out.println("Building luxury car");
Scanner scan = new Scanner(System.in);
System.out.print("Company: ");
company = scan.next();

System.out.print("Car Name: ");


carName = scan.next();

System.out.print("Rough Budget (in Lakhs): ");


budget = scan.nextDouble();

System.out.println("Luxury Car Details:");


System.out.println("Company: " + company);
System.out.println("Car Name: " + carName);
System.out.println("Budget: " + budget);
System.out.println("Color: Black/White/Orange/Red");
System.out.println("Fuel: Diesel");
System.out.println("Gears: Auto");
System.out.println("Tyres: Alloy Wheels");
System.out.println("Airbags: YES");
System.out.println("Back Wiper: YES");
System.out.println("Side Mirror: Two");
System.out.println("Touch Screen Music Player: YES");
System.out.println("Roof Window: YES");
}
}

class SmallCar extends Car {


private String company, carName;
private double budget;

public SmallCar() {
super("Small");
construct();
}

protected void construct() {


System.out.println("Building small car");
Scanner scan = new Scanner(System.in);
System.out.print("Company: ");
company = scan.next();

System.out.print("Car Name: ");


carName = scan.next();

System.out.print("Rough Budget (in Lakhs): ");


budget = scan.nextDouble();

System.out.println("Small Car Details:");


System.out.println("Company: " + company);
System.out.println("Car Name: " + carName);
System.out.println("Budget: " + budget);
System.out.println("Color: Black/White/Orange/Red");
System.out.println("Fuel: Petrol");
System.out.println("Gears: Manual");
System.out.println("Tyres: Alloy Wheels");
System.out.println("Side Mirror: Two");
}
}

class SedanCar extends Car {


private String company, carName;
private double budget;

public SedanCar() {
super("Sedan");
construct();
}

protected void construct() {


System.out.println("Building sedan car");
Scanner scan = new Scanner(System.in);

System.out.print("Company: ");
company = scan.next();
System.out.print("Car Name: ");
carName = scan.next();

System.out.print("Rough Budget (in Lakhs): ");


budget = scan.nextDouble();

System.out.println("Sedan Car Details:");


System.out.println("Company: " + company);
System.out.println("Car Name: " + carName);
System.out.println("Budget: " + budget);
System.out.println("Color: Black/White/Orange/Red");
System.out.println("Fuel: Petrol/Diesel");
System.out.println("Gears: Auto/Manual");
System.out.println("Tyres: Alloy Wheels");
System.out.println("Airbags: YES");
System.out.println("Back Wiper: YES");
System.out.println("Side Mirror: Two");
System.out.println("Touch Screen Music Player: YES");
}
}

// CarFactory Class
// Factory class responsible for creating car objects
class CarFactory {
public static Car buildCar(String model) {
switch (model.toLowerCase()) {
case "small":
return new SmallCar();
case "sedan":
return new SedanCar();
case "luxury":
return new LuxuryCar();
default:
System.out.println("Unknown car type: " + model);
return null;
}
}
}

//TestFactoryPattern Class

public class TestFactoryPattern {


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

while (true) {
System.out.print("\nChoose Car Type - 1. Small 2. Sedan 3. Luxury 4. Exit\nEnter Choice:
");
int choice = input.nextInt();

switch (choice) {
case 1:
CarFactory.buildCar("small");
break;
case 2:
CarFactory.buildCar("sedan");
break;
case 3:
CarFactory.buildCar("luxury");
break;
case 4:
System.out.println("Exiting...");
input.close();
return;
default:
System.out.println("Invalid choice. Please try again.");
}
}
}
}
****** 11 ******

*Implement and apply Strategy Design pattern for simple Shopping Cart where three
payment strategies are used such as Credit Card, PayPal, Bit Coin.
Create an interface for strategy pattern and give concrete implementation for payment*/

import java.util.Scanner;

// PaymentStrategy Interface
interface PaymentStrategy
{
void pay(int amount);
}

// CreditCardStrategy Implementation
class CreditCardStrategy implements PaymentStrategy
{
private String cardHolderName;
private String cardNumber;
private String cvv;
private String expiryDate;

public CreditCardStrategy(String cardHolderName, String cardNumber, String cvv, String


expiryDate)
{
this.cardHolderName = cardHolderName;
this.cardNumber = cardNumber;
this.cvv = cvv;
this.expiryDate = expiryDate;
}

public void pay(int amount)


{
System.out.println(amount + " paid using Credit Card.");
}
}
}

// PaypalStrategy Implementation
class PaypalStrategy implements PaymentStrategy
{
private String email;
private String password;

public PaypalStrategy(String email, String password)


{
this.email = email;
this.password = password;
}

public void pay(int amount)


{
System.out.println(amount + " paid using PayPal.");
}
}

// BitcoinStrategy Implementation
class BitcoinStrategy implements PaymentStrategy
{
private String walletAddress;

public BitcoinStrategy(String walletAddress)


{
this.walletAddress = walletAddress;
}

public void pay(int amount)


{
System.out.println(amount + " paid using Bitcoin.");
}
}
// Item Class
class Item
{
private String upcCode;
private int price;

public Item(String upcCode, int price)


{
this.upcCode = upcCode;
this.price = price;
}

public int getPrice()


{
return price;
}
}

// ShoppingCart Class
class ShoppingCart
{
private Item item1;
private Item item2;
private Item item3;

public ShoppingCart()
{
item1 = new Item("4359", 890);
item2 = new Item("2465", 3000);
item3 = new Item("3456", 10000);
}

public int calculateTotal()


{
return item1.getPrice() + item2.getPrice() + item3.getPrice();
}
public void pay(PaymentStrategy paymentMethod)
{
int amount = calculateTotal();
paymentMethod.pay(amount);
}
}

// Main Class
public class ShoppingCartApplication
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
ShoppingCart cart = new ShoppingCart();

System.out.println("Select payment method:");


System.out.println("1. Credit Card");
System.out.println("2. PayPal");
System.out.println("3. Bitcoin");

int choice = scanner.nextInt();


scanner.nextLine(); // Consume newline

switch (choice)
{
case 1:
System.out.print("Enter Name on Card: ");
String cardHolderName = scanner.nextLine();
System.out.print("Enter Card Number: ");
String cardNumber = scanner.nextLine();
System.out.print("Enter CVV: ");
String cvv = scanner.nextLine();
System.out.print("Enter Expiry Date (MM/YY): ");
String expiryDate = scanner.nextLine();
cart.pay(new CreditCardStrategy(cardHolderName, cardNumber, cvv, expiryDate));
break;
case 2:
System.out.print("Enter PayPal Email: ");
String email = scanner.nextLine();
System.out.print("Enter PayPal Password: ");
String password = scanner.nextLine();
cart.pay(new PaypalStrategy(email, password));
break;
case 3:
System.out.print("Enter Bitcoin Wallet Address: ");
String walletAddress = scanner.nextLine();
cart.pay(new BitcoinStrategy(walletAddress));
break;
default:
System.out.println("Invalid choice. Please try again.");
}

scanner.close();
}
}

You might also like