SwitchTest.java
// Fig. 5.7: SwitchTest.java
// Drawing lines, rectangles or ovals based on user input.
import java.awt.Graphics;
import javax.swing.*;
public class SwitchTest extends JApplet {
int choice; // user's choice of which shape to draw
// initialize applet by obtaining user's choice
public void init()
{
String input; // user's input
// obtain user's choice
input = JOptionPane.showInputDialog(
"Enter 1 to draw lines\n" +
"Enter 2 to draw rectangles\n" +
"Enter 3 to draw ovals\n" );
choice = Integer.parseInt( input ); // convert input to int
} // end method init
// draw shapes on applet's background
public void paint( Graphics g )
{
super.paint( g ); // call paint method inherited from JApplet
for ( int i = 0; i < 10; i++ ) { // loop 10 times (0-9)
switch ( choice ) { // determine shape to draw
case 1: // draw a line
g.drawLine( 10, 10, 250, 10 + i * 10 );
break; // done processing case
case 2: // draw a rectangle
g.drawRect( 10 + i * 10, 10 + i * 10,
50 + i * 10, 50 + i * 10 );
break; // done processing case
case 3: // draw an oval
g.drawOval( 10 + i * 10, 10 + i * 10,
50 + i * 10, 50 + i * 10 );
break; // done processing case
default: // draw string indicating invalid value entered
g.drawString( "Invalid value entered",
10, 20 + i * 15 );
} // end switch
} // end for
} // end method paint
} // end class SwitchTest
method defination
public abstract void drawLine(int x1,int y1,int x2,int y2)
method invocation
g.drawLine(10, 10, 250, counter * 10);
return type,
parameters, and
arguments
public abstract void drawLine(int x1,int y1,int x2,int y2)
g.drawLine(10, 10, 250, counter * 10);
Quiz
Find all classes and methods in the following program .
// Fig. 5.6: Interest.java
// Calculating compound interest.
import java.text.NumberFormat; // class for numeric formatting
import java.util.Locale; // class for country-specific information
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
public class Interest {
public static void main( String args[] )
{
double amount; // amount on deposit at end of each year
double principal = 1000.0; // initial amount before interest
double rate = 0.05; // interest rate
// create NumberFormat for currency in US dollar format
NumberFormat moneyFormat =
NumberFormat.getCurrencyInstance( Locale.US );
// create JTextArea to display output
JTextArea outputTextArea = new JTextArea();
// set first line of text in outputTextArea
outputTextArea.setText( "Year\tAmount on deposit\n" );
// calculate amount on deposit for each of ten years
for ( int year = 1; year <= 10; year++ ) {
// calculate new amount for specified year
amount = principal * Math.pow( 1.0 + rate, year );
// append one line of text to outputTextArea
outputTextArea.append( year + "\t" +
moneyFormat.format( amount ) + "\n" );
} // end for
// display results
JOptionPane.showMessageDialog( null, outputTextArea,
"Compound Interest", JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 ); // terminate the application
} // end main
} // end class Interest