7/30/2019 Java 2003
1/103
10 PAINT 25.8.2010
AIM:To develop a simple paint like program that can draw basic graphical primitives in
different dimensions and colors
ALGORITHM:Step 1 : Import all packagesStep 2 : Declare all necessary variables
Step 3: Create drawing class that calls frame class
Step4 : Create frame and include all icons of line ,oval,rectangle etcStep 5: Draw all ahapes using tools created
Step 6: Close the application
PROGRAM:
7/30/2019 Java 2003
2/103
//Shape.java
import java.awt.Graphics2D;
import java.awt.Color;import java.awt.Paint;
import java.awt.Stroke;
public abstract class Shape{
private int x1;
private int y1;private Paint paint;
private Stroke stroke;
// Class constructor with no argument
public Shape ()
{x1 = 0;
y1 = 0;
paint = Color.BLACK;
}
// Class constructor with three argument
public Shape( int x1Value , int y1Value , Paint paintValue , Stroke strokeValue ){
x1 = x1Value;
y1 = y1Value;paint = paintValue;
stroke = strokeValue;
}
// Each class that inherites this class must implement this method
// because this method is an abstract method
public abstract void draw( Graphics2D g2d );
public int getx1()
{return x1;
}
public void setx1( int x1Value)
{
x1 = ( x1Value > 0 ? x1Value : 0 );
}
public int gety1()
{return y1;
7/30/2019 Java 2003
3/103
}
public void sety1( int y1Value ){
y1 = ( y1Value > 0 ? y1Value : 0 );
}public Paint getPaint()
{
return paint;}
public void setPaint( Paint paintValue ){
paint = paintValue;
}
public void setStroke( Stroke strokeValue )
{
stroke = strokeValue;}
public Stroke getStroke(){
return stroke;
}
} // end class Shape
//Drawing.java
import javax.swing.JFrame;
public class Drawing
{
public static void main (String[] args)
{
DrawFrame frame = new DrawFrame();
frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
frame.setSize ( 600 , 600 );
frame.setVisible ( true );}
} // end class Drawing
7/30/2019 Java 2003
4/103
//DrawPanel.java
import javax.swing.JPanel;import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Color;import java.awt.Paint;import java.awt.GradientPaint;
import java.awt.BasicStroke;
import java.awt.Stroke;import java.awt.event.MouseAdapter;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseEvent;
public class DrawPanel extends JPanel
{
private Shape shapes[]; // Holds the shapes that the user has drawn
private Shape currentShape; // Holds the current shape the user is drawing
private Color color1; // If user uses Gradient , it holds the first colorprivate Color color2; // If user uses Gradient , it holds the second color
private Paint currentPaint; // Holds the current paint Pattern
private Stroke currentStroke; // Holds the current stroke patternprivate int lineWidth; // Holds the line width as a parameter for currentStroke
private int dashLength; // Holds the dash lenght as a parameter for currentStroke
private int shapeCount; // Holds the number of shapes the user has drawnprivate int shapeType; // Holds the current shapeType ( Line , Retangle or oval )
private int x1 , y1 , x2 , y2; // Holds necessary points
private boolean filledShape; // Holds whether to draw a fill or not
private boolean useGradient; // Holds whether to use gradient or notprivate boolean dashed; // Holds whether to draw dashed lines or not
private final int LINE = 0, // Constants for identifying how to draw different shapes
RECT = 1,OVAL = 2;
// Class constructorpublic DrawPanel()
{
shapes = new Shape[ 100 ];
currentShape = null;
color1 = Color.BLACK;
color2 = Color.BLACK;currentPaint = Color.BLACK;
currentStroke = null;
lineWidth = 1;dashLength = 1;
7/30/2019 Java 2003
5/103
shapeCount = 0;
shapeType = 0;
x1 = 0;y1 = 0;
x2 = 0;
y2 = 0;filledShape = false;useGradient = false;
dashed = false;
// Set the DrawPanel's background color
this.setBackground ( Color.WHITE );
// Register event listeners for DrawPanel
this.addMouseMotionListener ( new mouseHandler() );
this.addMouseListener ( new mouseHandler() );
} // end constructor
public void paintComponent( Graphics g ){
super.paintComponent ( g );
// Cast Graphics object "g" to Graphics2D
Graphics2D g2d = ( Graphics2D ) g;
int i = 0;
// Draw preceding shapes that the user has drawnwhile ( i < shapeCount )
{
shapes[ i ].draw ( g2d );i++;
}
// Draw the current shape that user has just drawn
if ( currentShape != null )
currentShape.draw ( g2d );
} // end method paintComponent
public void setShapeType( int shapeTypeValue ){
shapeType = shapeTypeValue;
}
7/30/2019 Java 2003
6/103
public void setCurrentPaint( Paint paintValue )
{
currentPaint = paintValue;}
public void setStroke( Stroke strokeValue ){currentStroke = strokeValue;
}
public void setFilledShape( boolean fillValue)
{
filledShape = fillValue;}
public void setUseGradient( boolean useGradientValue ){
useGradient = useGradientValue;
}
public void setColor1( Color color1Value )
{
color1 = color1Value;}
public void setColor2( Color color2Value ){
color2 = color2Value;
}
public void setDashed( boolean dashValue )
{
dashed = dashValue;}
public void setLineWidth( int lineWidthValue ){
lineWidth = lineWidthValue;
}
public void setDashLength( int dashLenghtValue )
{
dashLength = dashLenghtValue;}
public void clearLastShape(){
7/30/2019 Java 2003
7/103
if ( shapeCount > 0 ){
shapeCount--;
currentShape=null;
// Invoke method repaint to refresh the DrawPanel
this.repaint ();}}
public void clearDrawing(){
shapeCount = 0;
currentShape = null;
// Invoke method repaint to refresh the DrawPanel
this.repaint ();}
// Inner class for handling mouse events
private class mouseHandler extends MouseAdapter implements MouseMotionListener{
public void mousePressed( MouseEvent event ){
// set the shape's first point
if ( event.isAltDown () == false && event.isMetaDown () == false){x1 = event.getX ();
y1 = event.getY ();
}
}
public void mouseReleased( MouseEvent event )
{// Put the drew shape into the array "shapes"
if ( event.isAltDown () == false && event.isMetaDown () == false)
{shapes [ shapeCount ] = currentShape;
shapeCount++;
}}
public void mouseDragged( MouseEvent event )
{if ( event.isAltDown () == false && event.isMetaDown () == false)
{
// Set the shape's second point
7/30/2019 Java 2003
8/103
x2 = event.getX ();
y2 = event.getY ();
// Check whether user wants to use gradient
if ( useGradient == true )
currentPaint = new GradientPaint( 0 , 0 , color1 , 50 , 50 , color2 , true );elsecurrentPaint = color1;
// Check whether user wants to draw dashed linesif ( dashed == true ) {
float dashLenghtArray[]={ dashLength };
currentStroke = new BasicStroke( lineWidth , BasicStroke.CAP_ROUND ,BasicStroke.JOIN_ROUND , 10 , dashLenghtArray , 0 );
}
elsecurrentStroke = new BasicStroke( lineWidth );
// Create the appropriate shape according to the user selection
switch ( shapeType ){
case LINE:
currentShape = new Line( x1 , y1 , x2 , y2 , currentPaint , currentStroke);break;
case RECT:
currentShape = new Rectangle( x1 , y1 , x2 , y2 , currentPaint , currentStroke ,filledShape );
break;
case OVAL:
currentShape = new Oval( x1 , y1 , x2 , y2 , currentPaint , currentStroke ,filledShape );
break;
}
DrawPanel.this.repaint ();
} // end if
} // end method mouseDragged
} // end class MouseHandler
} // end class DrawPanel
//Line.javaimport java.awt.Graphics2D;
7/30/2019 Java 2003
9/103
import java.awt.Stroke;
import java.awt.Paint;
public class Line extends Shape
{
private int x2;private int y2;
// Class constructor with no argumentpublic Line ()
{
super();x2 = 0;
y2 = 0;
}
// Class constructor with five argument
public Line( int x1Value , int y1Value , int x2Value , int y2Value , Paint paintValue , Stroke
strokeValue ){
super ( x1Value , y1Value , paintValue , strokeValue );
x2= x2Value;y2 = y2Value;
}
// Override abstract method "draw" inherited from class "Shape" to draw a line
public void draw( Graphics2D g2d )
{
g2d.setPaint ( super.getPaint () );g2d.setStroke ( super.getStroke () );
g2d.drawLine ( super.getx1 () , super.gety1 () , x2 , y2 );}
} // end class Line
//Oval.javaimport java.awt.Graphics2D;
import java.awt.Color;
import java.awt.Stroke;
import java.awt.Paint;
public class Oval extends Shape
{
7/30/2019 Java 2003
10/103
private int width;
private int height;
private boolean fill;
// Class constructor with no argument
public Oval (){super();
width = 1;
height = 1;fill = false;
}
// Class constructor with six argument
public Oval( int x1Value , int y1Value , int x2Value , int y2Value , Paint paintValue , Stroke
strokeValue , boolean fillValue ){
super( x1Value < x2Value ? x1Value : x2Value , y1Value < y2Value ? y1Value : y2Value ,
paintValue , strokeValue );
width = Math.abs ( x1Value - x2Value );height = Math.abs ( y1Value - y2Value );
fill = fillValue;
}
// Override abstract method "draw" inherited from class "Shape" to draw an oval
public void draw ( Graphics2D g2d ){
g2d.setPaint ( super.getPaint () );
g2d.setStroke ( super.getStroke () );
if ( fill == true )
g2d.fillOval ( super.getx1 () , super.gety1 () , width , height );
elseg2d.drawOval ( super.getx1 () , super.gety1 () , width , height );
}
} // end class Oval
//DrawFrame.java
import javax.swing.JFrame;import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JLabel;import javax.swing.JTextField;
7/30/2019 Java 2003
11/103
import javax.swing.JComboBox;
import javax.swing.JCheckBox;
import javax.swing.JColorChooser;import javax.swing.JOptionPane;
import java.awt.Color;
import java.awt.FlowLayout;import java.awt.BorderLayout;import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import java.awt.event.KeyAdapter;import java.awt.event.KeyEvent;
public class DrawFrame extends JFrame{
private DrawPanel drawPanel;
private JPanel panel1;
private JPanel panel2;private JPanel panel3;
private JButton undoButton;
private JButton clearButton;private JButton firstColorButton;
private JButton secondColorButton;
private JComboBox shapeComboBox;private JCheckBox fillCheckBox;
private JCheckBox gradientCheckBox;
private JCheckBox dashCheckBox;
private JLabel shapesLabel;private JLabel widthLabel;
private JLabel lengthLabel;
private JTextField widthTextField;private JTextField dashLengthTextField;
private final String shapeNames[] = { "Line" , "Rectangle" ,"Oval" };
// Class constructor
public DrawFrame (){
// Set the title of JFrame
setTitle ( "Drawing Application" );
// Create a JPanel as a container for GUI components in first row
panel1 = new JPanel();
// Set the layout of panel1
7/30/2019 Java 2003
12/103
panel1.setLayout ( new FlowLayout( FlowLayout.CENTER ) );
// Create a JPanel as a container for GUI components in second rowpanel2 = new JPanel();
// Set the layout of panel2panel2.setLayout ( new FlowLayout( FlowLayout.CENTER ) );
// Create a JPanel to hold panel1 , panel2 and panel3
panel3 = new JPanel();
// Set the layout of panel4
panel3.setLayout ( new GridLayout( 2,1,0,0) );
// Create button "Undo" and add it to the panel
undoButton = new JButton();undoButton.setText( "Undo" );
undoButton.addActionListener (
// Create and register an ActionListener
new ActionListener(){
public void actionPerformed( ActionEvent event )
{drawPanel.clearLastShape ();
}
}
);
panel1.add ( undoButton );
// Create button "Clear" and add it to panel1
clearButton = new JButton();
clearButton.setText( "Clear" );clearButton.addActionListener (
// Create and register an ActionListener
new ActionListener(){
public void actionPerformed( ActionEvent event )
{drawPanel.clearDrawing ();
}
}
);panel1.add ( clearButton );
// Create label "shapesLabel" and add it to panel1shapesLabel = new JLabel();
7/30/2019 Java 2003
13/103
shapesLabel.setText ( "Shapes:" );
panel1.add ( shapesLabel );
// Create a combobox that contains shape names and add it to panel1
shapeComboBox = new JComboBox( shapeNames);
shapeComboBox.setMaximumRowCount ( 3 );shapeComboBox.addItemListener (// Create and register an ItemLsitener
new ItemListener()
{public void itemStateChanged( ItemEvent event )
{
if ( event.getStateChange () == ItemEvent.SELECTED )drawPanel.setShapeType ( shapeComboBox.getSelectedIndex () );
}
}
);
panel1.add ( shapeComboBox );
// Create checkbox "fillCheckBox" and add it to panel1
fillCheckBox = new JCheckBox();
fillCheckBox.setText ( "Filled" );fillCheckBox.addItemListener (
// Create and register an ItemListener
new ItemListener(){
public void itemStateChanged( ItemEvent event )
{
drawPanel.setFilledShape ( fillCheckBox.isSelected () );}
}
);
panel1.add ( fillCheckBox );
// Create checkbox "gradientCheckBox" and add it to panel2
gradientCheckBox = new JCheckBox();
gradientCheckBox.setText ( "Use Gradient" );gradientCheckBox.addItemListener (
// Create and register an ItemListener
new ItemListener()
{public void itemStateChanged( ItemEvent event )
{
drawPanel.setUseGradient ( gradientCheckBox.isSelected () );}
7/30/2019 Java 2003
14/103
}
);
panel2.add ( gradientCheckBox );
// Create button "firstColor" and add it to panel2
firstColorButton = new JButton();firstColorButton.setText ( "1st Color..." );firstColorButton.addActionListener (
// Create and register an ActionListener
new ActionListener(){
public void actionPerformed( ActionEvent event )
{Color color = Color.BLACK;
color = JColorChooser.showDialog ( null , "Color Chooser" , color );
if ( color == null)
color = color.BLACK;
drawPanel.setColor1 ( color );
}
});
panel2.add ( firstColorButton );
// Create button "secondColor" and add it to panel2
secondColorButton = new JButton();
secondColorButton.setText ( "2nd Color..." );
secondColorButton.addActionListener (// Create and register an ActionListener
new ActionListener()
{public void actionPerformed( ActionEvent event )
{
Color color = Color.BLACK;
color = JColorChooser.showDialog ( null , "Color Chooser" , color );
if ( color == null)
color = color.BLACK;
drawPanel.setColor2 ( color );}
}
);panel2.add ( secondColorButton );
7/30/2019 Java 2003
15/103
// Create label "widthLabel" and set its properties
widthLabel = new JLabel();widthLabel.setText ( "Line width:" );
panel2.add ( widthLabel );
// Create text field "widthTextField" and set its propertieswidthTextField = new JTextField();
widthTextField.addKeyListener(
// Create and register an KeyListenernew KeyAdapter()
{
public void keyReleased( KeyEvent e){
int lineWidth;
try
{
lineWidth = Integer.parseInt ( widthTextField.getText () );
if ( lineWidth < 1 || lineWidth > 20 )
throw new NumberFormatException();
drawPanel.setLineWidth ( lineWidth );
}
catch ( NumberFormatException exception ){
JOptionPane.showMessageDialog( null , "Please enter an integer between 1 to
20" , "Error" , JOptionPane.INFORMATION_MESSAGE );
widthTextField.setText( "" );}
}
});
widthTextField.setColumns ( 2 );
panel2.add ( widthTextField );
// create label "lenghtLabel" and set its properties
lengthLabel = new JLabel();lengthLabel.setText ( "Dash length:" );
panel2.add ( lengthLabel );
// Create text field "dashLenghtTextField" and set its propertiesdashLengthTextField = new JTextField();
dashLengthTextField.setColumns ( 2 );
dashLengthTextField.addKeyListener(// Create and register an KeyListener
7/30/2019 Java 2003
16/103
new KeyAdapter()
{
public void keyReleased( KeyEvent e){
int dashLength;
try{
dashLength = Integer.parseInt ( dashLengthTextField.getText () );
if ( dashLength < 1 || dashLength > 50 )
throw new NumberFormatException();
drawPanel.setDashLength ( dashLength );
}
catch ( NumberFormatException exception ){
JOptionPane.showMessageDialog( null , "Please enter an integer between 1 to
50" , "Error" , JOptionPane.INFORMATION_MESSAGE );
dashLengthTextField.setText( "" );}
}
});
panel2.add ( dashLengthTextField );
// Create check box "dashCheckBox" and set its properties
dashCheckBox = new JCheckBox();
dashCheckBox.setText ( "Dashed" );
dashCheckBox.addItemListener (// Create and register an ItemLitener
new ItemListener()
{public void itemStateChanged( ItemEvent event )
{
drawPanel.setDashed ( dashCheckBox.isSelected () );}
}
);panel2.add ( dashCheckBox );
// Add panel1 to panel3
panel3.add ( panel1 );
// add panel2 to panel3
panel3.add ( panel2 );
7/30/2019 Java 2003
17/103
// Add panel3 to the south region of JFrame
this.add ( panel3 , BorderLayout.NORTH );
// Create an object of type DrawPanel
drawPanel = new DrawPanel();
// Add "DrawPanel" object to JFramethis.add ( drawPanel );
} // end constructor
} // end class DrawFrame
//Rectangle.java
import java.awt.Graphics2D;
import java.awt.Color;
import java.awt.Stroke;import java.awt.Paint;
public class Rectangle extends Shape{
private int width;private int height;
private boolean fill;
// Class constructor with no argumentpublic Rectangle ()
{
super();width = 1;
height = 1;
fill = false;}
// Class constructor with six argumentpublic Rectangle( int x1Value , int y1Value , int x2Value , int y2Value , Paint paintValue ,
Stroke strokeValue , boolean fillValue )
{
super( x1Value < x2Value ? x1Value : x2Value , y1Value < y2Value ? y1Value : y2Value ,paintValue , strokeValue );
width = Math.abs ( x1Value - x2Value );
height = Math.abs ( y1Value - y2Value );fill = fillValue;
7/30/2019 Java 2003
18/103
}
// Override abstract method "draw" inherited from class "Shape" to draw a rectanglepublic void draw ( Graphics2D g2d )
{
g2d.setPaint ( super.getPaint () );g2d.setStroke ( super.getStroke () );
if ( fill == true )
g2d.fillRect ( super.getx1 () , super.gety1 () , width , height );else
g2d.drawRect ( super.getx1 () , super.gety1 () , width , height );
}
} // end class Rectangle
OUTPUT:
7/30/2019 Java 2003
19/103
RESULT:
Thus the program is written to implement simple paint like program.
11 SCIENTIFIC CALCULATOR 2.9.2010
7/30/2019 Java 2003
20/103
AIM: To write a program to implement scientific calculator using even-driven programming.
ALGORITHM:Step 1: Start the program.
Step 2: Import the required packages.
Step 3: Create class that extends frame.Step 4: Create text field and buttons.
Step 5: Add buttons to panel.
Step 6: Add mouse listener and perform necessary operation.Step 7: Exit the application.
PROGRAM:
7/30/2019 Java 2003
21/103
//Scientific Calculator
import java.awt.BorderLayout;
import java.awt.Color;import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;import java.awt.FlowLayout;import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;
import java.io.IOException;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.WindowConstants;import javax.swing.border.EmptyBorder;
public class Calc extends JFrame implements ActionListener,MouseListener //,KeyListener
{
private JButton
jb_one,jb_two,jb_three,jb_four,jb_five,jb_six,jb_seven,jb_eight,jb_nine,jb_zero;
private JButton jb_plus,jb_minus,jb_divide,jb_multiply;private JButton jb_sin,jb_cos,jb_tan,jb_asin,jb_acos,jb_atan,jb_pie,jb_E;
private JButton jb_decimalpoint,jb_equalto,jb_fact,jb_power,jb_changesign,jb_reciporcal;
private JButton jb_todeg,jb_torad,jb_round,jb_CA,jb_CE,jb_Backspace;
private JRadioButton jrb_deg,jrb_rad;private ButtonGroup jrb_group;
private JTextField jtf_display;
7/30/2019 Java 2003
22/103
private double tempdisplayNum;
boolean plusPressed,minusPressed,mulPressed,divPressed,equalPressed,powerPressed;
/**
* This constructor forms GUI and add required Compontents
* to listeners.*/public Calc()
{
super("Scientic Calculator ( Currently running on JVM Version " +
System.getProperty("java.version") + " )");
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e){
Calc.this.dispose();
System.runFinalization();System.gc();
System.exit(0);
}});
tempdisplayNum = 0;
resetAllButton();equalPressed = false;
/** GUI Formation
*/
JPanel jp_main = new JPanel();jp_main.setLayout(new BorderLayout());
jp_main.setBorder(new EmptyBorder(new Insets(3,5,5,5)));
JPanel jp_top = new JPanel();jp_top.setLayout(new BorderLayout());
JPanel jp_top_down = new JPanel();
jp_top_down.setLayout(new BorderLayout());
JPanel jp_top_west = new JPanel();jb_Backspace = new JButton("BackSpace");
jp_top_west.setLayout(new FlowLayout(FlowLayout.LEFT,0,5));
jp_top_west.add(jb_Backspace);JPanel jp_top_east = new JPanel();
7/30/2019 Java 2003
23/103
jp_top_east.setLayout(new FlowLayout(FlowLayout.RIGHT));
jtf_display = new JTextField();
jtf_display.setEditable(false);jtf_display.setHorizontalAlignment( JTextField.RIGHT );
jtf_display.setRequestFocusEnabled(false);
jtf_display.setBackground(Color.white);jrb_deg = new JRadioButton("Degrees");jrb_rad = new JRadioButton("Radian");
jrb_deg.setSelected(true);
jrb_group = new ButtonGroup();jrb_group.add(jrb_deg);
jrb_group.add(jrb_rad);
jp_top_east.add(jrb_deg);jp_top_east.add(jrb_rad);
jp_top_down.add(jp_top_east,BorderLayout.EAST);
jp_top_down.add(jp_top_west,BorderLayout.WEST);jp_top.setLayout(new BorderLayout());
jp_top.add(jtf_display,BorderLayout.CENTER);
jp_top.add(jp_top_down,BorderLayout.SOUTH);
JPanel jp_center = new JPanel();jp_center.setLayout(new GridLayout(5,7,5,5));
jb_one = new JButton("1");
jb_two = new JButton("2");jb_three = new JButton("3");
jb_four = new JButton("4");
jb_five = new JButton("5");
jb_six = new JButton("6");jb_seven = new JButton("7");
jb_eight = new JButton("8");
jb_nine = new JButton("9");jb_zero = new JButton("0");
jb_plus = new JButton("+");
jb_minus = new JButton("-");jb_divide = new JButton("/");
jb_multiply = new JButton("*");
jb_sin = new JButton("Sin");jb_cos = new JButton("Cos");
jb_tan = new JButton("Tan");
jb_asin = new JButton("aSin");
jb_acos = new JButton("aCos");jb_atan = new JButton("aTan");
jb_pie = new JButton("PI");
jb_E = new JButton("E");jb_decimalpoint = new JButton(".");
7/30/2019 Java 2003
24/103
jb_equalto = new JButton("=");
jb_fact = new JButton("x!");
jb_power = new JButton("x^n");jb_changesign = new JButton("+/-");
jb_reciporcal = new JButton("1/x");
jb_todeg = new JButton("toDeg");jb_torad = new JButton("toRad");jb_round = new JButton("Round");
jb_CA = new JButton("CA");
jb_CE = new JButton("CE");
/**
* Adding Button to Listeners*/
jb_one.addActionListener(Calc.this);
jb_two.addActionListener(Calc.this);jb_three.addActionListener(Calc.this);
jb_four.addActionListener(Calc.this);
jb_five.addActionListener(Calc.this);
jb_six.addActionListener(Calc.this);jb_seven.addActionListener(Calc.this);
jb_eight.addActionListener(Calc.this);
jb_nine.addActionListener(Calc.this);jb_zero.addActionListener(Calc.this);
jb_plus.addActionListener(Calc.this);
jb_minus.addActionListener(Calc.this);jb_divide.addActionListener(Calc.this);
jb_multiply.addActionListener(Calc.this);
jb_sin.addActionListener(Calc.this);
jb_cos.addActionListener(Calc.this);jb_tan.addActionListener(Calc.this);
jb_asin.addActionListener(Calc.this);
jb_acos.addActionListener(Calc.this);jb_atan.addActionListener(Calc.this);
jb_pie.addActionListener(Calc.this);
jb_E.addActionListener(Calc.this);jb_decimalpoint.addActionListener(Calc.this);
jb_equalto.addActionListener(Calc.this);
jb_fact.addActionListener(Calc.this);jb_power.addActionListener(Calc.this);
jb_changesign.addActionListener(Calc.this);
jb_reciporcal.addActionListener(Calc.this);
jb_todeg.addActionListener(Calc.this);jb_torad.addActionListener(Calc.this);
jb_round.addActionListener(Calc.this);
jb_CA.addActionListener(Calc.this);jb_CE.addActionListener(Calc.this);
7/30/2019 Java 2003
25/103
jb_Backspace.addActionListener(Calc.this);
jp_center.add(jb_one);
jp_center.add(jb_two);jp_center.add(jb_three);jp_center.add(jb_multiply);
jp_center.add(jb_reciporcal);
jp_center.add(jb_sin);jp_center.add(jb_asin);
jp_center.add(jb_four);
jp_center.add(jb_five);jp_center.add(jb_six);
jp_center.add(jb_divide);
jp_center.add(jb_power);jp_center.add(jb_cos);
jp_center.add(jb_acos);
jp_center.add(jb_seven);
jp_center.add(jb_eight);jp_center.add(jb_nine);
jp_center.add(jb_plus);
jp_center.add(jb_changesign);jp_center.add(jb_tan);
jp_center.add(jb_atan);
jp_center.add(jb_zero);jp_center.add(jb_decimalpoint);
jp_center.add(jb_equalto);
jp_center.add(jb_minus);
jp_center.add(jb_fact);jp_center.add(jb_pie);
jp_center.add(jb_E);
jp_center.add(jb_CA);jp_center.add(jb_CE);
jp_center.add(jb_round);
jp_center.add(jb_todeg);jp_center.add(jb_torad);
Container cp = this.getContentPane();jp_main.add(jp_top,BorderLayout.NORTH);
jp_main.add(jp_center,BorderLayout.CENTER);
cp.add(jp_main,BorderLayout.CENTER);
setSize(520,250);/* Packing all Commponent, so spaces are left */
pack();
/* Making Window to appear in Center of Screen */Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
7/30/2019 Java 2003
26/103
Dimension frameSize = this.getPreferredSize();
setLocation(screenSize.width/2 - (frameSize.width/2),screenSize.height/2 -
(frameSize.height/2));setVisible(true);
this.requestFocus();}
/**
* This method is used to reset the condition that* No plus,minus,multiply,division or power action is going on
* if there is cancel it.
*/public void resetAllButton()
{
plusPressed = false;minusPressed = false;
mulPressed = false;
divPressed = false;
powerPressed = false;}
/*** This method is use to calculate the factorial of
* number of double data type
*
* @param Double value
* @return String value
*/
public String factorial(double num){
int theNum = (int)num;
if (theNum < 1)
{
JOptionPane.showMessageDialog(Calc.this,"Cannot find the factorial of numbers less than1.","Facorial Error",JOptionPane.WARNING_MESSAGE);
return ("0");
}else
{
for (int i=(theNum -1); i > 1; --i)
theNum *= i;return Integer.toString(theNum);
}
}
7/30/2019 Java 2003
27/103
/**
* This is important method where All action takes places*/
public void actionPerformed(ActionEvent e)
{String s = e.getActionCommand();String temptext = jtf_display.getText();
boolean decimalPointFound = false;
double displayNumber = 0;
/**
* Converts String value of jtf_display's to Double value for Calculation*/
try
{displayNumber = Double.valueOf(jtf_display.getText()).doubleValue();
}
catch(NumberFormatException nfe) {}
/**
* Checks if equal button is pressed
*/if(equalPressed)
{
jtf_display.setText("");equalPressed = false;
}
if(s.equals("1"))
jtf_display.setText(jtf_display.getText()+"1");
if(s.equals("2"))jtf_display.setText(jtf_display.getText()+"2");
if(s.equals("3"))
jtf_display.setText(jtf_display.getText()+"3");if(s.equals("4"))
jtf_display.setText(jtf_display.getText()+"4");
if(s.equals("5"))jtf_display.setText(jtf_display.getText()+"5");
if(s.equals("6"))
jtf_display.setText(jtf_display.getText()+"6");
if(s.equals("7"))jtf_display.setText(jtf_display.getText()+"7");
if(s.equals("8"))
jtf_display.setText(jtf_display.getText()+"8");if(s.equals("9"))
7/30/2019 Java 2003
28/103
jtf_display.setText(jtf_display.getText()+"9");
if(s.equals("0") && !temptext.equals(""))jtf_display.setText(jtf_display.getText()+"0");
if(s.equals("E"))jtf_display.setText(Double.toString(Math.E));if(s.equals("PI"))
jtf_display.setText(Double.toString(Math.PI));
if(s.equals("toDeg"))jtf_display.setText(Double.toString(Math.toDegrees(displayNumber)));
if(s.equals("toRad"))
jtf_display.setText(Double.toString(Math.toRadians(displayNumber)));
if(s.equals("CE"))
jtf_display.setText("");if(s.equals("CA"))
{
resetAllButton();
jtf_display.setText("");}
if(s.equals("."))
{for (int i =0; i < temptext.length(); ++i)
{
if(temptext.charAt(i) == '.')
{decimalPointFound = true;
continue;
}}
if(!decimalPointFound && temptext.length()==0)
jtf_display.setText("0.");if(!decimalPointFound && temptext.length()!=0)
jtf_display.setText(jtf_display.getText()+".");
}
/**
* Calulation of sin,cos etc
*/if(s.equals("Sin"))
{
if(jrb_deg.isSelected())jtf_display.setText(Double.toString(Math.sin((displayNumber*Math.PI)/180)));
7/30/2019 Java 2003
29/103
else
{
jtf_display.setText(Double.toString(Math.sin(displayNumber)));// decimalPointpressed
}
}
if(s.equals("Cos"))
{
if(jrb_deg.isSelected())jtf_display.setText(Double.toString(Math.cos((displayNumber*Math.PI)/180)));
else
{jtf_display.setText(Double.toString(Math.cos(displayNumber)));
// decimalPointpressed
}}
if(s.equals("Tan"))
{if(jrb_deg.isSelected())
jtf_display.setText(Double.toString(Math.tan((displayNumber*Math.PI)/180)));
else{
jtf_display.setText(Double.toString(Math.tan(displayNumber)));
// decimalPointpressed}
}
if(s.equals("aSin")){
if(jrb_deg.isSelected())
jtf_display.setText(Double.toString(Math.asin((displayNumber*Math.PI)/180)));else
{
jtf_display.setText(Double.toString(Math.asin(displayNumber)));// decimalPointpressed
}
}
if(s.equals("aCos"))
{
if(jrb_deg.isSelected())jtf_display.setText(Double.toString(Math.acos((displayNumber*Math.PI)/180)));
else
{jtf_display.setText(Double.toString(Math.acos(displayNumber)));
7/30/2019 Java 2003
30/103
// decimalPointpressed
}
}
if(s.equals("aTan"))
{if(jrb_deg.isSelected())jtf_display.setText(Double.toString(Math.atan((displayNumber*Math.PI)/180)));
else
{jtf_display.setText(Double.toString(Math.atan(displayNumber)));
// decimalPointpressed
}}
/*** Calculation of "/""*""+""-"
*/
if(s.equals("*"))
{resetAllButton();
mulPressed = true;
try{
tempdisplayNum = displayNumber;
}catch(NumberFormatException mule)
{ tempdisplayNum = 0; }
jtf_display.setText("");
}
if(s.equals("+"))
{resetAllButton();
plusPressed = true;
try{
tempdisplayNum = displayNumber;
}catch(NumberFormatException pluse)
{ tempdisplayNum = 0; }
jtf_display.setText("");
}
if(s.equals("-"))
{resetAllButton();
7/30/2019 Java 2003
31/103
minusPressed = true;
try
{tempdisplayNum = displayNumber;
}
catch(NumberFormatException sube){ tempdisplayNum = 0; }jtf_display.setText("");
}
if(s.equals("/"))
{
resetAllButton();divPressed = true;
try
{tempdisplayNum = displayNumber;
}
catch(NumberFormatException dive)
{ tempdisplayNum = 0; }jtf_display.setText("");
}
/**
* It calculate power
*/if(s.equals("x^n"))
{
powerPressed = true;
try{
tempdisplayNum = displayNumber;
}catch(NumberFormatException dive)
{ tempdisplayNum = 0; }
jtf_display.setText("");}
/*** Events after "=" is pressed
*/
if(s.equals("="))
{if(mulPressed)
jtf_display.setText(Double.toString(tempdisplayNum*displayNumber));
if(plusPressed)jtf_display.setText(Double.toString(tempdisplayNum+displayNumber));
7/30/2019 Java 2003
32/103
if(minusPressed)
jtf_display.setText(Double.toString(tempdisplayNum-displayNumber));
if(divPressed)jtf_display.setText(Double.toString(tempdisplayNum/displayNumber));
if(powerPressed)
jtf_display.setText(Double.toString(Math.pow(tempdisplayNum,displayNumber)));
resetAllButton();
equalPressed = true;
}
/**
* Events for more functions "1/x""+/-""x!""Round"*/
if(s.equals("1/x"))
jtf_display.setText(Double.toString(1/displayNumber));if(s.equals("+/-") && displayNumber!=0)
jtf_display.setText(Double.toString(-displayNumber));
if(s.equals("x!"))
jtf_display.setText(factorial(displayNumber));if(s.equals("Round"))
jtf_display.setText(Double.toString(Math.round(displayNumber)));
/**
* For BackSpace Event
*/if(s.equals("BackSpace"))
{
String temptextt = jtf_display.getText();
if(!temptextt.equals(""))jtf_display.setText(temptextt.substring(0, temptextt.length() - 1));
}
}
public void mouseClicked(MouseEvent me){
}
public void mouseEntered(MouseEvent me)
{
}
public void mouseExited(MouseEvent me){
7/30/2019 Java 2003
33/103
}
public void mouseReleased(MouseEvent me) {}
public void mousePressed(MouseEvent me) {}
public static void main(String args[]){
try
{UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch(Exception e){}
new Calc();
}}
OUTPUT:
7/30/2019 Java 2003
34/103
RESULT:
Thus the program is written to implement Scientific Calculator.
12 LINKED LIST 9.9.2010
7/30/2019 Java 2003
35/103
AIM: To write a java program to implement linked list in java.
ALGORITHM:Step 1:Start the program.
Step 2:Create a linked list.
Step 3:Enter elements into the list.Step4:Then enter elements into the various positions in the list.
Step 5:Delete elements in the list.
Step 6:Stop
PROGRAM:
7/30/2019 Java 2003
36/103
import java.util.*;
public class LinkedListExample{public static void main(String[] args) {
System.out.println("Linked List Example!");
LinkedList list = new LinkedList();int num1 = 11, num2 = 22, num3 = 33, num4 = 44;int size;
Iterator iterator;
//Adding data in the listlist.add(num1);
list.add(num2);
list.add(num3);list.add(num4);
size = list.size();
System.out.print( "Linked list data: ");//Create a iterator
iterator = list.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next()+" ");}
System.out.println();
//Check list empty or notif (list.isEmpty()){
System.out.println("Linked list is empty");
}else{
System.out.println( "Linked list size: " + size);
}
System.out.println("Adding data at 1st location: 55");//Adding first
list.addFirst(55);
System.out.print("Now the list contain: ");iterator = list.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next()+" ");}
System.out.println();
System.out.println("Now the size of list: " + list.size());System.out.println("Adding data at last location: 66");
//Adding last or append
list.addLast(66);
System.out.print("Now the list contain: ");iterator = list.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next()+" ");}
7/30/2019 Java 2003
37/103
System.out.println();
System.out.println("Now the size of list: " + list.size());
System.out.println("Adding data at 3rd location: 55");//Adding data at 3rd position
list.add(2,99);
System.out.print("Now the list contain: ");iterator = list.iterator();while (iterator.hasNext()){
System.out.print(iterator.next()+" ");
}System.out.println();
System.out.println("Now the size of list: " + list.size());
//Retrieve first dataSystem.out.println("First data: " + list.getFirst());
//Retrieve lst data
System.out.println("Last data: " + list.getLast());//Retrieve specific data
System.out.println("Data at 4th position: " + list.get(3));
//Remove first
int first = list.removeFirst();System.out.println("Data removed from 1st location: " + first);
System.out.print("Now the list contain: ");
iterator = list.iterator();//After removing data
while (iterator.hasNext()){
System.out.print(iterator.next()+" ");}
System.out.println();
System.out.println("Now the size of list: " + list.size());
//Remove lastint last = list.removeLast();
System.out.println("Data removed from last location: " + last);
System.out.print("Now the list contain: ");iterator = list.iterator();
//After removing data
while (iterator.hasNext()){System.out.print(iterator.next()+" ");
}
System.out.println();System.out.println("Now the size of list: " + list.size());
//Remove 2nd data
int second = list.remove(1);
System.out.println("Data removed from 2nd location: " + second);System.out.print("Now the list contain: ");
iterator = list.iterator();
//After removing datawhile (iterator.hasNext()){
7/30/2019 Java 2003
38/103
System.out.print(iterator.next()+" ");
}
System.out.println();System.out.println("Now the size of list: " + list.size());
//Remove all
list.clear();if (list.isEmpty()){System.out.println("Linked list is empty");
}
else{System.out.println( "Linked list size: " + size);
}
}}
OUTPUT:E:\java>java LinkedListExampleLinked List Example!
Linked list data: 11 22 33 44
Linked list size: 4Adding data at 1st location: 55
Now the list contain: 55 11 22 33 44
Now the size of list: 5
7/30/2019 Java 2003
39/103
Adding data at last location: 66
Now the list contain: 55 11 22 33 44 66
Now the size of list: 6Adding data at 3rd location: 55
Now the list contain: 55 11 99 22 33 44 66
Now the size of list: 7First data: 55Last data: 66
Data at 4th position: 22
Data removed from 1st location: 55Now the list contain: 11 99 22 33 44 66
Now the size of list: 6
Data removed from last location: 66Now the list contain: 11 99 22 33 44
Now the size of list: 5
Data removed from 2nd location: 99Now the list contain: 11 22 33 44
Now the size of list: 4
Linked list is empty
RESULT:
Thus the program is written to implement linked list.
13 PRODUCER CONSUMER USING MULTITHREAD 9.9.2010
AIM:To design a thread safe implementation of queue class.
ALGORITHM:1.The producer creates tasks and inserts them into work queue.2.The consumer thread pick up task queue and execute then.
7/30/2019 Java 2003
40/103
3.Simple instances of this paradigm in which the task queue can hold only one task,which may be
sort or long but it is typically hava bounded size.
4.In this simple model,the producer thread can estimate the time taken for consumer work andinsert new work in shared buffer.
5.Several possibilities exist in which the producer thread must not overwrite the shared buffer
when the previous task has not been picked by consumer thread.6.Also,the consumer thread must not pick up tasks until there is something present in the shareddata structure and individual consumer thread picks up tasks one at a time.
7.Stop
PROGRAM:
class Q {
int n;boolean valueSet = false;
synchronized int get() {
if(!valueSet)try {
wait();
7/30/2019 Java 2003
41/103
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}System.out.println("Got: " + n);
valueSet = false;
notify();return n;}
synchronized void put(int n) {
if(valueSet)try {
wait();
} catch(InterruptedException e) {System.out.println("InterruptedException caught");
}
this.n = n;valueSet = true;
System.out.println("Put: " + n);
notify();
}}
class Producer implements Runnable {
Q q;
Producer(Q q) {this.q = q;
new Thread(this, "Producer").start();
}public void run() {
int i = 0;
while(true) {q.put(i++);
}
}}
class Consumer implements Runnable {
Q q;
Consumer(Q q) {this.q = q;
new Thread(this, "Consumer").start();
}
public void run() {while(true) {
q.get();
}
7/30/2019 Java 2003
42/103
}
}
class PCFixed {
public static void main(String args[]) {
Q q = new Q();new Producer(q);
new Consumer(q);System.out.println("Press Control-C to stop.");
}
}
OUTPUT:
Got: 2441
Put: 2442
Got: 2442
Put: 2443
7/30/2019 Java 2003
43/103
Got: 2443
Put: 2444
Got: 2444
Put: 2445
Got: 2445
Put: 2446
Got: 2446
Put: 2447
Got: 2447
Put: 2448
Got: 2448
Put: 2449
Got: 2449
Put: 2450
Got: 2450
Put: 2451
Got: 2451
Put: 2452
Got: 2452
Put: 2453
Got: 2453
Put: 2454
Got: 2454
7/30/2019 Java 2003
44/103
Put: 2455
Got: 2455
Put: 2456
Got: 2456
Put: 2457
Got: 2457
Put: 2458
Got: 2458
Put: 2459
RESULT:
Thus the program is written to implement Producer Consumer problem.
14 FIBONICCI AND PRIME USING MULTITHREAD 17.9.2010
AIM:To Write Program to develop multithreaded concept using pipes
ALGORITHM:
Step 1:Start the program
Step 2:Import required packages
Step3:Declare necessary variables and function
7/30/2019 Java 2003
45/103
Step 4:Create object parameters pr and pw to pass the values
Step5: Using thread1()Function find the parameters find prime numbers and Fibonacci series
And numbers common both the series.Step 6:Stop the program
PROGRAM:
import java.io.*;
import java.util.*;class MyThread1 extends Thread {
private PipedReader pr;
private PipedWriter pw;
MyThread1(PipedReader pr, PipedWriter pw) {
this.pr = pr;
7/30/2019 Java 2003
46/103
this.pw = pw;
}
public void run() {
try {
int i;for (i=1;i
7/30/2019 Java 2003
47/103
f3 = f1 + f2;
}
pw.close();} catch (IOException e) {
}
}}class MultithreadedProgram {
public static void main(String[] args) throws Exception {
ArrayList list1=new ArrayList();ArrayList list2=new ArrayList();
PipedWriter pw1 = new PipedWriter();
PipedReader pr1 = new PipedReader(pw1);MyThread1 mt1 = new MyThread1(pr1, pw1);
System.out.println("Prime Numbers: ");
mt1.start();int item1;
while ((item1 = pr1.read()) != -1){
char ch1=((char) item1);
System.out.print(Character.toString(ch1));list1.add(Character.toString(ch1));
}
pr1.close();PipedWriter pw2 = new PipedWriter();
PipedReader pr2 = new PipedReader(pw2);
MyThread2 mt2 = new MyThread2(pr2, pw2);System.out.println("Fibonacci Numbers: ");
mt2.start();
int item2;
while ((item2 = pr2.read()) != -1){char ch2=((char) item2);
System.out.print(Character.toString(ch2));
list2.add(Character.toString(ch2));}
pr2.close();
System.out.println("Elements common to both lists are:");list1.retainAll(list2);
for(int i=0;i
7/30/2019 Java 2003
48/103
OUTPUT:Prime Numbers:
23
5
7Fibonacci Numbers:
1
23
5
8
13
7/30/2019 Java 2003
49/103
21
34
55Elements common to both lists are:
2
35
RESULT:
Thus the program is written to find prime and Fibonicci number and the elements that are
common to both the lists.
8 DYNAMIC POLYMORPHISM 11.8.2010
Aim:To develop with suitable hierarchy,classes for
point,shape,circle,Rectangule,RectangularSolid etc.Design a simple test application to
demonstrate Dynamic polymorphism.
Algorithm:
STEP 1:Start the program.
STEP 2:Create the abstract class shape.
7/30/2019 Java 2003
50/103
STEP 3:Declare the methods and abstract method.
STEP 4:Define point class which extends shape.
STEP 5:Define constructors and member function of that class.STEP 6:Create a circle which extends the sample class.
STEP 7:Create a constructor for that class which calls the superclass constructors.
STEP 8:Caluculatethe area of the circle.STEP 9:Create a class named cylinder which extends Circle.STEP 10:Create aconstructor which tells superclass constructor.
STEP 11:Calculate the area and volume of the cylinder using suitable methods.
STEP 12:Declare a class rectangle which inherit the parts.STEP 13:Calculate the area of the rectangle.
STEP 14:Create a RectangularSolid class which extends the rectangle class.
STEP 15:Define the member function of that class.STEP 16:Create a class named ShapeTest.
STEP 17:Create object for all the class.
STEP 18:Print the shapes as an array of ShapeSTEP 19:Sort array of shapes using insertion sort
STEP 20:Stop the program.
PROGRAM :
public abstract class Shape{
private static int counter = 0;
private int idNumber;public Shape ()
{
idNumber = ++counter;}
public int getIdNumber() { return idNumber;}
public double area() { return 0.0; }
public double volume() { return 0.0; }
7/30/2019 Java 2003
51/103
public abstract String getName(); // abstract, so omit body
}
public class Point extends Shape
{
protected int x, y;public Point( int a, int b ) { x = a; y = b; }public int getX() { return x; }
public int getY() { return y; }
public String toString(){
return "[" + x + ", " + y + "]";
}public String getName() { return "Point"; }
}
public class Circle extends Point
{
protected double radius;
public Circle( double r, int a, int b ){
super( a, b );
radius = ( r >= 0 ? r : 0 );}
public double area() { return Math.PI * radius * radius; }
public String toString(){
return "Center = " + super.toString() +"; Radius = " + radius;
}
public String getName() { return "Circle"; }}
public class Cylinder extends Circle
{
protected double height;public Cylinder( double h, double r, int a, int b )
{
super( r, a, b );height = ( h >= 0 ? h : 0 );
}
public double area()
{return 2 * super.area() + 2 * Math.PI * radius * height;
}
public double volume() { return super.area() * height; }
7/30/2019 Java 2003
52/103
public String toString()
{
return super.toString() + "; Height = " + height;}
public String getName() { return "Cylinder"; }
}
public class Rectangle extends Point
{
protected double length;protected double width;
public Rectangle( double len, double wid, int a, int b )
{super( a, b );
length = ( len >= 0 ? len : 0 );
width = ( wid >= 0 ? wid : 0 );}
public double area() { return length * width; }
public String toString()
{return "Center = " + super.toString() + "; Length = " + length + ", Width =
" + width;
}public String getName()
{
if (length == width) return "Square";else return "Rectangle";
}
}
public class RectangularSolid extends Rectangle{
protected double height;
public RectangularSolid(double h, double len, double wid, int a, int b){
super(len, wid, a, b);
height = ( h >= 0 ? h : 0 );}
public double area()
{
return 2 * super.area() +2 * length * height +2 * width * height;}
public double volume() { return super.area() * height; }
public String toString(){
7/30/2019 Java 2003
53/103
return super.toString() + "; Height = " + height;
}
public String getName(){
if (length == width && length == height)
return("Cube");else return "RectangularSolid";}
}
public class ShapeTest
{private Shape shapes[];
public void createShapes()
{shapes = new Shape[15];
shapes[0] = new Rectangle(3.0, 4.0, 6, 8);
shapes[1] = new Point(7, 11);
shapes[2] = new Circle(3.5, 22, 8);shapes[3] = new Cylinder(10, 3.3, 10, 10);
shapes[4] = new RectangularSolid(2.0, 3.0, 4.0, 6, 8);
shapes[5] = new Point(8, 12);shapes[6] = new Rectangle(2.0, 2.0, 7, 9);
shapes[7] = new Circle(3.6, 23, 9);
shapes[8] = new Cylinder(12, 3.4, 20, 20);shapes[9] = new Rectangle(6.0, 6.0, 5, 7);
shapes[10] = new RectangularSolid(3.0, 3.0, 3.0, 10, 4);
shapes[11] = new Point(9, 13);
shapes[12] = new Circle(3.7, 24, 10);shapes[13] = new Cylinder(14, 3.5, 30, 30);
shapes[14] = new RectangularSolid(4.0, 4.0, 4.0, 8, 9);
}
public void printShapes(){
System.out.println("PRINT THE SHAPES AS AN ARRAY OF SHAPE");
for ( int i = 0; i < shapes.length; i++ ){
System.out.println(shapes[i].getName() + ": " +
shapes[i].toString() + ", ID: " +
shapes[i].getIdNumber());System.out.println("Area = " + shapes[i].area());
System.out.println("Volume = " + shapes[i].volume());
System.out.println();}
7/30/2019 Java 2003
54/103
}
public void insertionSort ()
{for (int index = 1; index < shapes.length; index++)
{
Shape key = shapes[index];int position = index;while (position > 0 && compareShapes(shapes[position-1], key) > 0)
{
shapes[position] = shapes[position-1];position--;
}
shapes[position] = key;}
}
private int compareShapes (Shape s1, Shape s2){
if ((s1.getName()).equals(s2.getName()))
return s1.getIdNumber() - s2.getIdNumber();
else return (s1.getName()).compareTo(s2.getName());}
public static void main (String[] args)
{ShapeTest shapeTest = new ShapeTest();
ShapeTest.createShapes();
ShapeTest.insertionSort();ShapeTest.printShapes();
}}
OUTPUT:
C:\Documents and Settings\Administrator>cd des*
C:\Documents and Settings\Administrator\Desktop>cd C:\Program Files\Java\jdk1.5.
0_03\bin
C:\Program Files\Java\jdk1.5.0_03\bin>javac Shape.java
C:\Program Files\Java\jdk1.5.0_03\bin>javac Point.java
C:\Program Files\Java\jdk1.5.0_03\bin>javac circle.java
C:\Program Files\Java\jdk1.5.0_03\bin>javac Cylinder.java
C:\Program Files\Java\jdk1.5.0_03\bin>javac Rectangle.java
7/30/2019 Java 2003
55/103
C:\Program Files\Java\jdk1.5.0_03\bin>javac RectangularSolid.java
C:\Program Files\Java\jdk1.5.0_03\bin>javac ShapeTest.java
C:\Program Files\Java\jdk1.5.0_03\bin>java ShapeTest
PRINT THE SHAPES AS AN ARRAY OF SHAPECircle: Center = [22, 8]; Radius = 3.5, ID: 3Area = 38.48451000647496
Volume = 0.0
Circle: Center = [23, 9]; Radius = 3.6, ID: 8
Area = 40.71504079052372
Volume = 0.0
Circle: Center = [24, 10]; Radius = 3.7, ID: 13
Area = 43.00840342764427Volume = 0.0
Cube: Center = [10, 4]; Length = 3.0, Width = 3.0; Height = 3.0, ID: 11
Area = 54.0Volume = 27.0
Cube: Center = [8, 9]; Length = 4.0, Width = 4.0; Height = 4.0, ID: 15Area = 96.0
Volume = 64.0
Cylinder: Center = [10, 10]; Radius = 3.3; Height = 10.0, ID: 4
Area = 275.76900313211206
Volume = 342.11943997592846
Cylinder: Center = [20, 20]; Radius = 3.4; Height = 12.0, ID: 9
Area = 328.9875826839231
Volume = 435.8017329059761
Cylinder: Center = [30, 30]; Radius = 3.5; Height = 14.0, ID: 14
Area = 384.84510006474966Volume = 538.7831400906495
Point: [7, 11], ID: 2Area = 0.0
Volume = 0.0
Point: [8, 12], ID: 6Area = 0.0
Volume = 0.0
Point: [9, 13], ID: 12
7/30/2019 Java 2003
56/103
Area = 0.0
Volume = 0.0
Rectangle: Center = [6, 8]; Length = 3.0, Width = 4.0, ID: 1
Area = 12.0
Volume = 0.0
RectangularSolid: Center = [6, 8]; Length = 3.0, Width = 4.0; Height = 2.0, ID:
5
Area = 52.0Volume = 24.0
Square: Center = [7, 9]; Length = 2.0, Width = 2.0, ID: 7Area = 4.0
Volume = 0.0
Square: Center = [5, 7]; Length = 6.0, Width = 6.0, ID: 10
Area = 36.0
Volume = 0.0
RESULT:Thus the program to demonstrate dynamic polymorphism using java was written
and output is achieved.
5 COMPLEX NUMBER
28.7.2010
AIM:To create a java code to get number as input and write itin complex form and find
addition ,subtarction,and multiplication forsuch two complexnumbers.
ALGORITHM:Step 1: Start the program.Step 2: Declare the necessary member variables and member functions.
Step 3: Using getvalue() function get number to write it in complex form.
Step 4: Using addition() function find the sum of two complex numbers by adding the real partof complex number and imaginary part of the complex numbers.
7/30/2019 Java 2003
57/103
Step 5: Similar to addition use subtarction() function,subtract the real part of one with real part
of another complex number and imaginary part of one with imaginary part of another complex
number.Step 6: Using multiplication() function find multiplie of two complex numbers.
Step 7: Print all the function values.
Step 8:Stop the program.
PROGRAM:
public class complexnumber
{private int a;
private int b;
public complexnumber(){
}
public complexnumber(int a,int b)
{this.a=a;
this.b=b;
}public string getcomplexvalue()
7/30/2019 Java 2003
58/103
{
if(this.b
7/30/2019 Java 2003
59/103
{
return a1-b1+"+"+vi+"i";
} }public static void main(String args[])
{
complexnumber com1=new complexnumber(-2,-3);complexnumber com2=new complexnumber(-4,-5);System.out.println(com1.getcomplexvalue());
System.out.println(com2.getcomplexvalue());
System.out.println("addition of 2 nos:"+complexnumber.addition(com1,com2));system.out.println("subtraction of 2 nos:"+complexnumber.subtraction(com1,com2));
system.out.println("multiplication of 2 nos:"+complexnumber.multiplication(com1,com2));
}}
OUTPUT:-2 -3i.
-4 -5i.Addition of both complex number: -6 -8i.
Subtraction of both complex number:2+2i.
Multiplication of both complex number:-7 +22i.
7/30/2019 Java 2003
60/103
RESULT:Thus the program for addition ,subtraction,multiplication of complex numbers using
JAVA has written and the expected output is achieved.
2 STACK ADT 21.7.2010
AIM:
To design a java interface for stack ADT.
ALGORITHM:
Step 1: Start the program
Step 2: create :: Stack acreate an empty stackStep 3: push :: a->Stack a->Stack apush an element on the stack
Step 4: pop :: Stack a->(a.,Stack a)pop an element off the stack
Step 5: empty :: Stack a->Booltells whether stack is emptyStep 6: pop(push x s)=(x,s)
Step 7: pop(create)error
Step 8: The interface to the stack ADT is defined as follows(file=MyStack.java);
Step 9: A simple stack testing class(file=StackTest.java)
7/30/2019 Java 2003
61/103
Step 10:End the program
PROGRAM:import java.io.*;
import java.util.*;class stack
{
static void pushop(Stack s,int a){
s.push(new Integer(a));
System.out.println("Push("+a+")");System.out.println("Stack:"+s);
}
static void popop(Stack s)
{System.out.println("Pop");
Integer a=(Integer)s.pop();
System.out.println("Stack:"+s);
7/30/2019 Java 2003
62/103
}
public static void main(String[] args)
{Scanner in=new Scanner(System.in);
Stack s=new Stack();
System.out.println("Enter the value of n:");int n=in.nextInt();for(int i=0;i
7/30/2019 Java 2003
63/103
Pop
Stack:[2]
PopStack:[]
Pop
Empty stack
RESULT:
Thus java program is written to find stack
1.3 FACTORIAL 6.7.2010
AIM:To write a java program to find factorial of a number.
ALGORITHM:1.Start the program.
2.Get the number from the user.3.Find the factorial of the number using for loop.
4.Print the fatorial value.
5.Stop.
7/30/2019 Java 2003
64/103
PROGRAM:import java.util.*;
class fact{
public static void main(String[] args)
{Int I,sum=1;
Scanner in=new Scanner(System.in);
System.out.,println(Enter the number:);int a=in.nextInt();
for(i=1;i
7/30/2019 Java 2003
65/103
}
OUTPUT:Enter the number:5
The Fatorial is:120
7/30/2019 Java 2003
66/103
RESULT:Thus the program is written to find the factorial of the number.
1.1 FIBONICCI SERIES 6.7.2010
AIM:To write a java program to find the fibonicci series.
ALGORITHM:1.Start the program.
2.Get the number from the user.
3.Find the fibonicci series using the formula f1=f2,f2=sum,sum=f1+f2.4.Print the result.
5.Stop.
7/30/2019 Java 2003
67/103
PROGRAM:import java.util.*;
class fibo{
public static void main(String args[])
{System.out.println(Program to find fibonicci series);
int i,sum=1;
int f1,f2=0;Scanner in=new Scanner(System.in);
System.out.printl;n(Enter the number:);
int a=in.nextInt();
System.out.println(Output);for(i=0;i
7/30/2019 Java 2003
68/103
f2=sum;
sum=f1+f2;
}}
}
OUTPUT:Program to find fibonicci series
Enter the number:15
Output1
1
23
5
813
21
34
5589
144
233
7/30/2019 Java 2003
69/103
377
610
987
RESULT:
Thus the program is written to find fibonicci series.
1.4 ARITHMETIC OPERATION USING 6.7.2010
COMMAND LINE ARGUMENTS
AIM:To write a java program to do arithmetic operation using command line arguments.
ALGORITHM:
1.Start the program.2.Assign values that are given during command line to variables.
3.Perform basic arithmetic operations.
5.Stop
7/30/2019 Java 2003
70/103
PROGRAM:import java.util.*;
class arith{
public static void main(String[] args)
{int a=Integer.parseInt(args[0]);
int b=Integer.parseInt(args[1]);
System.out.println(Addition:+(a+b));
System.out.println(Subtraction:+(a-b));System.out.println(Multiplication:+(a*b));
System.out.println((Division:+(a/b));
System.out.println(Modulo:+(a%b));}
}
7/30/2019 Java 2003
71/103
OUTPUT:D:\java>java arith 4 5
Addition:9
Subtraction:-1Multiplication:20
Division:0
Modulo:4
7/30/2019 Java 2003
72/103
RESULT:
Thus the program is written to do arithmetic operations using command line argument
1.2 PRIME 6.7.2010
AIM:To write java program to find whether given number is prime or not
ALGORITHM:Step 1:Start the program
Step 2:import the necessary classes from util package
Step 3:Get number from the usersStep 4:check whether given no is divisible by other number:
Step 5: If it is divisible then print the no is not prime
Step 6:else print no is primeStep 7:Stop the program
7/30/2019 Java 2003
73/103
PROGRAM:import java .in.*;
import java .util.*;
public static void main(String a[]){
int i,j=1,n;
System.out.println(enter the no);Scanner in=new Scanner (Sytem.in);
n=in.nextInt();
for(i=2;i
7/30/2019 Java 2003
74/103
}
if(n==i)
{System.out.println(prime no);
} } }
OUTPUT:Enter the no
5
Prime noEnter the no
10
Not a prime
7/30/2019 Java 2003
75/103
RESULT:
Thus Java program is written to find prime or not.
15 MULTI-THREADED GUI 23.9.2010
AIM:To develop a multithreaded GUI application.
ALGORITHM:1.Import the required packages.
2.Create class that implements actionlistener and mouse listener.3.Create menus,menuitems,buttons.
4.Add menuitems to menus and buttons to toolbars.
5.Add mouse listener and perform necessary operation.
6.Exit the application.
7/30/2019 Java 2003
76/103
PROGRAM:ChatServer.java
import java.io.*;import java.util.*;
import java.net.*;
import static java.lang.System.out;
public class ChatServer {
Vector users = new Vector();Vector clients = new Vector();
public void process() throws Exception {ServerSocket server = new ServerSocket(9999,10);
out.println("Server Started...");
while( true) {
Socket client = server.accept();
7/30/2019 Java 2003
77/103
HandleClient c = new HandleClient(client);
clients.add(c);
} // end of while}
public static void main(String ... args) throws Exception {
new ChatServer().process();} // end of main
public void boradcast(String user, String message) {
// send message to all connected usersfor ( HandleClient c : clients )
if ( ! c.getUserName().equals(user) )
c.sendMessage(user,message);}
class HandleClient extends Thread {String name = "";
BufferedReader input;
PrintWriter output;
public HandleClient(Socket client) throws Exception {
// get input and output streams
input = new BufferedReader( new InputStreamReader( client.getInputStream())) ;output = new PrintWriter ( client.getOutputStream(),true);
// read name
name = input.readLine();users.add(name); // add to vector
start();
}
public void sendMessage(String uname,String msg) {
output.println( uname + ":" + msg);
}
public String getUserName() {
return name;}
public void run() {
String line;try {
while(true) {
line = input.readLine();
if ( line.equals("end") ) {clients.remove(this);
users.remove(name);
break;}
7/30/2019 Java 2003
78/103
boradcast(name,line); // method of outer class - send messages to all
} // end of while
} // trycatch(Exception ex) {
System.out.println(ex.getMessage());
}} // end of run()} // end of inner class
} // end of Server
ChatClient.java
import java.io.*;import java.util.*;
import java.net.*;
import javax.swing.*;
import java.awt.*;import java.awt.event.*;
import static java.lang.System.out;
public class ChatClient extends JFrame implements ActionListener {
String uname;
PrintWriter pw;BufferedReader br;
JTextArea taMessages;
JTextField tfInput;
JButton btnSend,btnExit;Socket client;
public ChatClient(String uname,String servername) throws Exception {super(uname); // set title for frame
this.uname = uname;
client = new Socket(servername,9999);br = new BufferedReader( new InputStreamReader( client.getInputStream()) ) ;
pw = new PrintWriter(client.getOutputStream(),true);
pw.println(uname); // send name to serverbuildInterface();
new MessagesThread().start(); // create thread for listening for messages
}
public void buildInterface() {
btnSend = new JButton("Send");
btnExit = new JButton("Exit");taMessages = new JTextArea();
7/30/2019 Java 2003
79/103
taMessages.setRows(10);
taMessages.setColumns(50);
taMessages.setEditable(false);tfInput = new JTextField(50);
JScrollPane sp = new JScrollPane(taMessages,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);add(sp,"Center");
JPanel bp = new JPanel( new FlowLayout());
bp.add(tfInput);bp.add(btnSend);
bp.add(btnExit);
add(bp,"South");btnSend.addActionListener(this);
btnExit.addActionListener(this);
setSize(500,300);setVisible(true);
pack();
}
public void actionPerformed(ActionEvent evt) {
if ( evt.getSource() == btnExit ) {
pw.println("end"); // send end to server so that server know about the terminationSystem.exit(0);
} else {
// send message to serverpw.println(tfInput.getText());
}
}
public static void main(String args[]) {
// take username from userString name = JOptionPane.showInputDialog(null,"Enter your name :", "Username",
JOptionPane.PLAIN_MESSAGE);
String servername = "localhost";try {
new ChatClient( name ,servername);
} catch(Exception ex) {out.println( "Error --> " + ex.getMessage());
}
} // end of main
// inner class for Messages Thread
class MessagesThread extends Thread {public void run() {
7/30/2019 Java 2003
80/103
String line;
try {
while(true) {line = br.readLine();
taMessages.append(line + "\n");
} // end of while} catch(Exception ex) {}}
}
} // end of client
OUTPUT:
7/30/2019 Java 2003
81/103
RESULT:Thus the program is written to implement multi-threaded GUI.
9 INTERFACE FOR STACK ADT 18.8.2010
AIM:
To design a java interface for stack ADT.
ALGORITHM:
Step 1: Start the programStep 2: create :: Stack acreate an empty stack
Step 3: push :: a->Stack a->Stack apush an element on the stack
Step 4: pop :: Stack a->(a.,Stack a)pop an element off the stackStep 5: empty :: Stack a->Booltells whether stack is empty
Step 6: pop(push x s)=(x,s)
Step 7: pop(create)errorStep 8: The interface to the stack ADT is defined as follows(file=MyStack.java);
Step 9: A simple stack testing class(file=StackTest.java)
Step 10:End the program
7/30/2019 Java 2003
82/103
PROGRAM:
import java.util.*;
interface adt
{
public void push(int c);
public int pop();public boolean isempty();
public boolean isfull();
public void display();}
class st implements adt{
int top;
int [] st=new int[20];
st(){
top=-1;
}
7/30/2019 Java 2003
83/103
public boolean isempty()
{return(top==-1);
}
public boolean isfull(){
return(top>=20);
}
public void push(int c)
{if(isfull())
{
System.out.println("STACK IS FULL");}
else
{
top++;st[top]=c;
}
}
public int pop()
{if(isempty())
{
System.out.println("STACK IS EMPTY");
return 0;}
else
{int c=st[top];
top--;
return c;}
}
public void display()
{
if(isempty())
{System.out.println("STACK IS EMPTY");
}
else{
7/30/2019 Java 2003
84/103
7/30/2019 Java 2003
85/103
}while(choice
7/30/2019 Java 2003
86/103
ENTER UR CHOICE:
2
THE POPPED CHARECTER IS:561.PUSH 2.POP 3. DISPLAY 4. EXIT
ENTER UR CHOICE:
2STACK IS EMPTY1.PUSH 2.POP 3. DISPLAY 4. EXIT
ENTER UR CHOICE:
3STACK IS EMPTY
1.PUSH 2.POP 3. DISPLAY 4. EXIT
ENTER UR CHOICE:4
OUTPUT 2:1.PUSH 2.POP 3. DISPLAY 4. EXIT
ENTER UR CHOICE:1
ENTER AN INTEGER TO PUSH:
WInteger values only allowed : java.util.InputMismatchException
1.PUSH 2.POP 3. DISPLAY 4. EXIT
ENTER UR CHOICE:4
7/30/2019 Java 2003
87/103
RESULT:Thus the program for stack ADT using java interface was written and expected output is
achieved.
7/30/2019 Java 2003
88/103
7 PRINTING CURRENT DATE AND TIME 11.8.2010
AIM:To write a java program to print current date and time.
ALGORITHM:Step 1:Start the program.Step 2:Create an object for date foramt class.
Step 3:From the string of months get the instance.
Step 3:Print the current date,time.
Step 4:Stop.
7/30/2019 Java 2003
89/103
PROGRAM:import java.util.Calendar;import java.util.Date;
import java.text.SimpleDateFormat;
class DateCalendar {
public static void main(String args[]) {
System.out.println("Display current date and time using Date class>>> ");
Date d = new Date();SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
String formattedDate = formatter.format(d);
System.out.println("Today's date and Time is:"+d);String months[] = {
"Jan", "Feb", "Mar", "Apr",
"May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec"};Calendar calendar = Calendar.getInstance();
System.out.println("Display current date and time using Calendar class>>>> ");
System.out.print("Date: ");System.out.print(months[calendar.get(Calendar.MONTH)]);
System.out.print(" " + calendar.get(Calendar.DATE) + " ");
System.out.println(calendar.get(Calendar.YEAR));System.out.print("Time: ");
System.out.print(calendar.get(Calendar.HOUR) + ":");
System.out.print(calendar.get(Calendar.MINUTE) + ":");System.out.println(calendar.get(Calendar.SECOND));
}}
7/30/2019 Java 2003
90/103
OUTPUT:
Display current date and time using Date class>>>
Today's date and Time is:Sun Sep 26 09:19:30 IST 2010
Display current date and time using Calendar class>>>>Date: Sep 26 2010
Time: 9:19:30
RESULT:
7/30/2019 Java 2003
91/103
Thus the program is written to print current date and time.3 STACK USING LINKED LIST 21.7.2010
AIM:
To implement stack using linked list.
ALGORITHM:Step 1:Start the program.Step 2:Initialize head and tail as null.
Step 3:Define a method to insert into the head of the stack.
Step 4:Define a method to retrieve top element of the stack.Step 6:Based on user input do necessary operation.
Step 7:Close the program.
7/30/2019 Java 2003
92/103
PROGRAM:class Link{
public Object data;
public Link next;public Link(Object d, Link n)
{
data = d; next = n;
}}
//LINKEDLIST CLASS AND MAIN
import java.util.Scanner;
class LinkList
{
private Link head; // reference to first Link
private Link tail; // reference to last Link
private int size;
public LinkList(){
tail = null;head = null;
}
public Object peekHead() // return reference to first Object
{
return head.data;}
public Object peekTail() // return reference to last Object{
return tail.data;
}//THE ADD METHOD, NOT SURE IF DONE RIGHT
public void addHead(Object newData)
{
if (head == null){
head = new Link(newData, tail);
7/30/2019 Java 2003
93/103
7/30/2019 Java 2003
94/103
System.out.println("What would you like to do? (enter the number)");
System.out.println("1 - Push onto Head of Stack.");
System.out.println("2 - Remove from Head of Stack.");System.out.println("3 - Peek at Head of Stack.");
System.out.println("4 - Push at Tail of Stack.");
System.out.println("5 - Peak at Tail of Stack.");System.out.println("6 - Close Program.");choice = scan.nextInt();
switch(choice)
{
case 1:System.out.println("What do you want to push on Head?");
Object pushingHead = scan.next();
first.addHead(pushingHead);
break;
case 2:System.out.println("Removing: " + first.removeHead());
break;
case 3:
System.out.println("Peeking at Head of Stack: " + first.peekHead());
break;
case 4:
System.out.println("What do you want to push on Tail?");
Object pushingTail = scan.next();
first.addHead(pushingTail);
break;
case 5:
System.out.println("Peeking at Tail of Stack: " + first.peekTail());break;
case 6:System.out.println("Good Bye!");
break;
}
}
}
}
7/30/2019 Java 2003
95/103
OUTPUT:What would you like to do? (enter the number)
1 - Push onto Head of Stack.2 - Remove from Head of Stack.
3 - Peek at Head of Stack.
4 - Push at Tail of Stack.5 - Peak at Tail of Stack.
6 - Close Program.
1
What do you want to push on Head?12
What would you like to do? (enter the number)
1 - Push onto Head of Stack.2 - Remove from Head of Stack.
3 - Peek at Head of Stack.
4 - Push at Tail of Stack.
5 - Peak at Tail of Stack.6 - Close Program.
3
Peeking at Head of Stack: 12What would you like to do? (enter the number)
1 - Push onto Head of Stack.
2 - Remove from Head of Stack.3 - Peek at Head of Stack.
4 - Push at Tail of Stack.
5 - Peak at Tail of Stack.6 - Close Program.
4What do you want to push on Tail?23
What would you like to do? (enter the number)
1 - Push onto Head of Stack.
2 - Remove from Head of Stack.3 - Peek at Head of Stack.
4 - Push at Tail of Stack.
5 - Peak at Tail of Stack.6 - Close Program.
5
Peeking at Tail of Stack: 12What would you like to do? (enter the number)
1 - Push onto Head of Stack.
2 - Remove from Head of Stack.
3 - Peek at Head of Stack.4 - Push at Tail of Stack.
5 - Peak at Tail of Stack.
6 - Close Program.
7/30/2019 Java 2003
96/103
2
Removing: 23
What would you like to do? (enter the number)1 - Push onto Head of Stack.
2 - Remove from Head of Stack.
3 - Peek at Head of Stack.4 - Push at Tail of Stack.5 - Peak at Tail of Stack.
6 - Close Program.
RESULT:Thus the program is written to implement stack using linked list.
7/30/2019 Java 2003
97/103
7/30/2019 Java 2003
98/103
PROGRAM:
class Queue
{
private int maxSize;private long[] queArray;
private int front;
private int rear;
private int nItems;
public Queue(int s) // constructor
{maxSize = s;
queArray = new long[maxSize];
front = 0;
rear = -1;nItems = 0;
}
public void insert(long j) // put item at rear of queue
{
if(rear == maxSize-1) // deal with wraparoundrear = -1;
queArray[++rear] = j; // increment rear and insert
nItems++; // one more item}
public long remove() // take item from front of queue{
long temp = queArray[front++]; // get value and incr front
if(front == maxSize) // deal with wraparound
front = 0;nItems--; // one less item
return temp;
}
public long peekFront() // peek at front of queue
{return queArray[front];
}
public boolean isEmpty() // true if queue is empty{
return (nItems==0);
}
7/30/2019 Java 2003
99/103
public boolean isFull() // true if queue is full
{return (nItems==maxSize);
}
public int size() // number of items in queue{
return nItems;
}
}
class QueueApp{
public static void main(String[] args)
{Queue theQueue = new Queue(5); // queue holds 5 items
theQueue.insert(10); // insert 4 items
theQueue.insert(20);
theQueue.insert(30);theQueue.insert(40);
theQueue.remove(); // remove 3 items
theQueue.remove(); // (10, 20, 30)theQueue.remove();
theQueue.insert(50); // insert 4 more items
theQueue.insert(60); // (wraps around)theQueue.insert(70);
theQueue.insert(80);
while( !theQueue.isEmpty() ) // remove and display
{long n = theQueue.remove(); // (40, 50, 60, 70, 80)
System.out.print(n);
System.out.print(" ");}
System.out.println(" ");
}}
7/30/2019 Java 2003
100/103
OUTPUT:
40 50 60 70 80
RESULT:Thus the program is written to implement queue.
7/30/2019 Java 2003
101/103
6 READ FILE CONTENT 11.8.2010
AIM:
To develop a java program that reads file content and prints no of chars, lines, words,vowels.
ALGORITHM:Step 1: Declare the class DateCalender
Step 2:Inside class declare void main
Step 3: Declare integer variablesStep 4:using getchar get size ,length,buffer,starting location
Step 5:using for loop get check for vowels
Step 6:using object f1 write char to buffer
Step 7:read the content writtenStep 8: stop the program
7/30/2019 Java 2003
102/103
PROGRAM:import java.io.*;
class DateCalendar{
public static void main(String args[])throws Exception
{int i,l=0,w=0,vow=0;
String s="it is java program"+"\nplatform independent";
char buffer[]=new char[s.length()];
s.getChars(0,s.length(),buffer,0);System.out.println("no of characters="+s.length());
for(i=0;i
7/30/2019 Java 2003
103/103
OUTPUT:no of characters=39
no of words:5no of vowels:12
no of lines2