Showing posts with label Java Programming. Show all posts
Showing posts with label Java Programming. Show all posts

Draw Panel - Java Sample Program

//  DrawPanel.java
//  Using drawLine to connect the corners of a panel.
import java.awt.Graphics; 
import javax.swing.JPanel;

public class DrawPanel extends JPanel
{
   // draws an X from the corners of the panel
   public void paintComponent( Graphics g )
   {
      // call paintComponent to ensure the panel displays correctly
      super.paintComponent( g );
      
      int width = getWidth(); // total width   
      int height = getHeight(); // total height

      // draw a line from the upper-left to the lower-right
      g.drawLine( 0, 0, width, height );
      
      // draw a line from the lower-left to the upper-right
      g.drawLine( 0, height, width, 0 );
   } // end method paintComponent
} // end class DrawPanel


// DrawPanelTest.java
// Application to display a DrawPanel.
import javax.swing.JFrame;

public class DrawPanelTest
{
   public static void main( String[] args )
   {
      // create a panel that contains our drawing
      DrawPanel panel = new DrawPanel();
      
      // create a new frame to hold the panel
      JFrame application = new JFrame();
      
      // set the frame to exit when it is closed
      application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

      application.add( panel ); // add the panel to the frame      
      application.setSize( 250, 250 ); // set the size of the frame
      application.setVisible( true ); // make the frame visible    
   } // end main
} // end class DrawPanelTest


Drawing Animation - Java Sample Program

//file: Hypnosis.java
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.GeneralPath;
import javax.swing.*;

public class Hypnosis extends JComponent implements Runnable {

private int[] coordinates;
private int[] deltas;
private Paint paint;

public Hypnosis(int numberOfSegments) {

int numberOfCoordinates = numberOfSegments * 4 + 2;
coordinates = new int[numberOfCoordinates];
deltas = new int[numberOfCoordinates];

for (int i = 0 ; i < numberOfCoordinates; i++) {
coordinates[i] = (int)(Math.random() * 300);
deltas[i] = (int)(Math.random() * 4 + 3);

if (deltas[i] > 4) deltas[i] = -(deltas[i] - 3);
}

paint = new GradientPaint(0, 0, Color.BLUE, 20, 10, Color.RED, true);
Thread t = new Thread(this);
t.start();
}
public void run() {
try {
while (true) {
timeStep();
repaint();
Thread.sleep(1000 / 24);
}
}
catch (InterruptedException ie) {}
}

public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
Shape s = createShape();

g2.setPaint(paint);
g2.fill(s);
g2.setPaint(Color.WHITE);
g2.draw(s);
}
private void timeStep() {
Dimension d = getSize();

if (d.width == 0 || d.height == 0) return;

for (int i = 0; i < coordinates.length; i++) {
coordinates[i] += deltas[i];
int limit = (i % 2 == 0) ? d.width : d.height;

if (coordinates[i] < 0) {
coordinates[i] = 0;
deltas[i] = -deltas[i];
}
else if (coordinates[i] > limit) {
coordinates[i] = limit - 1;
deltas[i] = -deltas[i];
}
}
}

private Shape createShape() {
GeneralPath path = new GeneralPath();
path.moveTo(coordinates[0], coordinates[1]);
for (int i = 2; i < coordinates.length; i += 4)
path.quadTo(coordinates[i], coordinates[i + 1], coordinates[i + 2], coordinates[i + 3]);
path.closePath();
return path;
}

public static void main(String[] args) {
JFrame frame = new JFrame("Hypnosis");
frame.add( new Hypnosis(4) );
frame.setSize(300, 300);
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setVisible(true);
}
}


Sample Output:

Media Tracker - Java Sample Program

//The following code snippet illustrates how to use a MediaTracker to wait while an image is prepared:
//file: StatusImage.java

import java.awt.*;
import javax.swing.*;

public class StatusImage extends JComponent
{
boolean loaded = false;
String message = "Loading...";
Image image;

public StatusImage( Image image ) { this.image = image; }

public void paint(Graphics g) {

if (loaded)
g.drawImage(image, 0, 0, this);
else {
g.drawRect(0, 0, getSize().width - 1, getSize().height - 1);
g.drawString(message, 20, 20);
}
}

public void loaded() {
loaded = true;
repaint();
}

public void setMessage( String msg ) {
message = msg;
repaint();
}

public static void main( String [] args ) {
JFrame frame = new JFrame("TrackImage");
Image image = Toolkit.getDefaultToolkit().getImage( args[0] );
StatusImage statusImage = new StatusImage( image );

frame.add( statusImage );
frame.setSize(300,300);
frame.setVisible(true);

MediaTracker tracker = new MediaTracker( statusImage );

int MAIN_IMAGE = 0;

tracker.addImage( image, MAIN_IMAGE );

try {
tracker.waitForID( MAIN_IMAGE ); }
catch (InterruptedException e) {}
if ( tracker.isErrorID( MAIN_IMAGE ) )
statusImage.setMessage( "Error" );
else
statusImage.loaded();
}
}

ImageObserver Interface - Loading Image - Java Sample Program

//file: ObserveImageLoad.java

import java.awt.*;
import java.awt.image.*;

public class ObserveImageLoad {
public static void main( String [] args)
{
ImageObserver myObserver = new ImageObserver() {
public boolean imageUpdate( Image image, int flags, int x, int y, int width, int height)
{
if ( (flags & HEIGHT) !=0 )
System.out.println("Image height = " + height );

if ( (flags & WIDTH ) !=0 )
System.out.println("Image width = " + width );

if ( (flags & FRAMEBITS) != 0 )
System.out.println("Another frame finished.");

if ( (flags & SOMEBITS) != 0 )
System.out.println("Image section :" + new Rectangle( x, y, width, height ) );

if ( (flags & ALLBITS) != 0 )
System.out.println("Image finished!");

if ( (flags & ABORT) != 0 )
System.out.println("Image load aborted...");

return true;
}
};

Toolkit toolkit = Toolkit.getDefaultToolkit();
Image img = toolkit.getImage( args[0] );

toolkit.prepareImage( img, -1, -1, myObserver );
}
}

Circle (User Define Classes) - Java Sample Program

public class Circle
{
private double radius;

//Default constructor
//Sets the radius to 0
Circle()
{
radius = 0;
}

//Constructor with a parameter
//Sets the radius to the value specified by the parameter r.
Circle(double r)
{
radius = r;
}

//Method to set the radius of the circle.
//Sets the radius to the value specified by the parameter r.
public void setRadius(double r)
{
radius = r;
}

//Method to return the radius of the circle.
//Returns the radius of the circle.
public double getRadius()
{
return radius;
}

//Method to compute and return the area of the circle.
//Computes and returns the area of the circle.
public double area()
{
return Math.PI * Math.PI * radius;
}

//Method to compute and return the perimeter of the circle.
//Computes and returns the area of the circle.
public double perimeter()
{
return 2 * Math.PI * radius;
}

//Method to return the radius, area, perimeter of the circle
//as a string.
public String toString()
{
return String.format("Radius = %.2f, Perimeter = %.2f"+ ", Area = %.2f%n", radius, perimeter(), area());
}
}


We leave the UML class diagram of the class Circle as an exercise for you.
The following program shows how to use the class Circle in a program.
// Program to test various operations of the class Circle.

import java.util.*; //Line 1
public class TestProgCircle //Line 2
{ //Line 3

static Scanner console = new Scanner(System.in); //Line 4

public static void main(String[] args) //Line 5
{ //Line 6

Circle firstCircle = new Circle(); //Line 7
Circle secondCircle = new Circle(12); //Line 8

double radius; //Line 9

System.out.println("Line 10: firstCircle: " + firstCircle); //Line 10

System.out.println("Line 11: secondCircle: " + secondCircle); //Line 11

System.out.print("Line 12: Enter the radius: "); //Line 12

radius = console.nextDouble(); //Line 13

System.out.println(); //Line 14

firstCircle.setRadius(radius); //Line 15

System.out.println("Line 16: firstCircle: " + firstCircle ); //Line 16

if (firstCircle.getRadius() > secondCircle.getRadius()) //Line 17
System.out.println("Line 18: The radius of "+ "the first circle is greater than "+ "the radius of the second circle. "); //Line 18
else if (firstCircle.getRadius()< secondCircle.getRadius()) //Line 19
System.out.println("Line 20: The radius of "+ "the first circle is less than the " + "radius of the second circle. "); //Line 20
else //Line 21
System.out.println("Line 22: The radius of " + "both the circles are the same."); //Line 22
}//end main //Line 23
} //Line 24

Sample Sample Output:

Line 10: firstCircle: Radius = 0.00, Perimeter = 0.00, Area = 0.00
Line 11: secondCircle: Radius = 12.00, Perimeter = 75.40, Area = 118.44
Line 12: Enter the radius: 10
Line 16: firstCircle: Radius = 10.00, Perimeter = 62.83, Area = 98.70
Line 20: The radius of the first circle is less than the radius of the second circle.

The preceding program works as follows. The statement in Line 7 creates the object
firstCircle and using the default constructor sets the radius to 0. The statement in
Line 8 creates the object secondCircle and sets the radius to 12. The statement in Line
9 declares the double variable radius. The statement in Line 10 outputs the radius, area,
and perimeter of the firstCircle. Similarly, the statement in Line 11 outputs the
radius, area, and perimeter of the secondCircle The statement in Line 12 prompts the
user to enter the value of radius. The statement in Line 13 stores the value entered by
the user in the variable radius. The statement in Line 15 uses the value of radius to set
the radius of firstCircle. The statement in Line 16 outputs the radius, area, and
perimeter of the firstCircle. The statements in Lines 17 to 23 compare the radius of
firstCircle and secondCircle and output the appropriate result.

Clock (User Define Classes) - Java Sample Program

//The definition of the class Clock is:

public class Clock
{
private int hr; //store hours
private int min; //store minutes
private int sec; //store seconds

//Default constructor
//Postcondition: hr = 0; min = 0; sec = 0
public Clock()
{
setTime(0, 0, 0);
}

//Constructor with parameters, to set the time
//The time is set according to the parameters.
//Postcondition: hr = hours; min = minutes;
// sec = seconds
public Clock(int hours, int minutes, int seconds)
{
setTime(hours, minutes, seconds);
}

//Method to set the time
//The time is set according to the parameters.
//Postcondition: hr = hours; min = minutes;
// sec = seconds
public void setTime(int hours, int minutes, int seconds)
{
if (0 <= hours && hours < 24)
hr = hours;
else
hr = 0;

if (0 <= minutes && minutes < 60)
min = minutes;
else
min = 0;

if (0 <= seconds && seconds < 60)
sec = seconds;
else
sec = 0;
}

//Method to return the hours
//Postcondition: the value of hr is returned
public int getHours()
{
return hr;
}

//Method to return the minutes
//Postcondition: the value of min is returned
public int getMinutes()
{
return min;
}

//Method to return the seconds
//Postcondition: the value of sec is returned
public int getSeconds()
{
return sec;
}

//Method to print the time
//Postcondition: Time is printed in the form hh:mm:ss
public void printTime()
{
if (hr < 10)
System.out.print("0");
System.out.print(hr + ":");

if (min < 10)
System.out.print("0");
System.out.print(min + ":");

if (sec < 10)
System.out.print("0");
System.out.print(sec);
}

//Method to increment the time by one second
//Postcondition: The time is incremented by one second
//If the before-increment time is 23:59:59, the time
//is reset to 00:00:00
public void incrementSeconds()
{
sec++;

if (sec > 59)
{
sec = 0;
incrementMinutes(); //increment minutes
}
}

//Method to increment the time by one minute
//Postcondition: The time is incremented by one minute
//If the before-increment time is 23:59:53, the time
//is reset to 00:00:53
public void incrementMinutes()
{
min++;

if (min > 59)
{
min = 0;
incrementHours(); //increment hours
}
}

//Method to increment the time by one hour
//Postcondition: The time is incremented by one hour
//If the before-increment time is 23:45:53, the time
//is reset to 00:45:53
public void incrementHours()
{
hr++;

if (hr > 23)
hr = 0;
}

//Method to compare two times
//Postcondition: Returns true if this time is equal to
// otherClock; otherwise returns false
public boolean equals(Clock otherClock)
{
return (hr == otherClock.hr
&& min == otherClock.min
&& sec == otherClock.sec);
}

//Method to copy time
//Postcondition: The instance variables of otherClock
// copied into the corresponding data
// are members of this time.
// hr = otherClock.hr;
// min = otherClock.min;
// sec = otherClock.sec;
public void makeCopy(Clock otherClock)
{
hr = otherClock.hr;
min = otherClock.min;
sec = otherClock.sec;
}

//Method to return a copy of time
//Postcondition: A copy of the object is created and
// a reference of the copy is returned
public Clock getCopy()
{
Clock temp = new Clock();
temp.hr = hr;
temp.min = min;
temp.sec = sec;
return temp;
}
}


//Program to test various operations of the class Clock
import java.util.*;
public class TestProgClock
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
Clock myClock = new Clock(5, 4, 30); //Line 1
Clock yourClock = new Clock(); //Line 2

int hours; //Line 3
int minutes; //Line 4
int seconds; //Line 5

System.out.print("Line 6: myClock: "); //Line 6
myClock.printTime(); //Line 7

System.out.println(); //Line 8
System.out.print("Line 9: yourClock: "); //Line 9
yourClock.printTime(); //Line 10

System.out.println(); //Line 11
yourClock.setTime(5, 45, 16); //Line 12

System.out.print("Line 13: After setting "+ "the time - yourClock: "); //Line 13
yourClock.printTime(); //Line 14
System.out.println(); //Line 15

if (myClock.equals(yourClock)) //Line 16
System.out.println("Line 17: Both the " + "times are equal."); //Line 17
else //Line 18
System.out.println("Line 19: The two " + "times are not " + "equal."); //Line 19

System.out.print("Line 20: Enter hours, "+ "minutes, and seconds: "); //Line 20

hours = console.nextInt(); //Line 21
minutes = console.nextInt(); //Line 22
seconds = console.nextInt(); //Line 23
System.out.println(); //Line 24

myClock.setTime(hours, minutes, seconds); //Line 25

System.out.print("Line 26: New time of "+ "myClock: "); //Line 26
myClock.printTime(); //Line 27

System.out.println(); //Line 28
myClock.incrementSeconds(); //Line 29

System.out.print("Line 30: After "+ "incrementing the time by " + "one second, myClock: "); //Line 30

myClock.printTime(); //Line 31
System.out.println(); //Line 32

yourClock.makeCopy(myClock); //Line 33

System.out.print("Line 34: After copying "+ "myClock into yourClock, " + "yourClock: "); //Line 34

yourClock.printTime(); //Line 35

System.out.println(); //Line 36
}//end main
}
Sample Output:

Line 6: myClock: 05:04:30
Line 9: yourClock: 00:00:00
Line 13: After setting the time - yourClock: 05:45:16
Line 19: The two times are not equal.
Line 20: Enter hours, minutes, and seconds: 11 22 59
Line 26: New time of myClock: 11:22:59
Line 30: After incrementing the time by one second, myClock: 11:23:00
Line 34: After copying myClock into yourClock, yourClock: 11:23:00

Triangle of Stars - Void Method - Java Sample Program

// Program: Print a triangle of stars
// Given the number of lines, this program prints a triangle of stars.

import java.util.*;
public class TriangleOfStars
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
int numberOfLines;
int numberOfBlanks;
int counter = 1;

System.out.print("Enter the number of star lines " + "(1 to 20) to be printed: ");

numberOfLines = console.nextInt();

System.out.println();

while (numberOfLines < 0 || numberOfLines > 20)
{
System.out.println("The number of star lines should " + "be between 1 and 20");
System.out.print("Enter the number of star lines " + "(1 to 20) to be printed: ");

numberOfLines = console.nextInt();

System.out.println ();
}

numberOfBlanks = 30;
for (counter = 1; counter <= numberOfLines; counter++)
{
printStars(numberOfBlanks, counter);
numberOfBlanks--;
}
} // end main

public static void printStars(int blanks, int starsInLine)
{
int count = 1;

for (count = 1; count <= blanks; count++)
System.out.print(" ");

for (count = 1; count <= starsInLine; count++)
System.out.print(" *");

System.out.println();
} //end printStars
}

Sample Output:

Enter the number of star lines (1 to 20) to be printed: 10
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *

In the method main, the user is first asked to specify how many lines of stars to print. (In
this program, the user is restricted to 20 lines because a triangular grid of up to 20 lines fits
nicely on the screen.) Because the program is restricted to only 20 lines, the while loop
in the method main ensures that the program prints the triangular grid of stars only if the
number of lines is between 1 and 20.

Largest Number (Revised) - Java Sample Program

// Program: Largest number
// This program determines the largest number of a set of 10 numbers.

import java.util.*;
public class LargestNumber
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
double num; //variable to hold the current number
double max; //variable to hold the larger number

int count; //loop control variable

System.out.println("Enter 10 numbers:");
num = console.nextDouble(); //Step 1
max = num; //Step 1

for (count = 1; count < 10; count++) //Step 2
{
num = console.nextDouble(); //Step 2a
max = larger(max, num); //Step 2b
}

System.out.println("The largest number is " + max); //Step 3
}

public static double larger(double x, double y)
{
double max;

if (x >= y)
max = x;
else
max = y;
return max;
}
}

Sample Output:

Enter 10 numbers:
10.5 56.34 73.3 42 22 67 88.55 26 62 11
The largest number is 88.55

Larger Number Using Methods - Java Sample Program

//The following program uses the method larger and main to determine the larger of two numbers:
//Program: Larger of two numbers

import java.util.*;
public class LargerNumber
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
double num1; //Line 1
double num2; //Line 2

System.out.println("Line 3: The larger of " + "5.6 and 10.8 is " + larger(5.6, 10.8)); //Line 3
System.out.print("Line 4: Enter two " + "numbers: "); //Line 4

num1 = console.nextDouble(); //Line 5
num2 = console.nextDouble(); //Line 6

System.out.println(); //Line 7
System.out.println("Line 8: The larger of " + num1 + " and " + num2 + " is "+ larger(num1, num2)); //Line 8
}

public static double larger(double x, double y)
{
double max;
if (x >= y)
max = x;
else
max = y;
return max;
}
}

Sample Output:

Line 3: The larger of 5.6 and 10.8 is 10.8
Line 4: Enter two numbers: 34 43
Line 8: The larger of 34.0 and 43.0 is 43.0

Predefined Methods - Java Sample Program

//How to use the predefined methods
import static java.lang.Math.*;
import static java.lang.Character.*;

public class PredefinedMethods
{
public static void main(String[] args)
{
int x;
double u;
double v;

System.out.println("Line 1: Uppercase a is " + toUpperCase('a')); //Line 1

u = 4.2; //Line 2
v = 3.0; //Line 3

System.out.printf("Line 4: %.1f to the power " + "of %.1f = %.2f%n", u, v, pow(u, v)); //Line 4
System.out.printf("Line 5: 5 to the power of " + "4 = %.2f%n", pow(5, 4)); //Line 5

u = u + Math.pow(3, 3); //Line 6

System.out.printf("Line 7: u = %.2f%n", u); //Line 7

x = -15; //Line 8

System.out.printf("Line 9: The absolute value " + "of %d = %d%n", x, abs(x)); //Line 9
}
}


Sample Output:
Line 1: Uppercase a is A
Line 4: 4.2 to the power of 3.0 = 74.09
Line 5: 5 to the power of 4 = 625.00
Line 7: u = 31.20
Line 9: The absolute value of -15 = 15

This program works as follows: The statement in Line 1 outputs the uppercase letter that
corresponds to 'a', which is 'A'. In the statement in Line 4, themethod pow (of the class
Math) is used to output uv. In Java terminology, it is said that the method pow is called with the
(actual) parameters u and v. In this case, the values of u and v are passed to the method pow.

The statement in Line 5 uses the method pow to output 54. The statement in Line 6 uses the method
pow to determine 33, adds this value to the value of u, and then stores the new value into u.
Notice that in this statement, the method pow is called using the name of the class, which is
Math, and the dot operator. The statement in Line 7 outputs the value of u. The statement in
Line 8 stores -15 into x, and the statement in Line 9 outputs the absolute value of x.

Predefined Methods Class Character - Java Sample Program

class Character (Package: java.lang)

Example:

isLowerCase(ch)
ch is of type char. Returns true, if ch is a lowercase
letter; false otherwise.
Example:
isLowerCase('a') returns the value true
isLowerCase('A') returns the value false

isUpperCase(ch)
ch is of type char. Returns true, if ch is an uppercase
letter; false otherwise.
Example:
isUpperCase('B') returns the value true
isUpperCase('k') returns the value false

toLowerCase(ch)
ch is of type char. Returns the character that is the
lowercase equivalent of ch. If ch does not have the
corresponding lowercase letter, it returns ch.
Example:
toLowerCase('D') returns the value d
toLowerCase('*') returns the value *

toUpperCase(ch)
ch is of type char. Returns the character that is the
uppercase equivalent of ch. If ch does not have the
corresponding uppercase letter, it returns ch.
Example:
toUpperCase('j') returns the value J
toUpperCase('8') returns the value 8

Predefined Methods Class Math- Java Sample Program

class Math (Package: java.lang)

Example:

abs(-67) returns the value 67

abs(35) returns the value 35

abs(-75.38) returns the value 75.38

ceil(x)
x is of type double. Returns a value of type double, which is the
smallest integer value that is not less than x.
Example: ceil(56.34) returns the value 57.0

exp(x)
x is of type double. Returns ex, where e is approximately
2.7182818284590455.
Example: exp(3) returns the value 20.085536923187668

floor(x)
x is of type double. Returns a value of type double, which is the
largest integer value less than x.
Example: floor(65.78) returns the value 65.0

log(x)
x is of type double. Returns a value of type double, which is the
natural logarithm (base e) of x.
Example: log(2) returns the value 0.6931471805599453

log10(x)
x is of type double. Returns a value of type double, which is the
common logarithm (base 10) of x.
Example: log10(2) returns the value 0.3010299956639812

max(x, y)
Returns the larger of x and y. If x and y are of type int, it returns a
value of type int; if x and y are of type long, it returns a value of type
long; if x and y are of type float, it returns a value of type float;
if x and y are of type double, it returns a value of type double.
Example: max(15, 25) returns the value 25

max(23.67, 14.28) returns the value 23.67

max(45, 23.78) returns the value 45.00

min(x, y)
Returns the smaller of x and y. If x and y are of type int, it returns a
value of type int; if x and y are of type long, it returns a value of type
long; if x and y are of type float, it returns a value of type float;
if x and y are of type double, it returns a value of type double.
Example: min(15, 25) returns the value 15

min(23.67, 14.28) returns the value 14.28

min(12, 34.78) returns the value 12.00

pow(x, y)
x and y are of type double. Returns a value of type double, which is xy.
Example: pow(2.0, 3.0) returns the value 8.0

pow(4, 0.5) returns the value 2.0

round(x)
Returns a value which is the integer closest to x.
Example: round(24.56) returns the value 25

round(18.35) returns the value 18

Class Average - Java While Loop Sample Program

 Suppose we are given a file consisting of students’ names and their test scores, a number
between 0 and 100 (inclusive). Each line in the file consists of a student name followed by
the test score. We want a program that outputs each student’s name followed by the test
score and the grade. The program also needs to output the average test score for the class.
Consider the following program.

// This program reads data from a file consisting of students'
// names and their test scores. The program outputs each
// student's name followed by the test score and the grade. The
// program also outputs the average test score for all students.

import java.io.*; //Line 1
import java.util.*; //Line 2

public class ClassAverage //Line 3
{ //Line 4
public static void main(String[] args) throws FileNotFoundException //Line 5
{ //Line 6
String firstName; //Line 7
String lastName; //Line 8

double testScore; //Line 9
char grade = ' '; //Line 10
double classAverage; //Line 11
double sum = 0; //Line 12
int count = 0; //Line 13

Scanner inFile = new Scanner(new FileReader("stData.txt")); //Line 14
PrintWriter outFile = new PrintWriter("stData.out"); //Line 15

while (inFile.hasNext()) //Line 16
{ //Line 17
firstName = inFile.next();//read the first name Line 18
lastName = inFile.next(); //read the last name Line 19
testScore = inFile.nextDouble(); //read the test score Line 20
sum = sum + testScore; //update sum Line 21
count++; //increment count Line 22

//determine the grade
switch ((int) testScore / 10) //Line 23
{ //Line 24
case 0: //Line 25
case 1: //Line 26
case 2: //Line 27
case 3: //Line 28
case 4: //Line 29
case 5: //Line 30
grade = 'F'; //Line 31
break; //Line 32
case 6: //Line 33
grade = 'D'; //Line 34
break; //Line 35
case 7: //Line 36
grade = 'C'; //Line 37
break; //Line 38
case 8: //Line 39
grade = 'B'; //Line 40
break; //Line 41
case 9: //Line 42
case 10: //Line 43
grade = 'A'; //Line 44
break; //Line 45
default: //Line 46
System.out.println("Invalid score."); //Line 47
}//end switch //Line 48

outFile.printf("%-12s %-12s %4.2f %c %n",firstName, lastName,testScore, grade); //Line 49
}//end while //Line 50

outFile.println(); //Line 51

if (count != 0) //Line 52
outFile.printf("Class Average: %.2f %n",  sum / count); //Line 53
else //Line 54
outFile.println("No data."); //Line 55
outFile.close(); //Line 56
} //Line 57
} //Line 58

Sample Output:
****************************************
Input File:
Steve Gill 89
Rita Johnson 91.5
Randy Brown 85.5
Seema Arora 76.5
Samir Mann 73
Samantha McCoy 88.5
Output File:
Steve Gill 89.00 B
Rita Johnson 91.50 A
Randy Brown 85.50 B
Seema Arora 76.50 C
Samir Mann 73.00 C
Samantha McCoy 88.50 B
Class Average: 84.00
****************************************

 The preceding program works as follows. The statements in Lines 7 to 11 declare
variables required by the program. The statements in Lines 12 and 13 initialize the
variables sum and count. The statement in Line 14 declares inFile to be a reference
variable of type Scanner and associates it with the input file. The statement in Line 15
declares outFile to be a reference variable of type PrintWriter and associates it with
the output file.

 The while loop from Lines 16 to 50 reads each student’s first name, last name, and test
score, and outputs the name followed by the test score and grade. Specifically, the
statement in Line 18 reads the first name, the statement in Line 19 reads the last name,
and the statement in Line 20 reads the test score. The statement in Line 21 updates the
value of sum. (After reading all the data, the value of sum stores the sum of all the test
scores.) The statement in Line 22 updates the value of count. (The variable count stores
the number of students in the class.) The switch statement from Lines 23 to 48
determines the grade from testScore and stores it in the variable grade.

The statement in Line 49 outputs a student’s first name, last name, test score, and grade.
The if...else statement in Lines 52 to 55 outputs the class average, and the statement
in Line 56 closes the file associated with outFile, which is stData.out.

Flag Controlled Loop - Java While Loop Sample Program

//Flag-controlled while loop.
//Guessing the number game.
//Filename: FlagControlledLoop

import java.util.*;

public class FlagControlledLoop
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
//declare the variables
int num; //variable to store the random number
int guess; //variable to store the number

//guessed by the user
boolean done; //boolean variable to control the loop

num = (int) (Math.random() * 100); //Line 1
done = false; //Line 2

while (!done) //Line 3
{ //Line 4
System.out.print ("Enter an integer greater" + " than or equal to 0 and " + "less than 100: "); //Line 5
guess = console.nextInt(); //Line 6
System.out.println(); //Line 7

if (guess == num) //Line 8
{ //Line 9
System.out.println("You guessed the " + "correct number."); //Line 10
done = true; //Line 11
} //Line 12
else if (guess < num) //Line 13
System.out.println("Your guess is " + "lower than " + "the number.\n" + "Guess again!"); //Line 14
else //Line 15
System.out.println("Your guess is " + "higher than " + "the number.\n" + "Guess again!"); //Line 16
} //end while //Line 17
} //Line 18
}


Sample Output:
******************************************************************
Enter an integer greater than or equal to 0 and less than 100: 25
Your guess is higher than the number.
Guess again!

Enter an integer greater than or equal to 0 and less than 100: 5
Your guess is lower than the number.
Guess again!

Enter an integer greater than or equal to 0 and less than 100: 10
Your guess is higher than the number.
Guess again!

Enter an integer greater than or equal to 0 and less than 100: 8
Your guess is higher than the number.
Guess again!

Enter an integer greater than or equal to 0 and less than 100: 6
Your guess is lower than the number.
Guess again!

Enter an integer greater than or equal to 0 and less than 100: 7
You guessed the correct number.

 The preceding program works as follows: The statement in Line 1 creates an integer
greater than or equal to 0 and less than 100 and stores this number in the variable num.

 The statement in Line 2 sets the boolean variable done to false. The while loop starts
at Line 3 and ends at Line 17. The expression in the while loop at Line 3 evaluates the
expression !done. If done is false, then !done is true and the body of the while loop
executes; if done is true, then !done is false, so the while loop terminates.

 The statement in Line 5 prompts the user to enter an integer greater than or equal to 0
and less than 100. The statement in Line 6 stores the number entered by the user in the
variable guess. The expression in the if statement in Line 8 determines whether
the value of guess is the same as num , that is, if the user guessed the number correctly.
If the value of guess is the same as num, then the statements in Lines 10 and 11 execute.

The statement in Line 10 outputs the message:
You guessed the correct number.

 The statement in Line 11 sets the variable done to true. The control then goes back to
Line 3. Because done is true, !done is false and the while loop terminates.
If the expression in Line 8 evaluates to false, then the else statement in Line 13
executes. The statement part of this else is an if. . .else statement, starting at Line 13
and ending at Line 16. The if statement in Line 13 determines whether the value of
guess is less than num. In this case, the statement in Line 14 outputs the message:

Your guess is lower than the number.
Guess again!

 If the expression in the if statement in Line 13 evaluates to false, then the statement in
Line 16 executes, which outputs the message:
Your guess is higher than the number.
Guess again!

The program then prompts the user to enter an integer greater than or equal to 0 and less
than 100.

Perimeter and Area of a Rectangle - Java Sample Program

//Given the length and width of a rectangle, this Java program determines its area and perimeter.
//Filename: RectangleProgram.java

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class RectangleProgram extends JFrame
{
private JLabel lengthL, widthL, areaL, perimeterL;
private JTextField lengthTF, widthTF, areaTF, perimeterTF;
private JButton calculateB, exitB;
private CalculateButtonHandler cbHandler;
private ExitButtonHandler ebHandler;

private static final int WIDTH = 400;
private static final int HEIGHT = 300;

public RectangleProgram()
{
//Create the four labels
lengthL = new JLabel("Enter the length: ", SwingConstants.RIGHT);
widthL = new JLabel("Enter the width: ",SwingConstants.RIGHT);
areaL = new JLabel("Area: ", SwingConstants.RIGHT);
perimeterL = new JLabel("Perimeter: ", SwingConstants.RIGHT);

//Create the four text fields
lengthTF = new JTextField(10);
widthTF = new JTextField(10);
areaTF = new JTextField(10);
perimeterTF = new JTextField(10);

//Create Calculate Button
calculateB = new JButton("Calculate");
cbHandler = new CalculateButtonHandler();
calculateB.addActionListener(cbHandler);

//Create Exit Button
exitB = new JButton("Exit");
ebHandler = new ExitButtonHandler();
exitB.addActionListener(ebHandler);

//Set the title of the window
setTitle("Area and Perimeter of a Rectangle");

//Get the container
Container pane = getContentPane();

//Set the layout
pane.setLayout(new GridLayout(5, 2));

//Place the components in the pane
pane.add(lengthL);
pane.add(lengthTF);
pane.add(widthL);
pane.add(widthTF);
pane.add(areaL);
pane.add(areaTF);
pane.add(perimeterL);
pane.add(perimeterTF);
pane.add(calculateB);
pane.add(exitB);

//Set the size of the window and display it
setSize(WIDTH, HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}

private class CalculateButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
double width, length, area, perimeter;
length = Double.parseDouble(lengthTF.getText());
width = Double.parseDouble(widthTF.getText());
area = length * width;
perimeter = 2 * (length + width);
areaTF.setText("" + area);
perimeterTF.setText("" + perimeter);
}
}

private class ExitButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}

public static void main(String[] args)
{
RectangleProgram rectObject = new RectangleProgram();
}
}


***************Sample Output***************