0% found this document useful (0 votes)
102 views50 pages

CSE-1007 (Java Programming) Digital Assignment-1

The document contains code for 11 Java programs that perform various tasks: 1) Find the factorial of a number using command line arguments 2) Print the multiplication table of a number 3) Check if a number is an Armstrong number 4) Check if a number is a prime number 5) Generate patterns of increasing numbers and stars 6) Generate the Fibonacci series 7) Sort numbers in ascending order 8) Search for a number using binary search 9) Read numbers and calculate their sum and average 10) Convert a number between decimal, binary, octal, and hexadecimal 11) Provide a menu-driven program to append, insert, or delete from a string

Uploaded by

Ayush Roy
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)
102 views50 pages

CSE-1007 (Java Programming) Digital Assignment-1

The document contains code for 11 Java programs that perform various tasks: 1) Find the factorial of a number using command line arguments 2) Print the multiplication table of a number 3) Check if a number is an Armstrong number 4) Check if a number is a prime number 5) Generate patterns of increasing numbers and stars 6) Generate the Fibonacci series 7) Sort numbers in ascending order 8) Search for a number using binary search 9) Read numbers and calculate their sum and average 10) Convert a number between decimal, binary, octal, and hexadecimal 11) Provide a menu-driven program to append, insert, or delete from a string

Uploaded by

Ayush Roy
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/ 50

CSE-1007 (Java Programming)

DIGITAL ASSIGNMENT-1
Name: - Ayush Roy Slot: - L51+L52
Reg No: - 20BCE0260 Date: - 10/09/21

1) Write a program to find the factorial of a number using command line


arguments.

Code: -
public class factorial
{
public static void main (String args[])
{
int n,i,fact=1;
n=Integer.parseInt(args[0]);
for(i=1;i<=n;i++)
{
fact=fact*i;
}
System.out.println("The factorial is: "+fact);
}
}

Sample I/O: -
2) Write a program to print the multiplication table of a number.

Code: -

import java.util.*;
public class multiplication
{
public static void main (String args[])
{
Scanner sc= new Scanner(System.in);
int n,i,limit;
System.out.println("Enter the number whose table you want: ");
n=sc.nextInt();
System.out.println("Enter the number upto which you want the table: ");
limit=sc.nextInt();

for(i=1;i<=limit;i++)
{
System.out.println(n+" * "+i+" = "+(n*i));
}
}
}

Sample I/O: -
3) Write a program to check whether the given number is an Armstrong
number or not.

Code: -

import java.util.*;
public class armstrong
{
public static void main (String args[])
{
Scanner sc= new Scanner(System.in);
int n,temp,rem,sum;
System.out.println("Enter the number: ");
n=sc.nextInt();
temp=n;

sum=0;
while (temp>0)
{
rem=temp%10;
sum=sum+(int)(Math.pow(rem,3));
temp=temp/10;
}

if(n==sum)
System.out.println(n+" is an Armstrong number.");
else
System.out.println(n+" is not an Armstrong number.");
}
}
Sample I/O: -
4) Write a program to check whether the given number is a prime number
or not.

Code: -

import java.util.*;
public class prime
{
public static void main (String args[])
{
Scanner sc= new Scanner(System.in);
int n,i,count=0;
System.out.println("Enter the number: ");
n=sc.nextInt();

if(n==0||n==1)
{
System.out.println(n+" is not a Prime number.");
}
else
{
count=0;
for(i=1;i<=n;i++)
{
if(n%i==0)
count++;
}
if(count<=2)
System.out.println(n+" is a Prime number.");
else
System.out.println(n+" is not a Prime number.");
}
}
}

Sample I/O: -
5) Write a program to generate the following patterns: -
(i) 1
1 2
1 2 3

Code: -

import java.util.*;
public class pattern1
{
public static void main(String args[])
{
int i,j,n;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of rows: ");
n=sc.nextInt();

System.out.println("Here is the required pattern!");


for(i=1;i<=n;i++)
{
for (j=1;j<=i;j++)
{
System.out.print(j);
}
System.out.println();
}
}
}
Sample I/O: -

(ii) *

* *

* * *

* *

Code: -

import java.util.*;
public class pattern2
{
public static void main(String args[])
{
int n, i, j, space = 1;
System.out.print("Enter the number of rows: ");
Scanner s = new Scanner(System.in);
n = s.nextInt();
space = n - 1;
for (j = 1; j <= n; j++)
{
for (i = 1; i <= space; i++)
{
System.out.print(" ");
}
space--;
for (i = 1; i <= 2 * j - 1; i++)
{
System.out.print("*");
}
System.out.println("");
}
space = 1;
for (j = 1; j <= n - 1; j++)
{
for (i = 1; i <= space; i++)
{
System.out.print(" ");
}
space++;
for (i = 1; i <= 2 * (n - j) - 1; i++)
{
System.out.print("*");
}
System.out.println("");
}
}
}

Sample I/O: -
6) Write a program to generate the Fibonacci series.

Code: -

import java.util.*;
public class pattern2
{
public static void main(String args[])
{
int n,i,a=0,b=1,c;
System.out.print("Enter the number of terms: ");
Scanner sc = new Scanner(System.in);
n = sc.nextInt();

System.out.println("Here is the required series! ");


System.out.print(a+" "+b+" ");
for(i=1;i<=n-2;i++)
{
c=a+b;
System.out.print(c+" ");
a=b;
b=c;
}
}
}

Sample I/O: -
7) Write a program to sort n numbers in ascending order.

Code: -

import java.util.*;
public class ascsorting
{
public static void main(String args[])
{
int n,i,j,temp=0;
System.out.println("Enter the number of terms: ");
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
int arr[] = new int[n];

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


for(i=0;i<arr.length;i++)
{
arr[i]=sc.nextInt();
}

System.out.println("Elements of the original array: ");


for(i=0;i<arr.length;i++)
{
System.out.print(arr[i]+" ");
}

for(i=0;i<arr.length;i++)
{
for(j=i+1;j<arr.length;j++)
{
if(arr[j]<arr[i])
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}

System.out.println("\nElements of array sorted in ascending order: ");


for(i=0;i<arr.length;i++)
{
System.out.print(arr[i]+" ");
}
}
}

Sample I/O: -
8) Write a program to search a number among n numbers using binary
search.

Code: -

import java.util.*;
public class binarysearch
{
public static void main(String args[])
{
//binary search works only on sorted arrays. So we are sorting first using bubble sort
technique.
int n,i,j,key,low,high,mid=0,flag=0,temp;
System.out.println("Enter the number of terms: ");
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
int arr[] = new int[n];

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


for(i=0;i<arr.length;i++)
{
arr[i]=sc.nextInt();
}

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


{
for (j = i + 1; j < n; j++)
{
if (arr[i] > arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
System.out.println("Sorted Array is:");
for (i = 0; i < n; i++)
{
System.out.print(arr[i]+" ");
}

System.out.println("\nEnter the number you wanna search for: ");


key=sc.nextInt();
low=0;
high=n-1;

while(low<=high)
{
mid=(low+high)/2;
if(arr[mid]==key)
{
flag=1;
break;
}
else if(arr[mid]<key)
{
low=mid+1;
}
else
high=mid-1;
}
if(flag==0)
System.out.println("Element not found!");
else
System.out.println("Element is found at position "+(mid+1)+" in the sorted array");
}
}

Sample I/O: -
9) Write a program to read ‘n’ numbers and print their sum and average.

Code: -

import java.util.*;
public class sumavg
{
public static void main(String args[])
{
int n,i,sum=0;
float avg=0.0f;
System.out.println("Enter the number of terms: ");
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
int arr[] = new int[n];

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


for(i=0;i<arr.length;i++)
{
arr[i]=sc.nextInt();
sum+=arr[i];
}

avg=(float)sum/n;
System.out.println("Sum of numbers= "+sum+" and average of numbers= "+avg);
}
}
Sample I/O: -
10) Write a program that accepts a number as input and convert them to
binary, octal and hexadecimal equivalents.

Code: -

import java.util.*;
public class conversion
{
public static void main(String args[])
{
int n;
String hexa,octal,binary;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the decimal number: ");
n=sc.nextInt();

hexa=Integer.toHexString(n);
octal=Integer.toOctalString(n);
binary=Integer.toBinaryString(n);

System.out.println("Hexadecimal value of the given decimal number is : " + hexa);


System.out.println("Octal value of the given decimal number is : " + octal);
System.out.println("Binary value of the given decimal number is : " + binary);
}
}

Sample I/O: -
11) Write a menu driven program to (i) append a string (ii) insert a string
and (iii) delete a portion of the string.

Code: -

import java.util.*;
public class conversion
{
public static void main(String args[])
{
int ch;
Scanner sc = new Scanner(System.in);
System.out.println("1.APPEND 2.INSERT 3.DELETE 4.EXIT");
System.out.println("Enter your choice: ");
ch=sc.nextInt();

transfer t = new transfer();


switch(ch)
{
case 1:
t.append();
break;
case 2:
t.insert();
break;
case 3:
t.delete();
break;
case 4:
System.exit(0);
break;
default :
System.out.println("Wrong choice! Try again");
}
}
}

class transfer
{
int i,index,start,end;
Scanner sc = new Scanner(System.in);

void append()
{
System.out.println("Enter first string: ");
String s1 = new String();
sc.next();
System.out.println("Enter string you want to append to the first string: ");
String s2 = new String();
sc.next();
String s3 = new String();
s3=s1.concat(s2);
System.out.println("Appended string is : "+s3);
}

void insert()
{
System.out.println("Enter first string: ");
String originalString = new String();
originalString = sc.next();
System.out.println("Enter string to be inserted: ");
String stringInserted = new String();
stringInserted=sc.next();
System.out.println("Enter index where string is to be inserted: ");
index=sc.nextInt();

String newString = new String();


for (i = 0; i < originalString.length(); i++)
{
newString += originalString.charAt(i);
if (i == index)
{
newString += stringInserted;
}
}
System.out.println("Modified String is: "+newString);
}

void delete()
{
System.out.println("Enter original string: ");
String s1 = new String();
s1=sc.next();
String s2 = new String();
System.out.println("Enter start and end points of deletion: ");
start=sc.nextInt();
end=sc.nextInt();
s2=s1.substring(0,start-1)+s1.substring(end,s1.length());
System.out.println("Modified string after deletion is: "+s2);
}
}
Sample I/O: -
12) Write a program to check whether a string is palindrome or not
without using functions.

Code: -

import java.util.*;
public class Palindrome
{
public static void main(String args[])
{
String str, rev = "";
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string:");
str = sc.next();

int length = str.length();


for ( int i = length - 1; i >= 0; i-- )
rev = rev + str.charAt(i);

if (str.equals(rev))
System.out.println(str+" is a palindrome");
else
System.out.println(str+" is not a palindrome");
}
}

Sample I/O: -
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.*;
public class conversion
{
public static void main(String args[])
{
int ch;
Scanner sc = new Scanner(System.in);
System.out.println("1.COMPARE 2.CHARACTER AT SPECIFIED POSITION
3.SUBSTRING 4.REPLACE 5.POSITION OF SPECIFIED CHARACTER 6.EXIT");
System.out.println("Enter your choice: ");
ch=sc.nextInt();

transfer t = new transfer();


switch(ch)
{
case 1:
t.compare();
break;
case 2:
t.chrspepo();
break;
case 3:
t.sub();
break;
case 4:
t.replace();
break;
case 5:
t.pospechr();
break;
case 6:
System.exit(0);
break;
default :
System.out.println("Wrong choice! Try again");
}
}
}

class transfer
{
int i,index,start,end,pos=0;
char c,c1;
Scanner sc = new Scanner(System.in);

void compare()
{
System.out.println("Enter first string: ");
String s1 = new String();
s1=sc.next();
System.out.println("Enter second string: ");
String s2 = new String();
s2=sc.next();
if(s1.compareTo(s2)<0)
System.out.println("2nd string is larger");
else if(s1.compareTo(s2)>0)
System.out.println("1st string is larger");
else
System.out.println("Strings are same");
}

void chrspepo()
{
System.out.println("Enter the string: ");
String s1 = new String();
s1 = sc.next();
System.out.println("Enter position of required character: ");
index=sc.nextInt();
c=s1.charAt(index-1);
System.out.println("Character at specified position is: "+c);
}

void sub()
{
System.out.println("Enter original string: ");
String s = new String();
s=sc.next();
System.out.println("Enter start and end indices of extraction: ");
start=sc.nextInt();
end=sc.nextInt();
String s1 = new String();
s1=s.substring(start,end+1);
System.out.println("Substring extracted is: "+s1);
}

void replace()
{
System.out.println("Enter the string: ");
String s1 = new String();
s1 = sc.next();
String s2 = new String();
System.out.println("Enter character which you want to replace: ");
c=sc.next().charAt(0);
System.out.println("Enter replacing character: ");
c1=sc.next().charAt(0);
s2=s1.replace(c,c1);
System.out.println("Modified string is: "+s2);
}

void pospechr()
{
System.out.println("Enter the string: ");
String s1 = new String();
s1 = sc.next();
System.out.println("Enter character whose position you want: ");
c=sc.next().charAt(0);
pos=s1.indexOf(c);
System.out.println("Position of specified character is: "+(pos+1));
}
}

Sample I/O: -
14) Write a program to change the case of the letters in a string. Eg.
ABCdef -> abcDEF.

Code: -
import java.util.*;
public class topsyturvy
{
public static void main(String args[])
{
String str,newstr="";
int i;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string:");
str = sc.next();

for(i=0;i<str.length();i++)
{
if(Character.isLowerCase(str.charAt(i)))
newstr+=Character.toUpperCase(str.charAt(i));
if(Character.isUpperCase(str.charAt(i)))
newstr+=Character.toLowerCase(str.charAt(i));
}

System.out.println("New string is: "+newstr);


}
}

Sample I/O: -
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.*;
public class threemethods
{
public static void main(String args[])
{
String str,str2;

Scanner sc = new Scanner(System.in);


System.out.println("1.FOR WORD COUNT-->");
System.out.println("Enter the string whose words you want to count: ");
str=sc.nextLine();
wordCount(str);

System.out.println("2.FOR ARRAY TO STRING-->");


System.out.println("Enter the character array which you want to convert to string: ");
char ch[]=sc.nextLine().toCharArray();
arrayToString(ch);

System.out.println("3.FOR MOST FREQUENT CHARACTER IN STRING-->");


System.out.println("Enter the string whose most frequent word you want to find: ");
str2=sc.nextLine();
mostFrequent(str2);
}

static void wordCount(String str)


{
int c=0;
for(int i=0;i<str.length();i++)
{
if (str.charAt(i)==' ')
c++;
}
System.out.println("Number of words in the string are: "+(c+1));
}

static void arrayToString(char ch[])


{
String str1 = new String(ch);
System.out.println("The string from character array is: "+str1);
}

static void mostFrequent(String str2)


{
int max=0,i,j;
int freq[]=new int[str2.length()];
char maxChar=str2.charAt(0);
char string[]=str2.toCharArray();

for(i=0;i<string.length;i++)
{
freq[i]=1;
for(j = i+1; j < string.length; j++)
{
if(string[i] == string[j] && string[i] != ' ' && string[i] != '0')
{
freq[i]++;
string[j]='0';
}
}
}
max=freq[0];
for(i = 0; i <freq.length; i++)
{
if(max < freq[i])
{
max = freq[i];
maxChar = string[i];
}
}
System.out.println("Maximum occurring character: " + maxChar);
}
}

Sample I/O: -
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: -
import java.util.*;
public class Student
{
public static void main(String args[])
{
System.out.println("ENTER STUDENT DETAILS: ");
System.out.println("-----------------------");
details();
System.out.println();
System.out.println("ENTER MARKS DETAILS AND GET GRADE DETAILS: ");
System.out.println("-------------------------------------------");
marksgrade();
}

static void details()


{
int yr,sem;
String regno,name,branch;
Scanner sc = new Scanner(System.in);
System.out.println("Enter registration number: ");
regno=sc.nextLine();
System.out.println("Enter name: ");
name=sc.nextLine();
System.out.println("Enter branch: ");
branch=sc.nextLine();
System.out.println("Enter year: ");
yr=sc.nextInt();
System.out.println("Enter semester: ");
sem=sc.nextInt();
}

static void marksgrade()


{
int marks[]=new int[5];
int tot=0;
float avg=0.0f;
Scanner sc = new Scanner(System.in);
for(int i=0;i<5;i++)
{
System.out.println("Enter marks "+(i+1));
marks[i]=sc.nextInt();
tot=tot+marks[i];
}
for(int i=0;i<5;i++)
{
System.out.println("Marks "+(i+1)+" is "+marks[i]);
}
System.out.println("Total marks scored is: "+tot);
avg=(float)tot/5;
System.out.println("Average of the student is: "+avg);

if(avg>=90 && avg<=100)


System.out.println("Grade is S");
else if(avg>=80)
System.out.println("Grade is A");
else if(avg>=70)
System.out.println("Grade is B");
else if(avg>=60)
System.out.println("Grade is C");
else if(avg>=50)
System.out.println("Grade is D");
else if(avg>=40)
System.out.println("Grade is E");
else
System.out.println("Grade is F. You have failed!");
}
}

Sample I/O: -
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.

Code: -
import java.util.*;
public class Item
{
static String item_name;
static float quantity,price,total_cost;
public static void main(String args[])
{
System.out.println("GET VALUES FROM USER: ");
System.out.println("----------------------");
get();
billing b1 = new billing();
b1.getCost();
System.out.println();
System.out.println("SET PREDEFINED VALUES FROM SYSTEM: ");
System.out.println("-----------------------------------");
set();
billing b2 = new billing();
b2.getCost();
System.out.println();
}

static void get()


{
Scanner sc=new Scanner(System.in);
System.out.println("Enter item name: ");
item_name=sc.nextLine();
System.out.println("Enter quantity: ");
quantity=sc.nextFloat();
System.out.println("Enter price of item: ");
price=sc.nextFloat();
}

static void set()


{
item_name="Frooty";
quantity=10.0f;
price=15.0f;
}
}

class billing extends Item


{
void getCost()
{
total_cost=quantity*price;
System.out.println("Total cost of "+item_name+" is: "+total_cost);
}
}

Sample I/O: -
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.

Code: -
import java.util.*;
class Telephone
{
private String name;
private String phoneNumber;
public Telephone()
{}
public Telephone(String name, String phoneNumber)
{
this.name = name;
this.phoneNumber = phoneNumber;
}
public String getName()
{
return name;
}
public void setName(String s)
{
this.name = s;
}
public String getNumber()
{
return phoneNumber;
}
public void setNumber(String phoneNumber)
{
this.phoneNumber = phoneNumber;
}
}

class TelephoneIndex extends Telephone


{
public TelephoneIndex()
{}
public TelephoneIndex(String name, String phoneNumber)
{
super(name,phoneNumber);
}
public void changeName(String s)
{
setName(s);
}
public void changeNumber(String phoneNumber)
{
setNumber(phoneNumber);
}
}

public class Jumbo


{
public static void main(String args[])
{
TelephoneIndex[] arr=new TelephoneIndex[5];
arr[0] = new TelephoneIndex("Ayush", "7872739955");
arr[1] = new TelephoneIndex("Ayan", "7363959263");
arr[4] = new TelephoneIndex("Rahul", "9749181536");
arr[2] = new TelephoneIndex("Anish", "7001639403");
arr[3] = new TelephoneIndex("Devil", "8918477263");
Scanner sc= new Scanner(System.in);
System.out.print("Enter the string for search: ");
String search=sc.nextLine();
//1st part
boolean first=true;
for(int i=0;i<5;i++)
{
if(arr[i].getName().substring(0,search.length()).equals(search))
{
if(first)
{
System.out.println("Names found:");
first=false;
}
System.out.println(arr[i].getName());
}
}
if(first)
{
System.out.println("No results found");
}
//2nd part
System.out.print("Enter the string for search to get corresponding phone no.: ");
search=sc.nextLine();
first=true;
for(int i=0;i<5;i++)
{
if(arr[i].getName().substring(0,search.length()).equals(search))
{
if(first)
{
System.out.println("\nNames & numbers found:");
first=false;
}
System.out.println(arr[i].getName()+" Phone-> "+arr[i].getNumber());
}
}
if(first)
{
System.out.println("No results found ");
}
//3rd part
System.out.print("Enter the full name of the customer whose name is to be changed: ");
search=sc.nextLine();
String temp;
boolean found=false;
for(int i=0;i<5;i++)
{
if(arr[i].getName().equals(search))
{
System.out.print("Enter the new name for "+arr[i].getName()+" :");
temp=sc.nextLine();
arr[i].setName(temp);
found=true;
}
}
if(!found)
{
System.out.println("No such customer exists");
}
else
{
System.out.println("Name Changed!");
}
//4th part
System.out.print("Enter the full name of the customer whose number is to be changed:
");
search=sc.nextLine();
found=false;
for(int i=0;i<5;i++)
{
if(arr[i].getName().equals(search))
{
System.out.print("Enter the new number for "+arr[i].getName()+" :");
temp=sc.nextLine();
arr[i].setNumber(temp);
found=true;
}
}
if(!found)
{
System.out.println("No such customer exists ");
}else
{
System.out.println("Number Changed!");
}
}
}

Sample I/O: -
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.

Code: -
import java.util.*;
abstract class BankAccount
{
String name,dob,address;
int accno,bal;
public void input()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter name of customer: ");
name=sc.nextLine();
System.out.println("Enter date of birth of customer: ");
dob=sc.nextLine();
System.out.println("Enter address of customer: ");
address=sc.nextLine();
System.out.println("Enter account number of customer: ");
accno=sc.nextInt();
System.out.println("Enter account balance of customer: ");
bal=sc.nextInt();
}
public void display()
{
System.out.println(name+"\t"+dob+"\t"+address+"\t"+accno+"\t"+bal);
}
}

class SavingsAccount extends BankAccount


{
public int deposit(int depoamt)
{
bal=bal+depoamt;
return bal;
}
public int withdraw(int withamt)
{
bal=bal-withamt;
return bal;
}
}

public class Jumbo


{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int i=-1,j,n,ch,depoamt,withamt;
System.out.println("Enter number of customers: ");
n=sc.nextInt();
SavingsAccount[] obj= new SavingsAccount[n];
do
{
System.out.println ("\nMenu:\n1. Create A/C\n2. Withdrawal\n3. Deposit\n4. Delete
A/C\n5. Exit\nEnter your choice:");
ch= sc.nextInt();
switch(ch)
{
case 1:
if (i < n)
{
i++;
obj[i]= new SavingsAccount();
obj[i].input();
}
break;

case 2:
if (i == -1)
System.out.println ("\nNo accounts in database.");
else
{
System.out.print ("Enter withdrawal amount: ");
withamt= sc.nextInt();
obj[i].bal= obj[i].withdraw(withamt);
System.out.println ("\nName\tDOB\tAddress\tA/C No.\tBalance");
for (j= 0; j <= i; j++)
obj[j].display();
}
break;

case 3:
if (i == -1)
System.out.println ("\nNo accounts in database.");
else
{
System.out.print ("Enter deposition amount: ");
depoamt= sc.nextInt();
obj[i].bal= obj[i].deposit(depoamt);
System.out.println ("\nName\tDOB\tAddress\tA/C No.\tBalance");
for (j= 0; j <= i; j++)
obj[j].display();
}
break;

case 4:
if (i == -1)
System.out.println ("\nNo accounts in database");
else
{
System.out.println ("\nAccount with A/C Number \'"+obj[i].accno+"\' has been
deleted");
i--;
System.out.println ("\nName\tDOB\tAddress\tA/C No.\tBalance");
for (j= 0; j <= i; j++)
obj[j].display();
}
break;

case 5:
System.out.println ("\nFinished");
break;

default:
System.out.println ("\nInvalid choice");
}
}while (ch != 5);
}
}
Sample I/O: -
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.

Code: -
import java.util.*;
interface A
{
public void add();
public void sub();
public void multiply();
public void divide();
}

class FloatValues implements A


{
public float a,b;
public void add()
{
System.out.println("Sum is: "+(a+b));
}
public void sub()
{
System.out.println("Difference is: "+(a-b));
}
public void multiply()
{
System.out.println("Product is: "+(a*b));
}
public void divide()
{
System.out.println("Quotient is: "+(a/b));
}
}

class IntegerValues implements A


{
public int a,b;

public void add()


{
System.out.println("Sum is: "+(a+b));
}
public void sub()
{
System.out.println("Difference is: "+(a-b));
}
public void multiply()
{
System.out.println("Product is: "+(a*b));
}
public void divide()
{
System.out.println("Quotient is: "+(a/b));
}
}

public class Jumbo


{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
FloatValues f = new FloatValues();
System.out.println("Enter first float number: ");
f.a=sc.nextFloat();
System.out.println("Enter second float number: ");
f.b=sc.nextFloat();
f.add();
f.sub();
f.multiply();
f.divide();
System.out.println();
IntegerValues i = new IntegerValues();
System.out.println("Enter first integer number: ");
i.a=sc.nextInt();
System.out.println("Enter second integer number: ");
i.b=sc.nextInt();
i.add();
i.sub();
i.multiply();
i.divide();
}
}

Sample I/O: -
21) Write the following two methods under an interface Number: -
// Return the reversal of an integer, i.e. reverse(456) returns 654
public static int reverse(int number)
// Return true if number is palindrome
public static boolean isPalindrome(int number)
Use the reverse method to implement isPalindrome. A number is a
palindrome if its reversal is the same as itself. Write a test program to
implement the interface Number and prompts the user to enter an integer
and reports whether the integer is a palindrome.

Code: -
import java.util.*;
interface Number
{
public abstract int reverse(int number);
public abstract boolean isPalindrome(int number);
}

class revpal implements Number


{
public int reverse(int number)
{
int rev=0;
while(number!=0)
{
int remainder=number%10;
rev=rev*10+remainder;
number=number/10;
}
return rev;
}
public boolean isPalindrome(int number)
{
if(reverse(number)==number)
return true;
else
return false;
}
}

public class Jumbo


{
public static void main (String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
int number=sc.nextInt();
revpal r = new revpal();
if(r.isPalindrome(number))
System.out.println(number+" is a Palindrome!");
else
System.out.println(number+" is not a Palindrome!");
}
}

Sample I/O: -
22) Write a method to implement the binary search. Use a package that
has the class sort with a method void bubble_sort(double[] array) to
perform a bubble sort
public void search(double[] array)
Write a test program that prompts the user to enter n numbers, and a
search element. Invoke this method to return the position of the search
element.

Code: -
package mypack;
public class sort
{
public void bubble_sort(double[] array)
{
int n=array.length;
double temp=0;
for(int i=0;i<n;i++)
{
for(int j=i+1; j<n; j++)
{
if(array[i] > array[j])
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
}
}

NOW CREATE A NEW CLASS AND PROCEED AS FOLLOWS: -

import java.util.*;
public class binarysearch
{
public static void main(String args[])
{
int n,i,low,high,mid=0,flag=0,temp;
double key;
System.out.println("Enter the number of terms: ");
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
double array[] = new double[n];

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


for(i=0;i<array.length;i++)
{
array[i]=sc.nextDouble();
}

mypack.sort obj=new mypack.sort();


obj.bubble_sort(array);

System.out.println("Sorted Array is:");


for (i = 0; i < n; i++)
{
System.out.print(array[i]+" ");
}

System.out.println("\nEnter the number you wanna search for: ");


key=sc.nextDouble();
low=0;
high=n-1;

while(low<=high)
{
mid=(low+high)/2;
if(array[mid]==key)
{
flag=1;
break;
}
else if(array[mid]<key)
{
low=mid+1;
}
else
high=mid-1;
}
if(flag==0)
System.out.println("Element not found!");
else
System.out.println("Element is found at position "+(mid+1)+" in the sorted array");
}
}

Sample I/O: -
23) Write a program that has a class Factor with a method boolean
isFactor(int n, int m) that checks if n is a factor of m. Write another
class Divisibleby2 that derives Factor class. Override the isFactor(n,m)
method to find it is divisible by 2 or not. Write another class
Divisibleby3 that derives Factor class. Override the isFactor(n,m)
method to find it is divisible by 3 or not. Write a test method that
creates object for 2 classes. Get a number n from the user and check
whether it is divisible by 6.

Code: -
import java.util.*;
class Factor
{
boolean isFactor(int n, int m)
{
if(m%n==0)
return true;
else
return false;
}
}

class Divisibleby2 extends Factor


{
boolean isFactor(int n, int m)
{
if(m%n==0)
return true;
else
return false;
}
}

class Divisibleby3 extends Factor


{
boolean isFactor(int n, int m)
{
if(m%n==0)
return true;
else
return false;
}
}

public class Test


{
public static void main (String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number to check divisibility by 6: ");
int num=sc.nextInt();

Divisibleby2 d2= new Divisibleby2();


Divisibleby3 d3= new Divisibleby3();
if(d2.isFactor(2,num) && d3.isFactor(3,num))
System.out.println(num+" is divisible by 6!");
else
System.out.println(num+" is not divisible by 6!");
}
}

Sample I/O: -

You might also like