Download Java Practical Programs(Unit-1,2,3,4)

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
1
B.Sc (Computer Science)
Object Oriented Programming with Java and Data Structures
Lab Programs
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 Prog1
{
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the value of n for Harmonic Series");
int n=Integer.parseInt(br.readLine());
double sum=0.0;
for(int i=1;i<=n;i++)
sum=sum+1.0/i;
System.out.println("Total of Harmonic Series upto" +n+ "=" + sum);
}
}
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.
a)
import java.io.*;
class Prog2a
{
public static void main(String[] args) throws IOException
{
System.out.println("Enter number of strings:");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(br.readLine());
System.out.println("Enter " + n + " String:");
String name[]=new String[n];
for(int i=0;i<n;i++)
name[i]=br.readLine();
System.out.println("----------------------------");
String temp=null;
for(int i=0;i<name.length;i++)
{
for(int j=i+1;j<name.length;j++)
{
if(name[j].compareTo(name[i])<0)
{
Prasanth Kumar K
2
}
}
temp=name[i];
name[i]=name[j];
name[j]=temp;
}
System.out.println("Sorted Strings:");
System.out.println("----------------------------");
for(int i=0;i<name.length;i++)
{
System.out.println(name[i]);
}
}
}
b)
import java.io.*;
class Prog2b
{
public static void main(String[] args) throws IOException
{
System.out.println("Enter the Main String:");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String m=br.readLine();
System.out.println("Enter the Sub String:");
String s=br.readLine();
int index=m.indexOf(s);
if (index != -1)
System.out.println("It is a sub string");
else
System.out.println("No. It is not a sub string");
}
}
c)
import java.io.*;
class Prog2c
{
public static void main(String[] args) throws IOException
{
System.out.println("Enter number of strings:");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(br.readLine());
System.out.println("Enter " + n + " String:");
String name[]=new String[n];
for(int i=0;i<n;i++)
name[i]=br.readLine();
System.out.println("----------------------------");
for(int i=0;i<n;i++)
name[i]=name[i].toUpperCase();
System.out.println("Strings in Uppercase");
Prasanth Kumar K
3
System.out.println("----------------------------");
for(int i=0;i<name.length;i++)
{
System.out.println(name[i]);
}
}
}
3.
Write a program to simulate on-line shopping.
import java.io.*;
class OnlineShopping
{
public static void main(String args[]) throws Exception
{
int i=0,n,borrow,sum=0;
String con="";
int a[]=new int[10];
String name[]=new String[10];
String s[]={"C Programming","Java","DBMS","Web Technologies"};
int price[]={200,250,300,350};
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
do
{
System.out.println("Select Books from the list:\n");
System.out.println(" 1.C Programming-Rs.200");
System.out.println(" 2.Java-Rs.250");
System.out.println(" 3.DBMS-Rs.300");
System.out.println(" 4.Web Technologies-Rs.350");
System.out.println("\nSelect the book number:");
n=Integer.parseInt(br.readLine());
n--;
if(n<0 || n>3)
{
System.out.println("Invalid");
break;
}
a[i]=n;
System.out.println("Enter your name:");
name[i]=br.readLine();
i++;
System.out.println("Continue?(y,n):");
con=br.readLine();
}while(con.equals("y"));
borrow=i;
if(borrow>0)
{
System.out.println("****************************************");
System.out.println("\nName \t Book Purchased");
System.out.println("****************************************");
for(i=0;i<=n;i++)
{
Prasanth Kumar K
4
if(name[i]!=null)
{
if(a[i]==0)
sum=sum+200;
else if(a[i]==1)
sum=sum+250;
else if(a[i]==2)
sum=sum+300;
else if(a[i]==3)
sum=sum+350;
System.out.println(name[i]+"\t"+s[a[i]]);
}
}
System.out.println("Total Price=" + sum);
System.out.println("****************************************");
}
}
}
4. Write a program to identify duplicate value in a vector.
import java.io.*;
import java.util.Vector;
class Prog4
{
public static void main(String[] args) throws IOException
{
Vector v=new Vector();
System.out.println("Enter the number of values to insert into Vector");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(br.readLine());
System.out.println("Enter " + n + " values:");
for(int i=0;i<n;i++)
v.addElement(br.readLine());
System.out.println("-------Duplicate values are---------------");
for(int i=0;i<n;i++)
for(int j=i+1;j<n;j++)
if(v.elementAt(j).equals(v.elementAt(i)))
System.out.println(v.elementAt(j));
}
}
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.
import java.io.*;
class Even extends Thread
{
int x,y;
public Even(int a,int b)
{
x=a;
y=b;
}
public void run()
Prasanth Kumar K
5
{
for(int i=x; i<=y; i++)
{
if(i%2==0)
{
System.out.println("Even Number " + i);
}
}
}
}
class Odd extends Thread
{
int x,y;
public Odd(int a,int b)
{
x=a;
y=b;
}
public void run()
{
for(int j=x; j<=y; j++)
{
if(j%2!=0)
{
System.out.println("Odd number " + j);
}
}
}
}
class Prog5
{
public static void main(String[] args) throws IOException
{
System.out.println("Enter Starting value");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int r1=Integer.parseInt(br.readLine());
System.out.println("Enter Ending value");
int r2=Integer.parseInt(br.readLine());
Even e=new Even(r1,r2);
Odd o=new Odd(r1,r2);
e.start();
o.start();
}
}
6. Define an exception called “MarksOutOfBound” Exception that is
thrown if the entered marks are greater than 100.
import java.io.*;
class MarksOutOfBound extends Exception
{
MarksOutOfBound(String s)
{
super(s);
}
}
Prasanth Kumar K
6
class Prog6
{
public static void main(String[] args) throws IOException
{
try
{
System.out.println("Enter student name:");
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
String name=br.readLine();
System.out.println("Enter the marks in Java:");
int marks=Integer.parseInt(br.readLine());
if (marks>100)
{
throw new MarksOutOfBound("Marks should not be greater than
100.");
}
System.out.println("Entered marks: " + marks+ " is valid");
}
catch (MarksOutOfBound mb)
{
System.out.println(mb.getMessage());
}
}
}
7. Write a program to shuffle the list elements using all possible
permutations.
import java.io.*;
import java.util.*;
class Prog7
{
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader
(System.in));
System.out.print("How many elements you want to add to the list: ");
int n = Integer.parseInt(br.readLine());
System.out.println("Enter " + n + " numbers");
List Y = new ArrayList(n);
for(int i = 0; i < n; i++){
Y.add(br.readLine());
}
System.out.println("List:"+ Y);
int fact=1;
for(int j=1;j<=n;j++)
fact=fact*j;
int count=0;
for(int i = 0; i < fact; i++)
{
Collections.shuffle(Y);
System.out.println("List:"+Y);
Prasanth Kumar K
7
count++;
}
System.out.println("The number of possible permutations=" + count);
}
}
8. Create a package called “Arithmetic” that contains methods to deal
with all arithmetic operations. Also, write a program to use the
package.
package Arithmetic;
public class Prog8
{
public int add(int a,int b)
{
return a+b;
}
public int sub(int a,int b)
{
return a-b;
}
public int mult(int a,int b)
{
return a*b;
}
public double div(int a,int b)
{
return a/b;
}
}
import Arithmetic.Prog8;
import java.io.*;
public class Prog8a
{
public static void main(String[] args) throws IOException
{
System.out.println("Enter the values of A and B:");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int a=Integer.parseInt(br.readLine());
int b=Integer.parseInt(br.readLine());
Prog8 p=new Prog8();
System.out.println("Addition=" + p.add(a,b));
System.out.println("Subtraction=" + p.sub(a,b));
System.out.println("Multiplication=" + p.mult(a,b));
System.out.println("nDivision=" + p.div(a,b));
}
}
Prasanth Kumar K
8
9. Write an Applet program to design a simple calculator.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Calc extends Applet implements ActionListener
{
String cmd[]={"+","-","*","/","=","C"};
int pv=0;
String op="";
Button b[]=new Button[16];
TextField t1=new TextField(10);
public void init()
{
setLayout(new BorderLayout());
add(t1,"North");
t1.setText("0");
Panel p=new Panel();
p.setLayout(new GridLayout(4,4));
for(int i=0;i<16;i++)
{
if(i<10)
b[i]=new Button(String.valueOf(i));
else
b[i]=new Button(cmd[i%10]);
b[i].setFont(new Font("Arial",Font.BOLD,25));
p.add(b[i]);
add(p,"Center");
b[i].addActionListener(this);
}
}
public void actionPerformed(ActionEvent ae)
{
int res=0;
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));
}
Prasanth Kumar K
9
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));
}
}
}
10. Write a program to read a text and count all the occurrences of a
given word. Also, display their position.
import java.io.*;
import java.lang.String;
public class Prog10
{
public static void main(String args[]) throws IOException
{
System.out.println("Enter the Text:");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String m=br.readLine();
System.out.println("Enter the word to search:");
String s=br.readLine();
int index = m.indexOf(s);
int len = s.length();
int count = 0;
if (len > 0) {
while (index != -1) {
count++;
System.out.println("Found at position:" + index);
index = m.indexOf(s, index+len);
}
}
if(count!=0)
System.out.println("The number of occurrences of the given word is: " + count);
else
System.out.println(“Word does not exist”);
}
}
11. Write an applet illustrating sequence of events in an applet.
import java.awt.*;
import java.applet.Applet;
public class Prog11 extends Applet {
String msg;
public void init()
{
setBackground(Color.cyan);
setForeground(Color.blue);
Prasanth Kumar K
10
}
msg="
Init()";
public void start()
{
msg= msg + " Start()";
}
public void paint(Graphics g) {
msg= msg + " Paint()";
g.drawString(msg, 100,100);
showStatus("This is displyed in status window");
}
public void destroy()
{
msg= msg + "
}
Destroyed()";
}
12.Illustrate the method overriding in Java
class A {
int i;
A(int a, int b) {
i = a+b;
}
void add() {
System.out.println("Sum of a and b is: " + i);
}
}
class B extends A {
int j;
B(int a, int b, int c) {
super(a, b);
j = a+b+c;
}
void add() {
super.add();
System.out.println("Sum of a, b and c is: " + j);
}
}
class Prog12
{
public static void main(String args[]) {
B b = new B(10, 20, 30);
b.add();
}
}
Prasanth Kumar K
11
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 Prog13
{
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("How many elements you want to add to the list: ");
int n = Integer.parseInt(br.readLine());
System.out.println("Enter " + n + " elements");
List Y = new ArrayList(n);
for(int i = 0; i < n; i++){
Y.add(br.readLine());
}
System.out.println("List:"+ Y);
Collections.reverse(Y);
System.out.println("Reverse List:"+ Y);
List revlist= new ArrayList(n);
for(int i=0;i<n;i++)
revlist.add(Y.get(i));
System.out.println("List 2:"+ revlist);
}
14.Write an interactive program to accept name of a person and
validate it. If the name contains any numberic value throw an
exception “InvalidName”
import java.io.*;
class invname extends Exception
{
invname(String s)
{
super(s);
}
}
class Prog14
{
public static void main(String[] args) throws IOException
{
try
{
System.out.println("Enter student name:");
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
String name=br.readLine();
for(int i=0;i<name.length();i++)
{
if (Character.isDigit(name.charAt(i)))
Prasanth Kumar K
12
{
throw new invname("String contains numeric value.");
}
}
System.out.println("Entered Stirng : " + name + " contains only
text");
}
catch (invname in)
{
System.out.println(in.getMessage());
}
}
}
15. Write an applet program to insert the text at the specified position.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class Prog15 extends Applet implements ActionListener
{
TextArea ta=new TextArea("",2,20);
TextField t1=new TextField(10);
TextField t2=new TextField(10);
Button b1=new Button("Insert");
public void init()
{
add(t1);
add(t2);
add(b1);
add(ta);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
ta.insert(t1.getText(),1);
ta.insert(t2.getText(),6);
}
}
16.Prompt for the cost price and selling price of an article and
display the profit (or) loss percentage.
import java.io.*;
class Prog16
{
public static void main(String[] args) throws IOException
{
System.out.println("Enter the cost price:");
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
Prasanth Kumar K
13
double cost=Double.parseDouble(br.readLine());
System.out.println("Cost Price:" + cost);
System.out.println("Enter the Selling price:");
double sell=Double.parseDouble(br.readLine());
System.out.println("Selling Price:" + sell);
if(cost>sell)
{
System.out.println("Loss=" + (cost-sell));
System.out.println("Loss Percentage=" + ((costsell)/cost)*100);
}
else
{
cost)/cost)*100);
System.out.println("Profit=" + (sell-cost));
System.out.println("Profit Percentage=" + ((sell-
}
}
}
17.Create an Anonymous array in Java
public class AnonymousArrayExample
{
public static void main(String args[])
{
System.out.println(“Length of array is “ + findLength(new int[]{1,2,3}));
}
public static int findLength(int[] array)
{
for(int i=0;i<array.length;i++)
System.out.println(array[i]);
}
}
return array.length;
18. Create a font animation application that change the colors of text as and
when prompted.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Prog18 extends Applet implements ActionListener
{
Button b1=new Button("Change Color");
int r=0,g=0,b=0;
public void init()
{
add(b1);
Prasanth Kumar K
14
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)
{
setBackground(new Color(125,34,67));
gr.setColor(new Color(r,g,b));
gr.drawString("BSc Students are very Good",10,100);
}
}
19. Write an interactive program to wish the user at different hours of
the day.
import java.util.*;
import java.io.*;
class Prog19
{
public static void main(String[] args) throws IOException
{
System.out.println("Enter your name:");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String name=br.readLine();
Calendar t=Calendar.getInstance();
t.setTimeZone(TimeZone.getTimeZone("IST"));
int hourtime=t.get(Calendar.HOUR_OF_DAY);
System.out.println("Time=" + hourtime);
if(hourtime<12)
System.out.println("Good Morning, " + name);
else if(hourtime>=12 && hourtime<16)
System.out.println("Good Afternoon " + name);
else if(hourtime>=16 && hourtime<21)
System.out.println("Good Evening " + name);
else
System.out.println("Good Night " + name);
}
}
20. Simulate the library information system i.e. maintain the list of books
and borrower's details.
import java.io.*;
class Library
Prasanth Kumar K
15
{
public static void main(String args[]) throws Exception
{
int i=0,n,borrow;
String con="";
int a[]=new int[10];
String name[]=new String[10];
String s[]={"C Programming","Java","DBMS","Web Technologies"};
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
do
{
System.out.println("Select Books from the list:\n");
System.out.println(" 1.C Programming");
System.out.println(" 2.Java");
System.out.println(" 3.DBMS");
System.out.println(" 4.Web Technologies");
System.out.println("\nSelect the book number:");
n=Integer.parseInt(br.readLine());
if(n<1 || n>4)
{
System.out.println("Invalid");
break;
}
a[i]=n;
System.out.println("Enter your name:");
name[i]=br.readLine();
i++;
System.out.println("Continue?(y,n):");
con=br.readLine();
}while(con.equals("y"));
borrow=i;
if(borrow>0)
{
System.out.println("****************************************");
System.out.println("\nName \t Book borrowed");
System.out.println("****************************************");
for(i=0;i<n;i++)
{
if(name[i]!=null)
System.out.println(name[i]+"\t"+s[a[i]]);
}
System.out.println("****************************************");
}
}
}
Prasanth Kumar K
Related documents