Professional Documents
Culture Documents
1) Write a java program that prints all real solutions to the quadratic equation
ax2+bx+c=0. Read in a, b, c and use the quadratic formula. If the discriminant b2-4ac is
negative, display a message stating that there are no real solutions.
Procedure
Example:
Q) The Fibonacci sequence is defined by the following rule. The first two values in the
sequence are 1 and 1. Every subsequent value is the sum of the two values preceding it.
Write a java program that uses both recursive and non-recursive functions to print the nth
value in the Fibonacci sequence.
Procedure:
them to be accessed as entire lines of text (as delineated by new line characters). This
entire chain of
objects can be constructed in a Java program by the single statement
that declares the variable keyboard to be an object of type BufferedReader, which gets its
input
from an object of type InputStreamReader, which gets its input from the object
System.in.
The classes BufferedReader and InputStreamReader are defined in the Java
Application
Programming Interface, or Java API and must be added (or imported) to any program
that uses
them. This is done by including the statement
import java.io.*;
Procedure:
→ Read n value from keyboard (By using BufferedReader class) in the main ().
→ Pass that value to the two functions called rec() and nonrec() defined in another
class say test
→ In rec() we will give a condition n==0 or n==1 then return 1.
Otherwise return rec(n-1)+rec(n-2)
f= f1+f2
f1=f2
f2=f
1, 1, 2, 3, 5, 8
1, 1, 2, 3, 5, 8
2. The Fibonacci sequence is defined by the following rule. The first two values in the
sequence are 1 and 1. Every subsequent value is the sum of the two values preceding it.
Write a java program that uses both recursive and non-recursive functions to print the nth
value in the Fibonacci sequence.
import java.io.*;
class Test {
int rec(int n)
if(n==0||n==1)
return 1;
else
return(rec(n-1)+rec(n-2));
}
void nonrec(int n)
{
int j,f1=1,f2=1,f;
System.out.println();
System.out.println("non recursive function output is ");
System.out.println(f1+","+f2+",");
for(j=3;j<=n;j++)
{
f=f1+f2;
f1=f2;
f2=f;
System.out.println(f+",");
}
}
}
class Fibonacci
{
public static void main(String args[])throws Exception {
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
int rec,i,n;
System.out.println("Enter a value:");
n=Integer.parseInt(br.readLine());
Test t=new Test();
System.out.println("Recursive output is ..");
for(i=0;i<n;i++)
{
rec=t.rec(i);
System.out.print(rec+",");
}
t.nonrec(n);
}
}
***********************************************************************
*
WEEK 2
3) Write a java program that prompts the user for an integer and then print out all prime
numbers up to that Integer.
Procedure
Example
Take n=5,
i=1, j=1 and let p=0
i=2, j=1
/* 3.Prime Number */
import java.io.*;
class Prime {
public static void main(String args[])throws Exception {
int count,n,i;
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
for(n=1;n<=100;n++)
{
count=0;
for(i=1;i<=n;i++)
{
if(n%i==0)
count++;
}
if(count==2)
System.out.println(n+"\t");
}
}//main
}//class
Output:
2 3 5 7 11 13 17 19
Procedure:
For matrix multiplication, we have to multiply ‘a’ matrix row values to ‘b’ matrix
column values
Example, a[0][0]*b[0][0] + a[0][1]*b[1][0]
……………………………
c[i][j] = a[i][k]*[k][j]
Here k is same for matrix ‘a’ column size and matrix ‘b’ row size.
Arrays:
Example
2
3
Simply
7 10
15 22
/*.Matrix Multiplication*/
import java.io.*;
class Matrix
{
public static void main(String args[])throws Exception
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
int i,j,k,m,n,p,q;
System.out.println("Enter the size forA:m*n");
m=Integer.parseInt(br.readLine());
n=Integer.parseInt(br.readLine());
System.out.println("enter the size for b:p*q");
p=Integer.parseInt(br.readLine());
q=Integer.parseInt(br.readLine());
int a[][]=new int[m][n];
int b[][]=new int[p][q];
int c[][]=new int[m][q];
if(n==p)
{
System.out.println("enter the values of matrix a:m*n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
a[i][j]=Integer.parseInt(br.readLine());
System.out.println("enter the values of matrix b:p*q");
for(i=0;i<p;i++)
for(j=0;j<q;j++)
b[i][j]=Integer.parseInt(br.readLine());
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
c[i][j]=0;
for(k=0;k<n;k++)
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
System.out.println("The resultant matrix c is:"+"\t");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
System.out.println(c[i][j]+" ");
}
}
}
else
System.out.println("Matrix multiplication is not possible...");
}
}
5. Write a Java Program that reads a line of integers, and then displays each integer, and
The processing of data often consists of parsing a formatted input data (or string). The string tokenizer class
allows an application to break a string into tokens. The discrete parts of a string are called tokens. The
StringTokenizer methods do not distinguish among identifiers, numbers, and quoted strings, nor do
they recognize and skip comments. The set of delimiters (the characters that separate tokens) may be
specified either at creation time or on a per-token basis. StringTokenizer implements the
Enumeration interface. Therefore, given an input string, we can enumerate the individual tokens
contained in it using StringTokenizer. The default delimiters are whitespace characters: space, tab,
newline, and carriage return. Other than default delimiters, each character in the delimiters string is
considered a valid delimiter.
A StringTokenizer object internally maintains a current position within the string to be tokenized.
Some operations advance this current position past the characters processed. A token is returned by taking a
substring of the string that was used to create the StringTokenizer object. The following is one
example of the use of the tokenizer. The code:
StringTokenizer st = new StringTokenizer("this is a test");
while (st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
prints the following output: (Here, space is the default delimiter)
this
is
a
test
StringTokenizer is a legacy class that is retained for compatibility reasons although its use is
discouraged in new code.
StringTokenizer constructors are:
StringTokenizer(String str)
StringTokenizer(String str, String delimiters)
Program
import java.util.StringTokenizer;
import java.io.*;
class StringTokenizerDemo
{
public static void main(String[] args) throws IOException
{
BufferedReader kb = new
BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a string of digits: ");
String str = kb.readLine();
StringTokenizer st = new StringTokenizer(str);
int a, sum = 0;
String s;
while (st.hasMoreTokens())
{
s = st.nextToken();
a = Integer.parseInt(s);
sum = sum + a;
System.out.println(a);
}
System.out.println("Sum of these integers = " + sum); }
}
This program prints the following output:
Enter a string of digits: 45 100 750 5
45
100
750
5
Sum of these integers = 900
***********************************************************************
*
WEEK 3
6.Write a java program that checks whether the given String is a Palindrome or not
Procedure
(Since, s1.length ( )-1 to 0, and length () is a method used for finding String
length)
use charAT( ) to take individual characters from a String and store the Received
Characters in another String(say, s2)
Example
s1 = MADAM
M ---------- s1.length( )-1
A -
D -
A -
M ---------- 0
Then s2 = MADAM
s1.equals(s2) condition true
Then print “ The given String is Palindrome ”.
7) Write a java program for sorting a given list of names in ascending order.
Procedure
arr[j].compareTo(arr[i]<0)
T=arr[i]
arr[i]=arr[j]
arr[j]=t
Output
ant
ass
bos
hai
how
class StrAscend
String a[]={"bos","how","hai","ant","ass"};
int s=a.length;
String t=NULL;
for(int i=0;i<s;i++)
for(int j=i+1;j<s;i++)
if(a[j].compareTo(a[i]<0))
t=a[i];
a[i]=a[j];
a[j]=t;
}
for(int i=0;i<s;i++)
System.out.println(a[i]);
NOT COMPLETED
***********************************************************************
*
WEEK 4
9. Write a java program that reads on file name from the user then displays information
about whether the file exists, whether the file is readable, whether the file is writable, the
type of the file and the length of the file in bytes.
10. Write a java program that reads a file and displays a file and displays the file on the
screen, with a line number before each line.
NOT COMPLETED
Software/Hardware Requirements:
H/W: Pentium IV, Intel Mother Board Processor, 40 GB HDD, 256 MB RAM
ALGORITHM:
3. compute count=0
printf counter,count++
Test Data:
line no:3{
line no:5{
line no:3{
line no:5{
line no:8while(token.hasMoreTokens())
line no:9s=s+Integer.parseInt(token.nextToken());
line no:10System.out.println(s);
line no:11}
line no:12}
line no:13 line no:14?
11. Write a java program that displays the number of characters, lines and words in a text
file.
ALGORITHM:
1) Start the program, import the packages.
3) compute count=0,word=0,line=1,space=0
line++
else
word++
else
char++
6) print word,line,char
7) Stop the program
else
word++
else
char++
******************************************************************************
WEEK 5
12. Write a java program that :
a)Implement Stack ADT b)converts infix expression into postfix form. c). Evaluate the
postfix expression .
******************************************************************************
WEEK 6
Procedure
Example
import java.awt.*;
import java.applet.*;
/*
<applet code="MyAppletTest" width=500 height=300>
</applet>
*/
14. Develop an applet that receives an Integer in one text field and computes its factorial
value and returns it in another text field, when the button named “compute” is clicked.
NOT COMPLETED
******************************************************************************
WEEK 7
15. Write a java program that works as a simple calculator. Use a grid layout to arrange
buttons for the digits and for the +-*% operations. And a text field to display the result.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="Calculator.class" width=200 height=200>
</applet>
*/
public class Calculator extends Applet
implements ActionListener
{
TextField t1;
Button[] b=new Button[20];
Panel p1,p2,p3,p4,p5;
String fn="",sn="",str="",s="";String oper="";
public void init()
{
p1=new Panel();
t1=new TextField(20);
setLayout(new BorderLayout());
p1.add(t1);
add(p1,"North");
p2=new Panel();
add(p2);
p2.setLayout(new BorderLayout(5,5));
p3=new Panel();
p2.add(p3);
p3.setLayout(new GridLayout(3,3,5,5));
for(int i=0;i<9;i++)
{
b[i]=new Button(i+1+" ");
p3.add(b[i]);
}
p4=new Panel();
p4.setLayout(new GridLayout(3,1,5,5));
p4.add(b[9]=new Button("C"));
p4.add(b[10]=new Button("/"));
p4.add(b[11]=new Button("*"));
p2.add(p4,"East");
p5=new Panel();
p5.setLayout(new GridLayout(1,4,5,5));
p5.add(b[12]=new Button("0"));
p5.add(b[13]=new Button("="));
p5.add(b[14]=new Button("+"));
p5.add(b[15]=new Button("-"));
p2.add(p5,"South");
for(int i=0;i<=15;i++)
{
b[i].addActionListener(this);
}
setBackground(Color.cyan);
setForeground(Color.black);
}
public void actionPerformed(ActionEvent ae)
{
str=ae.getActionCommand();
if(str.equals("+")||str.equals("-")||str.equals("*")||str.equals("/"))
{
oper=str;
fn=t1.getText();
s="";
}
else if(str.equals("="))
{
sn=t1.getText();
double x=Double.parseDouble(fn);
double y=Double.parseDouble(sn);
if(oper.equals("+"))
t1.setText(" "+(x+y));
if(oper.equals("-"))
t1.setText(" "+(x-y));
if(oper.equals("/"))
t1.setText(" "+(x/y));
if(oper.equals("*"))
t1.setText(" "+(x*y));
}
else if(str.equals("C"))
{
t1.setText("");
s="";
}
else
{
s=s+ae.getActionCommand().trim();
t1.setText(s);
}
showStatus("CALCULATOR");
}
}
******************************************************************************
WEEK 8
16. Write a java program for handling mouse and key events.
/*Demonstrate the Mouse Event Handlers.*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="MouseEvents" width=300 height=100>
</applet>
*/
public class MouseEvents extends Applet
implements MouseListener, MouseMotionListener {
String msg = "";
int mouseX = 0, mouseY = 0; // coordinates of mouse
public void init() {
addMouseListener(this);
addMouseMotionListener(this);
}
// Handle Mouse clicked.
public void mouseClicked(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse Clicked.";
repaint();
}
// Handle Mouse entered.
public void mouseEntered(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse Entered.";
repaint();
}
// Handle mouse exited.
public void mouseExited(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse exited.";
repaint();
}
// Handle button pressed.
public void mousePressed(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Down";
repaint();
}
// Handle Button released.
public void mouseReleased(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Up";
repaint();
}
// Handle Mouse Dragged.
public void mouseDragged(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
repaint();
}
// Handle mouse moved.
public void mouseMoved(MouseEvent me) {
// show status
showStatus("Moving mouse at " + me.getX() + ", " + me.getY());
}
// Display msg in applet window at current X,Y location.
public void paint(Graphics g) {
g.drawString(msg, mouseX, mouseY);
}
}
******************************************************************************
WEEK 9
17. Write a java program that creates three threads. First thread displays “Good Morning”
every one second, the second thread displays “Hello” every two seconds and third thread
displays “Welcome” every three seconds.
NOT COMPLETED
18. Write a java program that correctly implements producer consumer problem using
the concept of inter thread communication.
******************************************************************************
WEEK 10
19. Write a java program that creates user interface to perform integer divisions. The
user enters two numbers in a text fields, Num1 & Num2. The division of Num1 & Num2
is displayed in the result field when the divide button is clicked. If Num1 or Num2 were
not an Integer, the program would throw a NumberFormatException. If Num2 were zero,
the program would throw an ArithemeticExpception Display the exception in a message
dialogbox.
Procedure:
1. Create three Textfield objects and one Button
Ex; Label l1=new Label("enter num1");
Textfield T1 =new TextField(5);
Button b1=new Button("divide");
WEEK 11
20. Write a java program that simulates a traffic lights. The program lets the user select
one of three lights: red, yellow, or green. When a radio button is selected the light is
turned on, and only one light can be on at a time No light is on when the program starts.
Procedure:
1. Define a user define class which extends Applet class and
implements Item Listener interface.
Ex: public class TrafficDemo extends Applet implements
ItemListener
2. Create Checkbox group as follows
Ex: CheckboxGroup cbg;
3. Create three checkbox objects with same checkbox group.
Ex: Chechbox cb1=new Checkbox("red",cbg,false);
Chechbox cb2=new Checkbox("yellow",cbg,false);
Chechbox cb3=new Checkbox("greed”,cbg,false);
4. Override the itemStateChanged() method to know which radio
button was pressed and accordingly return which color to be set
to circle
5. Override the paint() method to create three circles one after the
other and set three different colors.
Example:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="TrafficDemo" height="300" width="300">
</applet>
*/
public class TrafficDemo extends Applet implements ItemListener
{
Checkbox cb1,cb2,cb3;
String str=" ";
CheckboxGroup cbg;
Color c;
public void init()
{
setBackground(Color.red);
cbg=new CheckboxGroup();
cb1=new Checkbox("red",cbg,false);
add(cb1);
cb1.addItemListener(this);
setBackground(Color.yellow);
cb2=new Checkbox("yellow",cbg,true);
add(cb2);
cb2.addItemListener(this);
setBackground(Color.green);
cb3=new Checkbox("green",cbg,true);
add(cb3);
cb3.addItemListener(this);
setBackground(Color.white);
}
public void itemStateChanged(ItemEvent ie)
{
str=cbg.getSelectedCheckbox().getLabel();
if(str.equalsIgnoreCase("red"))
c=new Color(255,0,0);
else if(str.equalsIgnoreCase("green"))
c=new Color(0,255,0);
else if(str.equals("yellow"))
c=new Color(0,0,255);
repaint();
public void paint(Graphics g)
{
g.drawString(str,30,100);
g.setColor(c);
g.drawOval(150,100,60,60);
g.drawOval(150,170,60,60);
g.drawOval(150,250,60,60);
if(str.equals("red"))
{
g.fillOval(150,100,60,60);
}
else if(str.equals("yellow"))
{
g.setColor(Color.yellow);
g.fillOval(150,170,60,60);
}
else if(str.equals("green"))
{
g.fillOval(150,250,60,60);
}
System.out.println(str);
}
}
21. Write a java program that allows the user to draw lines, rectangle and ovals.
NOT COMPLETED
******************************************************************************
WEEK 12
22.Write a java program to create an abstract class named shape that contains an empty
method named numberOfSides(). Provides three classes named Trapezoid, Triangle and
Hexagon such that each one of the classess extends the class shape. Each one of the
classes contains only the method numberOfSides() that shows the number of sides in the
given geometrical figures.
Procedure:
1.Define the class Shape with abstract method numberOfSides().
Ex: abstract void numberOdSides();
2. Define another class Triangle which extends Shape class and overrides
abstract method define in the Shape class.
3. Define third class Trepezoid which extends Shape class and overrides
abstract
method define in the Shape class.
4. Define fourth class Hexagon which extends Shape class and overrides
abstract
method define in the Shape class.
Example:
class Shape
{
Shape()
{
}
abstract void numberOdSides();
}
class Triangle extends Shape
{
void numberOdSides()
{
System.out.println("No of sides are three");
}
}
class Trapezoid extends Shape
{
void numberOdSides()
{
System.out.println("No of sides are four");
}
}
void numberOdSides()
{
System.out.println("No of sides are six");
}
}
class ShapeDemo
{
public static void main(String args[])
{
Shape ref;
Triangle t=new Triangle();
Hexagon h=new Hexagon();
Trapezoid tp=new Trapezoid();
ref=t;
ref.numberOfSides();
ref=h;
ref.numberOfSides();
ref=tp;
ref.numberOfSides();
}
}
23. Suppose that table named Table.txt is stored in a test file. The first line in the file is
the header, and the remaining lines correspond to rows in the table. The elements are
separated by commas, Write a java program to display the table using JTable component.
Procedure:
1. Read the file table.txt using File Reader.
Ex: BufferReader br=new BufferReader(new FileReader(table.txt))
2. Separate each attribute of the table using StringTokenizer.
Ex: StringTokenizer st1=new StringTokenizer(str,", ");
3. Store column heads in single dimensional array variable.
Ex: heading[i]=st1.nextToken();
4. Store data of the table in the two dimensional array variable.
Ex: data[i][j]=st2.nextToken()
5. Create a JTable object with two parameters data and col variables
Ex: JTable table=new JTable(data,heading)
PROGRAM:
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.*;
/*
<applet code="JTableDemo" width="300" height="300">
</applet>
*/
public class JTableDemo extends JApplet
{
public void init()
{
try
{
/* Creating an object of Buffer Reader class for reading the table.txt
file*/
BufferedReader br=new BufferedReader(new FileReader("table.txt"));
String heading[]=new String[3];
String str=br.readLine();
StringTokenizer st1=new StringTokenizer(str,", ");
int i=0;
while(st1.hasMoreTokens())
{
heading[i]=st1.nextToken();
i++;
}
String data[][]=new String[10][3];
i=1;
int j;
while((str=br.readLine())!=null)
{
j=0;
System.out.println(str);
StringTokenizer st2=new StringTokenizer(str,", ");
while(st2.hasMoreTokens())
{
data[i][j]=st2.nextToken();
j++;
}
i++;
}
JTable table=new JTable(data,heading);
JScrollPane jsp=new JScrollPane(table);
add(jsp);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
******************************************************************************