You are on page 1of 65

Name:- HRITHIK JAISWAL

Reg No:- 19BCE0173


Course:- Java Programming Lab
Slot:- L49 + L50
Cycle Sheet 1
1. Write a program to find the factorial of a number using command line
arguments.

Code:- public class fac2

public static void main(String args[ ])

int i,a=1;

int n=Integer.parseInt(args[0]);

for(i=1;i<=n;i++)

a=a*i;

System.out.println("Factorial of number is:"+a);

Output:-

2. Write a program to print the multiplication table of a number.


Code:- import java.util.Scanner;

public class mul

public static void main(String args[])

int i,n;

Scanner sn= new Scanner(System.in);

n=sn.nextInt();

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

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

Output:-
3. Write a program to check whether the given number is an
Armstrong number or not.

Code:- import java.util.Scanner;

public class arm

public static void main(String args[])

int k=0,a,temp;

Scanner sn= new Scanner(System.in);

int n= sn.nextInt();

temp=n;

while(n>0)

a=n%10;

n=n/10;
k=k+(a*a*a);

if(temp==k)

System.out.println("Armstrong number");

else

System.out.println("Not an Armstrong number");

Output:-

4. Write a program to check whether the given number is a prime


number or not.

Code:- import java.util.Scanner;

public class Prime


{

public static void main(String[]args)

int n,i;

Scanner sc= new Scanner(System.in);

n=sc.nextInt();

boolean flag=false;

for(i=2;i<=n/2;i++)

if(n%i==0)

flag=true;

break;

if(!flag)

System.out.println(n+" is prime no");

}
else

System.out.println(n+"Not a prime no");


}

Output:-

5. Write a program to generate the following patterns.

(i) 1
1 2
1 2 3

Sol:- import java.util.Scanner;

public class P1

public static void main(String[] args)

Scanner sn = new Scanner(System.in);

System.out.println("Enter the number of rows to print the pattern ");


int r = sn.nextInt();

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

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

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

System.out.println();

Output:-

5 (ii) *

**

***

**
*

Code:-
import java.util.Scanner;

public class P3

public static void main(String[] args)

Scanner sc = new Scanner(System.in);

int r = sc.nextInt();

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

for (int j = r; j > i; j--)

System.out.print(" ");

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

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

System.out.println();

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


{

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

System.out.print(" ");

for (int k = 1; k <= r - i; k++)

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

System.out.println();

Output:-

6. Write a program to generate the Fibonacci series

Code:- import java.util.Scanner;

public class Fib


{

public static void main(String args[])

int n,a=0,b=1,s;

Scanner sn= new Scanner(System.in);

n=sn.nextInt();

for( int i=0;i<=n;i++)

System.out.println(a+" ");

s= a+b;

a=b;

b=s;

Output:-
7. Write a program to sort n numbers in ascending order.

Code:-

import java.util.Scanner;
public class sort1

public static void main(String args[])

Scanner sc = new Scanner(System.in);

int n;

System.out.println("No of elements in array is:=");

int s = sc.nextInt();

int[] numArray = new int[s];

for (int i = 0; i < s; i++)

{
System.out.print("Enter element : ");

numArray[i] = sc.nextInt();

System.out.println("Elements entered are:=");

for (int i = 0; i < s - 1; i++)

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

System.out.println(numArray[numArray.length - 1]);

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

for (int j = i + 1; j < numArray.length; j++)

if (numArray[i] > numArray[j])

n = numArray[i];

numArray[i] = numArray[j];

numArray[j] = n;

}
}

System.out.println("Array after sorting is:= ");

for (int i = 0; i < s - 1; i++)

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

System.out.println(numArray[numArray.length - 1]);

Output:-

8. Write a program to search a number among n numbers using


binary search.

Code:-
import java.util.Scanner;

public class Search

public static void main(String args[])

int count, n, i, arr[],first,last,mid;

Scanner sn = new Scanner(System.in);

System.out.println("Enter elements of array:");

n = sn.nextInt();

arr = new int[n];

System.out.println("Enter " + n + " integers");

for (count = 0; count < n; count++)

arr[count] = sn.nextInt();

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

i= sn.nextInt();

first = 0;

last = n - 1;

mid = (first + last)/2;


while( first <= last )

if ( arr[mid] < i )

first = mid + 1;

else if ( arr[mid] == i )

System.out.println(i + " found at location " + (mid + 1) + ".");

break;

else

last = mid - 1;

mid = (first + last)/2;

if ( first > last )

System.out.println(i + " is not found.\n");

}
Output:-

9. Write a program to read ‘n’ numbers and print their sum and average.
Code:- import java.util.Scanner;

public class Avg

public static void main(String args[])

int i,n,sum=0,avg=0,count=0;

Scanner sn= new Scanner(System.in);

n=sn.nextInt();

for(i=1;i<=n;i++)

System.out.println(i);

sum=sum+i;

avg=sum/n;

System.out.println(" The sum is:="+ sum);


System.out.println(" The average is:=" + avg);
}

Output:-

10. Write a program that accepts a number as input and convert them into
binary, octal and hexadecimal equivalents.

Sol:- class Convert

Scanner Scan= new Scanner(System.in);

int n;

void get()

Scan = new Scanner(System.in);

System.out.println("\nEnter the number :");

n = Integer.parseInt(Scan.nextLine());

void convert()

{
String hexa = Integer.toHexString(n);

System.out.println("HexaDecimal Value is : " + hexa);

String octal = Integer.toOctalString(n);

System.out.println("Octal Value is : " + octal);

String binary = Integer.toBinaryString(n);

System.out.println("Value of Binary is:= " + binary);

public class Decimal_Conversion

public static void main(String args[])

Convert obj = new Convert();

obj.get();

obj.convert();

Output:-
11. Write a menu driven program to i) append a string ii) insert a string iii)
delete a portion of the string.

CODE:-

import java.util.Scanner;

public class Str {

static String insert(String str, String sub, int index) {

String strBegin = str.substring(0, index);

String strEnd = str.substring(index);


return strBegin + sub + strEnd;

static String delete(String str, int start, int end) {

String strBegin = str.substring(0, start);

String strEnd = str.substring(end);

return strBegin + strEnd;

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter the initial String: ");

String s = sc.nextLine();

int choice = 0;

while (choice != 4) {

String substr;

int index;

System.out.print(

"Select an option: \n1. Append the string\n2. Insert a String\n3.


Delete a portion\n4. Exit\n");

System.out.print("Enter your Choice: ");

choice = sc.nextInt();
sc.nextLine();

switch (choice) {

case 1:

System.out.print("Enter string to be appended: ");

substr = sc.nextLine();

s = insert(s, substr, s.length());

break;

case 2:

System.out.print("Enter string to be inserted: ");

substr = sc.nextLine();

System.out.print("Enter the position(Number of characters before


current string): ");

index = sc.nextInt();

sc.nextLine();

s = insert(s, substr, index);

break;

case 3:

System.out.print("Enter the position(Number of characters before the


string to be deleted): ");

index = sc.nextInt();

sc.nextLine();
System.out.print("Enter the position(Number of characters till the end
of the string to be deleted): ");

int end = sc.nextInt();

sc.nextLine();

s = delete(s, index, end);

break;

default:

break;

System.out.println("\nModified String: " + s + "\n");

sc.close();

Output:-
12. Write a program to check whether a string is palindrome or not without
using functions.

Sol:- import java.util.Scanner;

public class Palindrome

public static void main(String args[])

int a,sum=0,k,n;

Scanner sn = new Scanner(System.in);

n=sn.nextInt();

a=n;

while(n>0)

k=n%10;

sum=(sum*10)+k;

n=n/10;
}

if(a==sum)

System.out.println( sum + " is a palindrome");

else

System.out.println( sum + "is not a palindrome");

Output:-

13. Write a menu driven program to i) compare two strings ii) get the character
in the specified position iii) extract a substring iv) replace a character with the
given character v) get the position of a specified substring/character.

CODE:-
import java.util.Scanner;

public class StringOps {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

int choice = 0;

while (choice != 6) {

System.out.print("\nSelect an option: \n1. Compare two strings\n2. Get


char at specified position\n");

System.out.print("3. Extract a substring\n4. Replace a character with


given character\n");

System.out.print("5. Get position of a specified character\n6. Exit");

System.out.print("\nEnter your Choice: ");

choice = sc.nextInt();

sc.nextLine();

String str, str1;

int index, endIndex;

char ch;

switch (choice) {

case 1:

System.out.print("Enter string one: ");

str = sc.nextLine();
System.out.print("Enter string two: ");

str1 = sc.nextLine();

if (str1.equals(str))

System.out.println("The strings are same");

else

System.out.println("The strings are different");

break;

case 2:

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

str = sc.nextLine();

System.out.print("Enter the position(starting from 1): ");

index = sc.nextInt();

sc.nextLine();

System.out.println("Character at the specified position is " +


str.charAt(index - 1));

break;

case 3:

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

str = sc.nextLine();

System.out.print("Enter the start position(starting from 1): ");

index = sc.nextInt();

sc.nextLine();
System.out.print("Enter the end position(starting from 1): ");

endIndex = sc.nextInt();

sc.nextLine();

System.out.println("Extracted Substring is " + str.substring(index - 1,


endIndex));

break;

case 4:

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

str = sc.nextLine();

System.out.print("Enter the position(starting from 1): ");

index = sc.nextInt();

sc.nextLine();

System.out.print("Enter the the character to be replaced with: ");

ch = sc.next().charAt(0);

System.out.println("Modified String is " + str.substring(0, index - 1) +


ch + str.substring(index));

break;

case 5:

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

str = sc.nextLine();

System.out.print("Enter the the character to be searched: ");

str1 = sc.nextLine();
index = str.indexOf(str1);

if (index != -1)

System.out.println("Substring found at index " + index);

else

System.out.println("Substring not found");

break;

default:

break;

sc.close();

14. Write a program to change the case of the letters in a string. Eg. ABCdef
abcDEF.

Sol:- import java.util.Scanner;

public class Case

public static String Change(String a)

{
String temp = "";

int k = a.length();

for(int i = 0 ; i < k ; i++)

char ch=a.charAt(i);

if(ch >= 'a' &&ch <= 'z')

ch = (char)(65 + (int)(ch - 'a'));

else if(ch >= 'A' &&ch <= 'Z')

ch = (char)(97 +

(int)(ch - 'A'));

temp += ch;

return temp;

public static void Transstring(String a)

String b=Change(a);

System.out.println(b);

public static void main(String args[])

{
String a="ABCdef";

Transstring(a);

Output:-

15. Write a class with the following methods: wordCount: This method accepts
a String object as an argument and returns the number of words contained in
the object. arrayToString: This method accepts a char array as an argument
and converts it to a String object. mostFrequent: This method accepts a String
object as an argument and returns the character that occurs the most
frequently in the object.

CODE:-

import java.util.Scanner;

public class q15

public static void main(String[] args)

String string1 = "the dog jumped over the fence";

String string2 = "the";


String string3 = "that";

char[] charArray = { 'a', 'b', 'c', 'd', 'e', 'f', 'g'};

int numberOfWords = wordCount(string1);

System.out.println("The string is : " + string1);

System.out.println("Number of words in the above string is : " +


numberOfWords);

String character = arrayToString(charArray);

System.out.print("\nThe array is :");

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

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

System.out.print("\nString from the above character array is : "+


character);

char mostOccurrence = mostFrequent(string1);

System.out.println("\nThe string is : "+ string1);

System.out.print("The most occured character in the above string is : "+


mostOccurrence);

int numberOfWords;

private static int wordCount(String string1)

{
int number = 0;

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

char ch = string1.charAt(i);

if(Character.isWhitespace(ch))

number = number + 1;

return number + 1;

private static String arrayToString(char[] charArray)

return String.valueOf(charArray);

private static char mostFrequent(String string1)

char mostOccurrence = ' ';

int most = 0;

int j;

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


{

int count = 0;

char ch = string1.charAt(i);

for(j = 0; j < string1.length(); j++)

if(ch == string1.charAt(j))

count = count + 1;

if(count >= most)

most = count;

mostOccurrence = ch;

return mostOccurrence;

OUTPUT:-
16. Create a class Student (Regno, Name, Branch, Year, Semester and 5 Marks).
Add methods to read the student details, calculate the grade and print the
mark statement.

CODE:

package Pkg_1;
class Student
{
String reg;
String year;
String branch;
String name;
int sem;
double[] marks = new double[5];

public Student(String reg,String year,String branch,String name,int


sem,double[] marks)
{
this.reg = reg;
this.year = year;
this.branch = branch;
this.name = name;
this.sem = sem;
this.marks = marks;
}

public void detail()


{
System.out.println("Name: "+this.name);
System.out.println("RegNo: "+this.reg);
System.out.println("branch: "+this.branch);
System.out.println("Sem: "+this.sem);
}

public double total()


{
double sum = 0;
for(int i=0;i<this.marks.length;i++)
{
sum = sum + this.marks[i];
}
return sum;
}

public char getGrade(double total)


{
char grade = 'F';
if (total>90)
grade = 'S';
else if(total>80)
grade = 'A';
else if(total>70)
grade = 'B';
else if(total>60)
grade = 'C';
else if(total>50)
grade = 'D';
else if(total>40)
grade = 'C';
return grade;
}
}
public class Main {

public static void main(String[] args) {


double[] marks = {80,88,75,90,92};
Student s = new
Student("19BCE0172","2021","CSE","Aman",4,marks);
s.detail();
System.out.println(s.total());
System.out.println(s.getGrade(s.total()));
}

}
OUTPUT:
17. Write a program that displays an invoice of several items. Create a class
called Item with members item_name, quantity, price and total_cost and
methods to get and set values for the members. Derive a new class to print the
bill using Item class.

import java.util.Scanner;

public class Invoice

private int item_number;

private String name;

private int quantity;

private double price;

private double total_cost;

public Invoice(int item_num, String nm, int quan, double pri)

item_number = item_num;

name = nm;

quantity = quan;

price = pri;

total_cost = 0;

}
public int getitem_number()

return item_number;

public String getname()

return name;

public int getquantity()

return quantity;

public double getprice()

return price;

public double gettotal_cost()

return total_cost;

}
public void setitem_number( int item_n)

item_number = item_n;

public void setname(String n)

name = n;

public void setquantity(int quan)

quantity = quan;

total();

public void setprice(double pri)

price = pri;

total();

public void total()

{
total_cost = price * quantity;

public void displayLine()

System.out.println("Item Number: "+item_number);

System.out.println("Name: "+name);

System.out.println("Quantity: "+quantity);

System.out.println("Price: "+price);

System.out.println("Total Cost: "+total_cost);

import java.util.Scanner;

public class InvoiceDriver {

public static void main(String[] args) {

Invoice check1 = new Invoice(112, "Book", 3, 125.98);

Invoice check2 = new Invoice(101, "Phone", 2, 456.35);

Invoice check3 = new Invoice(187, "Laptop", 1, 2345.68);


items(check1,check2, check3);

public static void items(Invoice chk1, Invoice chk2, Invoice chk3)

Scanner sn = new Scanner(System.in);

//-----------------------------------------------------------

System.out.println("Please enter Item Number: ");

chk1.setitem_number(sn.nextInt());

System.out.println("Please enter Item Name: ");

chk1.setname(sn.next());

System.out.println("Please enter quantity: ");

chk1.setquantity(sn.nextInt());

System.out.println("Please enter price: ");

chk1.setprice(sn.nextDouble());

//-----------------------------------------------------------
//-----------------------------------------------------------

System.out.println("Please enter Item Number: ");

chk2.setitem_number(sn.nextInt());

System.out.println("Please enter Item Name: ");

chk2.setname(sn.next());

System.out.println("Please enter quantity: ");

chk2.setquantity(sn.nextInt());

System.out.println("Please enter price: ");

chk2.setprice(sn.nextDouble());

//-----------------------------------------------------------

//-----------------------------------------------------------

System.out.println("Please enter Item Number: ");

chk3.setitem_number(sn.nextInt());

System.out.println("Please enter Item Name: ");

chk3.setname(sn.next());
System.out.println("Please enter quantity: ");

chk3.setquantity(sn.nextInt());

System.out.println("Please enter price: ");

chk3.setprice(sn.nextDouble());

//-----------------------------------------------------------

chk1.displayLine();

chk2.displayLine();

chk3.displayLine();

}
18. Create a class Telephone with two members to hold customer’s name and
phone number. The class should have appropriate constructor, input and
display methods. Derive a class TelephoneIndex with methods to change the
name or phone number.Create an array of objects and perform the following
functions. a. Search for a name when the user enters a name or the first few
characters. b. Display all of the names that match the user’s input and their
corresponding phone numbers. c. Change the name of a customer. d. Change
the phone number of a customer.
import java.io.*;

public class PhoneDirectory {

/* The data for the directory is stored in a pair of arrays. The


phone
number associated with the name names[i] is numbers[i]. These
arrays will grow, as necessary, to accommodate as many entries as
are added to the directory. The variable count keeps track of
the number of entires in the directory. */

private String[] names = new String[1];


private String[] numbers = new String[1];
private int count = 0;
public boolean changed; // This variable is set to true whenever a
change
// is made to the data in this directory.
The value
// is false when the object is created.
The only time
// that it is reset to false is if the
load() method
// is used to load a phone directory from a
stream.
// (Programs that use the directory can
also set the
// value of changed if they want, since
it's public.)

public void load(TextReader in) throws IOException {


// Clears any entries currently in the directory, and loads
// a new set of directory entries from the TextReader. The
// data must consist of the following: a line containing the
// number of entries in the directory; two lines for each
// entry, with the name on the first line and the associated
// number on the second line. Note that this method might
// throw an IllegalArgumentException if the data in the file
// is not valid -- for example if the same name occurs twice.
// Note that if an error does occur, then the original
// data in the directory remains.
int newCount = in.getlnInt();
String[] newNames = new String[newCount + 5];
String[] newNumbers = new String[newCount + 5];
for (int i = 0; i < newCount; i++) {
newNames[i] = in.getln();
newNumbers[i] = in.getln();
}
count = newCount;
names = newNames;
numbers = newNumbers;
changed = false;
}

public void save(PrintWriter out) {


// Saves all the entries in the directory to the PrintWriter.
// Data is written in the same format that is used in the
load()
// method. Note that PrintWriters do not throw exceptions.
// To test whether the data was written successfully, the
// caller of this routine can call out.checkError().
out.println(count);
for (int i = 0; i < count; i++) {
out.println(names[i]);
out.println(numbers[i]);
}
}
public String numberFor(String name) {
// Get the phone number associated with the given name, if
any.
// If the name does not exist in the directory, null is
returned. The
// name cannot be null. (If it is, an
IllegalArgumentException is thrown.)
if (name == null)
throw new IllegalArgumentException("Name cannot be null in
numberFor(name)");
int position = indexOf(name);
if (position == -1)
return null;
else
return numbers[position];
}

public void addNewEntry(String name, String number) {


// Create a new entry in the directory for the given name and
number.
// An IllegalArgumentException is thrown if the name is
already in
// the directory or if either of the parameters is null. If
the
// arrays, "names" and "numbers", that hold the data are full,
// replace them with larger arrays.
if (name == null)
throw new IllegalArgumentException("Name cannot be null in
addNewEntry(name,number)");
if (number == null)
throw new IllegalArgumentException("Number cannot be null in
addNewEntry(name,number)");
int position = indexOf(name);
if (position != -1)
throw new IllegalArgumentException("Name already exists in
addNewEntry(name,number).");
if (count == names.length) {
String[] tempNames = new String[ 2*count ];
String[] tempNumbers = new String[ 2* count];
System.arraycopy(names, 0, tempNames, 0, count);
System.arraycopy(numbers, 0, tempNumbers, 0, count);
names = tempNames;
numbers = tempNumbers;
}
names[count] = name;
numbers[count] = number;
count++;
changed = true;
}

public void deleteEntry(String name) {


// Remove the entry for the specified name from the directory,
if
// there is one. If the specified name does not exist in the
// directory, nothing is done and no error occurs.
if (name == null)
return;
int position = indexOf(name);
if (position == -1)
return;
names[position] = names[count-1];
numbers[position] = numbers[count-1];
count--;
changed = true;
}

public void updateEntry(String name, String number) {


// Change the number associated with the given name. An
IllegalArgumentException
// is thrown if the name does not exist in the directory or
if either of
// the parameters is null.
if (name == null)
throw new IllegalArgumentException("Name cannot be null in
updateEntry(name,number)");
if (number == null)
throw new IllegalArgumentException("Number cannot be null in
updateEntry(name,number)");
int position = indexOf(name);
if (position == -1)
throw new IllegalArgumentException("Name not found in
updateEntry(name,number).");
numbers[position] = number;
changed = true;
}

private int indexOf(String name) {


// Finds and returns the position of the name in the names
array,
// ignoring case. Returns -1 if the name does not occur in the
// array.
for (int i = 0 ; i < count; i++) {
if (names[i].equalsIgnoreCase(name))
return i;
}
return -1;
}

} // end class PhoneDirectory

The main program:


import java.io.*;

public class Phones {

static final String DEFAULT_FILENAME =


"phones.dat";

static PhoneDirectory directory; // Holds the


data for
// the
phone directory.

public static void main(String[] args) {

String fileName; // Name of file that


stores the directory data.
boolean done; // Set to true when the user
wants to exit the program.

/* Get the file name from the command line,


or use the
DEFAULT_FILENAME if there is no command-
line argument. */

if (args.length == 0)
fileName = DEFAULT_FILENAME;
else
fileName = args[0];

/* Read the phone directory data from the


file. This routine
might terminate the program if an error
occurs when the
attempt is made to end the data. */

readPhoneData(fileName);
/* Show user a menu of available
operations, get the user's
choice, and carry it out. Repeat until
the user selects
the "Exit from this program" operation.
Each of the other
four commands is carried out by calling
a subroutine. */

done = false;

while (done == false) {


TextIO.putln();
TextIO.putln();
TextIO.putln("Select the operation you
want to perform:");
TextIO.putln();
TextIO.putln(" 1. Look up a phone
number");
TextIO.putln(" 2. Add an entry to
the directory");
TextIO.putln(" 3. Delete an entry
from the directory");
TextIO.putln(" 4. Change someone's
phone number");
TextIO.putln(" 5. Exit form this
program.");
TextIO.putln();
TextIO.put("Enter the number of your
choice: ");
int menuOption = TextIO.getlnInt();
switch (menuOption) {
case 1:
doLookup();
break;
case 2:
doAddEntry();
break;
case 3:
doDeleteEntry();
break;
case 4:
doModifyEntry();
break;
case 5:
done = true;
break;
default:
System.out.println("Illegal
choice! Please try again.");
} // end switch
} // end while

/* If the phone directory data has been


modified, write the
changed data back to the file. */

if (directory.changed == true)
writePhoneData(fileName);

TextIO.putln("\nExiting program.");

} // end main()

static void readPhoneData(String fileName) {


// Get the data for the phone directory
from the specified
// file. Terminate the program if an
error occurs. If the
// file does not exist, give the user
the option of creating
// it.
TextReader in; // A stream for reading the
data.
try {
// Try to create a stream for reading
from the file.
// If the file is not found, set the
value of in to null.
in = new TextReader( new
FileReader(fileName) );
}
catch (Exception e) {
in = null;
}
if (in == null) {
// The specified file could not be
opened. Give the
// user the option of creating a
new, empty file.
TextIO.putln("\nThe file \"" + fileName
+ "\" does not exist.");
TextIO.put("Do you want to create the
file? ");
boolean create = TextIO.getlnBoolean();
if (create == false) {
TextIO.putln("Program aborted.");
System.exit(0);
}
directory = new PhoneDirectory(); // A
new, empty phone directory.
try {
// Try to create the file.
PrintWriter out = new PrintWriter(
new FileWriter(fileName) );
directory.save(out);
if (out.checkError())
throw new Exception();
TextIO.putln("Empty directory
created.");
}
catch (Exception e) {
TextIO.putln("Can't create file.");
TextIO.putln("Program aborted.");
System.exit(0);
}
}
else {
// The input stream was created
successfully. Get the data.
try {
directory = new PhoneDirectory();
// A new, empty directory.
directory.load(in); // Try to load
it with data from the file.
}
catch (Exception e) {
TextIO.putln("An error occurred while
read data from \"" + fileName + "\":");
TextIO.putln(e.toString());
TextIO.putln("Program aborted.");
System.exit(0);
}
}
} // end readPhoneData()

static void writePhoneData(String fileName) {


// Save the data from the phone directory
to the specified file.
PrintWriter out;
try {
out = new PrintWriter( new
FileWriter(fileName) );
}
catch (Exception e) {
TextIO.putln("\nCan't open file for
output!");
TextIO.putln("Changes have not been
saved.");
return;
}
directory.save(out);
if (out.checkError()) {
TextIO.putln("Some error occurred while
saving data to a file.");
TextIO.putln("Sorry, but your phone
directory might be ruined");
}
}

static void doLookup() {


// Carry out the "Look up a phone
number" command. Get
// a name from the user, then find and
print the associated
// number if any.
TextIO.putln("\nLook up the name: ");
String name = TextIO.getln();
String number = directory.numberFor(name);
if (number == null)
TextIO.putln("\nNo such name in the
directory.");
else
TextIO.putln("\nThe number for " + name
+ " is " + number);
}

static void doAddEntry() {


// Carry out the "Add an entry to the
directory" command.
// This will only work if the name that
the user specifies
// does not already exist in the
directory. If it does,
// print an error message and exit.
Otherwise, get the
// number for that person from the user
and add the entry
// to the directory.
TextIO.putln("\nAdd entry for this name:
");
String name = TextIO.getln();
if (directory.numberFor(name) != null) {
TextIO.putln("That name is already in
the directory.");
TextIO.putln("Use command number 4 to
change the entry for " + name);
return;
}
TextIO.putln("What is the number for " +
name + "? ");
String number = TextIO.getln();
directory.addNewEntry(name,number);
}

static void doDeleteEntry() {


// Carry out the "Delete an entry from
the directory" command.
// Get the name to be deleted from the
user and delete it.
// If the name doesn't exist in the
directory, print a message.
TextIO.putln("\nDelete the entry for this
name: ");
String name = TextIO.getln();
if (directory.numberFor(name) == null)
TextIO.putln("There is not entry for " +
name);
else {
directory.deleteEntry(name);
TextIO.putln("Entry deleted.");
}
}

static void doModifyEntry() {


// Carry out the "Change someone's
phone number" command.
// Get the name from the user. If the
name does not exist
// in the directory, print a message
and exit. Otherwise,
// get the new number for that person
and make the change.
TextIO.putln("\nChange the number for this
name: ");
String name = TextIO.getln();
if (directory.numberFor(name) == null) {
TextIO.putln("That name is not in the
directory.");
TextIO.putln("Use command number 2 to
add an entry for " + name);
return;
}
TextIO.putln("What is the new number for "
+ name + "? ");
String number = TextIO.getln();
directory.updateEntry(name,number);
}

} // end class Phones

19. Create an abstract class called BankAccount with members customer name,
date of birth, address, account number, balance and member functions to get
values for the members and display it. Derive a class SavingsAccount with
member functions to perform deposit and withdraw in the account. Write a
menu driven program to create a new account, perform withdraw, deposit and
delete an account.

class BankAccount
{
// instance variable

private String accountNum; // the account number


private double balance; // the amount on deposit

/**
* Constructs a bank account with an account number and initial balance
*
* @param acctNum the account number
* @param initialBalance the initial balance
*/
public BankAccount(String acctNum, double initialBalance)
{
accountNum = acctNum;
balance = initialBalance;
}

/**
* Deposits money into the bank account.
*
* @param amount the amount to deposit
*/
public void deposit(double amount) // note "mutator" method
{
double newBalance = balance + amount;
balance = newBalance; // modifies instance
var
}

/**
* Withdraws money from the bank account.
*
* @param amount the amount to withdraw
*/
public void withdraw(double amount) // note "mutator" method
{
double newBalance = balance - amount;
balance = newBalance; // modifies instance var
}

/**
* Gets the account number
*
* @return the account number
*/
public String getAccount() // note "accessor" method
{
return accountNum; // returns value of instance var
}

/**
* Gets the current balance
*
* @return the balance
*/
public double getBalance() // note "accessor" method
{
return balance; // returns value of instance var
}

/**
* Transfer funds from one bank account object to another
*
* @param destination the BankAccount object receiving the funds
* @param amount the amount of money to be transferred
*/
public void transferFundsA(BankAccount destination, double amount)
{
destination.balance = destination.balance + amount;
// note explicit use of this to reference instance variables of the
// object for which the method was called
this.balance = this.balance - amount;
}

// Another way to transfer funds - by calling deposit and withdraw methods.


// Shows explicit use of "this" to call another method for the same object
// for which the current method was called.
public void transferFundsB(BankAccount destination, double amount)
{
destination.deposit(amount); // deposit to "destination" account
this.withdraw(amount); // withdraw from this account
}
}
//******************** end of BankAccount class definition
********************

/**
* A class to test the BankAccount2 class
*/
public class BankAccountTest2
{

public static void main(String[] args)


{
// create two BankAccount objects
BankAccount first = new BankAccount("1111111", 20000);
BankAccount second = new BankAccount("2222222", 30000);

// print initial balances


System.out.printf("Account #%s has initial balance of $%.2f%n",
first.getAccount(), first.getBalance());

System.out.printf("Account #%s has initial balance of $%.2f%n",


second.getAccount(), second.getBalance());

// transfer $5000 from first to second account (via transferFundsA())


first.transferFundsA(second, 5000);

// print new balances


System.out.println("\nAfter \"first.transferFunds(second, 5000)\" ...");
System.out.printf("Account #%s has new balance of $%.2f%n",
first.getAccount(), first.getBalance());

System.out.printf("Account #%s has new balance of $%.2f%n",


second.getAccount(), second.getBalance());

// transfer $10000 from second account to first (via transferFundsB())


second.transferFundsB(first, 10000);

// print new balances


System.out.println("\nAfter \"second.transferFunds(first, 10000)\" ...");
System.out.printf("Account #%s has new balance of $%.2f%n",
first.getAccount(), first.getBalance());

System.out.printf("Account #%s has new balance of $%.2f%n",


second.getAccount(), second.getBalance());
}
}
OUTPUT

20. Create an Interface with methods add(), sub(), multiply() and divide().
Write two classes FloatValues to perform arithmetic operations on floating
point numbers and IntegerValues on integer numbers by implementing the
interface.

public class Main {

public static void main(String[] args) {

// write your code here

FloatValues f = new FloatValues(3.5f,4.5f);

f.add();

f.sub();
f.divide();

f.multiply();

IntegerValues i = new IntegerValues(3,4);

i.add();

i.sub();

i.divide();

i.multiply();

interface calculator {

public void add();

public void sub();

public void multiply();

public void divide();

class FloatValues implements calculator{

float a;
float b;

public FloatValues(float a, float b) {

System.out.println("Floating point calculator");

this.a = a;

this.b = b;

@Override

public void add() {

System.out.println("addition of 2 numbers = "+(a+b));

@Override

public void sub() {

System.out.println("Subtraction of 2 numbers = "+(a-b));

@Override

public void multiply() {


System.out.println("Multiplication of 2 numbers = "+(a*b));

@Override

public void divide() {

System.out.println("Multiplication of 2 numbers = "+(a/b));

class IntegerValues implements calculator{

int a;

int b;

public IntegerValues(int a, int b) {

System.out.println("Integer point calculator");

this.a = a;

this.b = b;

}
@Override

public void add() {

System.out.println("addition of 2 numbers = "+(a+b));

@Override

public void sub() {

System.out.println("Subtraction of 2 numbers = "+(a-b));

@Override

public void multiply() {

System.out.println("Multiplication of 2 numbers = "+(a*b));

@Override

public void divide() {

System.out.println("Multiplication of 2 numbers = "+(a/b));

}
}

You might also like