Java Lab Cycle (1)
Java Lab Cycle (1)
1. Write a java program to determine the sum of the following harmonic series for a
given value of ‘n’.
1+1/2+1/3+. . . +1/n
import java.io.*;
class ShowSum
{
public static void main(String args[]) throws Exception
{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
System.out.println("Enter n value:");
int n=Integer.parseInt(br.readLine());
float sum=1;
for(int i=1;i<=n; i++)
sum = sum+(float)1/i;
System.out.println ("Sum="+sum);
}
}
Output:
Enter n value: 5
Sum=3.2833333
2. Write a program to perform the following operations on strings through interactive input.
a) Sort given strings in alphabetical order.
b) Check whether one string is sub string of another string or not.
c) Convert the strings to uppercase.
import java.io.*;
class StringTest
{
public static void main(String args[]) throws Exception
{
int i, j, n, x;
String temp,s1,s2;
String s[]=new String[10];
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
do
{
System.out.println("\n 1.Sorting\n 2.Substring\n 3.Uppercase");
System.out.println("\n 1.Enter your choice:");
x=Integer.parseInt(br.readLine());
} while(x<1||x>3);
if(x==1||x==3)
{
System.out.println("How many Strings:");
n=Integer.parseInt(br.readLine());
System.out.println("Enter strings:\n");
for(i=0;i<n;i++)
s[i]=br.readLine();
}
if(x==1)
{
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
if(s[i].compareTo(s[j])>0)
{
temp=s[i];
s[i]=s[j];
s[j]=temp;
}
System.out.println("After Sorting:");
for(i=0;i<n;i++)
System.out.print(s[i]+"\t");
}
else if(x==2)
{
System.out.println("Enter main string:");
s1=br.readLine();
System.out.println("Enter sub string:");
s2=br.readLine();
if(s1.indexOf(s2)!=-1)
System.out.println(s2 +" is sub string of"+ s1);
else
System.out.println(s2 +" is not a sub string of "+ s1);
}
else
{
System.out.println("Strings in Uppercase");
for(i=0;i<n;i++)
System.out.print("\t"+s[i].toUpperCase());
}
}
}
Output:
1.Sorting
2.Substring
3.Uppercase
Enter your choice:1
How many Strings:3
Enter strings:
mango
apple
banana
After Sorting:
apple banana mango
System.out.println("Enter option:");
op=Integer.parseInt(br.readLine());
if(op==1)
{
System.out.println("==========================================");
System.out.println("\nItem\tQuantity");
System.out.println("==========================================");
for(i=0;i<m;i++)
{
if(a[i]==1)
sum=sum+n[i]*200;
else if(a[i]==2)
sum=sum+n[i]*100;
else if(a[i]==3)
sum=sum+n[i]*150;
else if(a[i]==4)
sum=sum+n[i]*300;
System.out.println("\n"+s[a[i]]+"\t"+n[i]);
}
System.out.println("==========================================");
System.out.println("\nTotal Bill:"+sum);
System.out.println("==========================================");
}
}
}
Output:
Select Items from the list:
1.Self Confidence -book Rs.200
2.My Experiments with truth Rs.100
3.Java Apoorva book Rs.150
4.Java Complete Reference Rs.300
Select the Item number:1
Enter quantity: 2
Add more Items?(y,n):y
Select Items from the list:
1.Self Confidence -book Rs.200
2.My Experiments with truth Rs.100
3.Java Apoorva book Rs.150
4.Java Complete Reference Rs.300
Select the Item number:3
Enter quantity:2
Add more Items?(y,n):n
1. Check out
2. Cancel the order
Enter option:1
=============================================
Item Quantity
=============================================
My Experiments with truth(Rs. 200) 2
Java Apoorva book(Rs. 150) 2
=============================================
Total Bill:700
=============================================
Output:
How many Strings:5
Enter strings:
cat
rat
mat
cat
mat
Vector Elements:
[cat, rat, mat, cat, mat]
Duplicate Elements:
[cat, mat]
5. Create two threads such that one of the thread print even no’s and another prints odd no’s up
to a given range.
class MyThread extends Thread
{
int initval, finalval;
MyThread(int iv,int fv)
{
initval=iv;
finalval=fv;
start();
}
public void run()
{
for(int i=initval;i<=finalval;i+=2)
{
System.out.println(i);
try
{
Thread.sleep(1000);
}
catch(Exception e){}
}
}
}
class ThreadTest
{
public static void main(String args[])
{
MyThread t1=new MyThread(1,6);
MyThread t2=new MyThread(2,6);
}
}
Output:
1
2
3
4
5
6
import java.io.*;
class MarksOutOfBounds extends Exception
{
public void showError()
{
System.out.println("Invalid Marks");
}
}
class ErrorTest
{
public static void main(String args[]) throws Exception
{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
int m=0;
try
{
System.out.println("Enter Marks:");
m=Integer.parseInt(br.readLine());
if(m>100)
throw new MarksOutOfBounds();
System.out.println("Your Marks:"+m);
}
catch(MarksOutOfBounds e)
{
e.showError();
}
}
}
Output: Enter Marks:120
Invalid Marks
7. Write a JAVA program to shuffle the list elements using all the possible permutations.
class ShuffleString
{
public static void main(String args[])
{
char s[]={'a','b','c'};
int i,j,k,n=s.length;
/* number of for loops should match with number of character i.e here ‘3’ */
for(i=0;i<n;i++)
for(j=0;j<n;j++)
for(k=0;k<n;k++)
if(i!=j && j!=k && i!=k)
System.out.println(s[i]+","+s[j]+","+s[k]);
}
}
/* Output: */
abc
acb
bac
bca
cab
cba
8. Create a package called “Arithmetic” that contains methods to deal with all arithmetic
operations. Also, write a program to use the package.
Note: First create a directory by name “Arithmetic” and move to that directory, create the following file
and compile the file in the same directory.
package arithmetic;
public class MyMath
{
public int add(int x,int y)
{
return x+y;
}
public int sub(int x,int y)
{
return x-y;
}
public int mul(int x,int y)
{
return x*y;
}
public double div(int x,int y)
{
return (double)x/y;
}
public int mod(int x,int y)
{
return x%y;
}
}
Note: Move to parent directory, write the following file and execute it.
import arithmetic.*;
class Test
{
public static void main(String args[])
{
MyMath m=new MyMath();
System.out.println(m.add(8,5));
System.out.println(m.sub(8,5));
System.out.println(m.mul(8,5));
System.out.println(m.div(8,5));
System.out.println(m.mod(8,5));
}
}
Output:
13
3
40
1.6
3
String cap=ae.getActionCommand();
int cv=Integer.parseInt(t1.getText());
if(cap.equals("C"))
{
t1.setText("0");
pv=0;
cv=0;
res=0;
op="";
}
else if(cap.equals("="))
{
res=0;
if(op=="+")
res=pv+cv;
else if(op=="-")
res=pv-cv;
else if(op=="*")
res=pv*cv;
else if(op=="/")
res=pv/cv;
t1.setText(String.valueOf(res));
}
else if(cap.equals("+")||cap.equals("-")||
cap.equals("*")||cap.equals("/"))
{
pv=cv;
op=cap;
t1.setText("0");
}
else
{
int v=cv*10+Integer.parseInt(cap);
t1.setText(String.valueOf(v));
}
}
}
Output:
10.Write a program to read a text and count all the occurrences of a given word. Also, display their
positions.
import java.io.*;
class TextSearch
{
public static void main(String args[]) throws Exception
{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
int i=0,count=0;
String text="",s="";
System.out.println("Enter Text:(press ENTER twice to stop)\n");
s=br.readLine();
while(s.length()!=0)
{
text+=s;
s=br.readLine();
}
System.out.println("Enter search word:");
s=br.readLine();
while(true)
{
i=text.indexOf(s,i);
if(i==-1) break;
System.out.println("Word found at position:"+i);
count++;
i+=s.length();
}
System.out.println("Number of occurrences of given word:"+count);
}
}
Output:
Enter Text:(press ENTER twice to stop)
Hello hi , hi again
hi nice to see you
Enter search word:hi
Word found at position:6
Word found at position:11
Word found at position:19
Number of occurrences of given word:3
13. Write a program to fill elements into a list. Also, copy them in reverse order into another list.
import java.io.*;
import java.util.*;
class ListTest
{
public static void main(String as[]) throws Exception
{
int i,j,n;
ArrayList l1=new ArrayList();
ArrayList l2=new ArrayList();
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
System.out.println("How many Strings:");
n=Integer.parseInt(br.readLine());
System.out.println("Enter strings:\n");
for(i=0;i<n;i++)
l1.add(br.readLine());
System.out.println("List Elements:\n"+l1);
for(i=n-1;i>=0;i--)
l2.add(l1.get(i));
System.out.println("List Elements Reversed:\n"+l2);
}
}
Output:
How many Strings:4
Enter strings:
cat
rat
bat
List Elements:
[cat, rat, bat]
List Elements Reversed:
[bat, rat, cat]
14. Write an interactive program to accept name of a person and validate it.
If the name contains any numeric value throw an exception “InvalidName”.
import java.io.*;
class InvalidName extends Exception
{
public void showError()
{
System.out.println("Error:Name contains digits");
}
}
class NameTest
{
public static void main(String args[]) throws Exception
{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
String name;
int i;
try
{
System.out.println("Enter Name:");
name=br.readLine();
for(i=0;i<name.length();i++)
{
char ch=name.charAt(i);
if(Character.isDigit(ch))
throw new InvalidName();
}
System.out.println("Your Name:"+name);
}
catch(InvalidName e)
{
e.showError();
}
}
}
/* Output: */
Enter Name:Ravi12
Error:Name contains digits
15. Write an applet program to insert the text at the specified position.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class TextInsert extends Applet implements ActionListener
{
TextArea ta=new TextArea("Welcome to text insert \n application"+ "place the cursor to insert text and
enter \n"+ "the text to insert in text box then click \n"+ "insert button",10,20);
TextField t1=new TextField(10);
TextField t2=new TextField(10);
Button b1=new Button("Insert");
public void init()
{
add(ta);
add(new Label("position"));
add(t1);
add(new Label("string"));
add(t2);
add(b1);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
ta.insertText(t2.getText(),Integer.parseInt(t1.getText()));
}
}
output:
16. Prompt for the cost price and selling price of an article and display the profit
(or) loss percentage.
import java.io.*;
class Sales
{
public static void main(String args[]) throws Exception
{
double sp,cp,perc;
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
System.out.println("Enter Cost price of an article:");
cp=Double.parseDouble(br.readLine());
System.out.println("Enter Cost price of an article:");
sp=Double.parseDouble(br.readLine());
perc=((sp-cp)/cp)*100;
if(perc<0)
System.out.println("Loss percentage="+perc+"%");
else if(perc>0)
System.out.println("Gian percentage="+perc+"%");
else
System.out.println("No Profitm, No Loss");
}
}
Output:
Enter Cost price of an article:200
Enter Cost price of an article:250
Gian percentage=25.0%
18. Create a font animation application that changes the colors of text as and when prompted.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class FontAnim extends Applet implements ActionListener
{
Button b1=new Button("Change Color");
int r=0,g=0,b=0;
public void init()
{
add(b1);
b1.addActionListener(this);
setFont(new Font("Arial",Font.BOLD,30));
}
public void actionPerformed(ActionEvent ae)
{
r=(int)(Math.random()*255);
g=(int)(Math.random()*255);
b=(int)(Math.random()*255);
repaint();
}
public void paint(Graphics gr)
{
gr.setColor(new Color(r,g,b));
gr.drawString("APOORVA",20,200);
}
}
output:
19. Write an interactive program to wish the user at different hours of the day.
import java.util.*;
class TimeTest
{
public static void main(String args[]) throws Exception
{
Date d=new Date();
int h=d.getHours();
if(h<12)
System.out.println("Good Morning");
else if(h<16)
System.out.println("Good Afternoon");
else if(h<20)
System.out.println("Good Evening");
else
System.out.println("Time to sleep, Good night");
}
}
Output:
Good Afternoon.
20. Simulate the library information system i.e. maintain the list of books and borrower’s details.
import java.io.*;
class Library
{
public static void main(String args[]) throws Exception
{
int i=0,x,m;
String con="";
int a[]=new int[10];
String name[]=new String[10];
String s[]={"Self Confidence ","My Experiments with truth",
"Java Apoorva book","Java Complete Reference"};
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
do
{
System.out.println("Select Books from the list:\n");
System.out.println(" 1.Self Confidence -book");
System.out.println(" 2.My Experiments with truth");
System.out.println(" 3.Java Apoorva book");
System.out.println(" 4.Java Complete Reference");
System.out.println("\nSelect the book number:");
x=Integer.parseInt(br.readLine());
if(x<1 || x>4) continue;
a[i]=x;
System.out.println("Enter your name:");
name[i]=br.readLine();
i++;
System.out.println("Continue?(y,n):");
con=br.readLine();
}while(con.equals("y"));
m=i; // number of borrowers
System.out.println("==========================================");