//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
Showing posts with label If and Else Statement. Show all posts
Showing posts with label If and Else Statement. Show all posts
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
// 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
//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
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.
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.
Classify Numbers - Java Sample Program
//********************************************************
// Program: Classify Numbers
// This program counts the number of odd and even numbers.
// The program also counts the number of zeros.
// Filename: ClassifyNumbers.java
//********************************************************
import java.util.*;
public class ClassifyNumbers
{
static Scanner console = new Scanner(System.in);
static final int N = 20;
public static void main (String[] args)
{
//Declare the variables
int counter; //loop control variable
int number; //variable to store the new number
int zeros = 0; //Step 1
int odds = 0; //Step 1
int evens = 0; //Step 1
System.out.println("Please enter " + N + " integers, positive, "
+ "negative, or zeros."); //Step 2
for (counter = 1; counter <= N; counter++) //Step 3
{
number = console.nextInt(); //Step 3a
System.out.print(number + " "); //Step 3b
//Step 3c
switch (number % 2)
{
case 0:
evens++;
if (number == 0)
zeros++;
break;
case 1:
case -1:
odds++;
}//end switch
}//end for loop
System.out.println();
//Step 4
System.out.println("There are " + evens + " evens, "
+ "which also includes "
+ zeros + " zeros");
System.out.println("Total number of odds is: " + odds);
}
}
/*
Sample Output: (In this sample run, the user input is shaded.)
********************************************************
Please enter 20 integers, positive, negative, or zeros.
0 0 -2 -3 -5 6 7 8 0 3 0 -23 -8 0 2 9 0 12 67 54
0 0 -2 -3 -5 6 7 8 0 3 0 -23 -8 0 2 9 0 12 67 54
There are 13 evens, which also includes 6 zeros
Total number of odds is: 7
********************************************************
We recommend that you do a walk-through of this program using the above sample
input.
Note that the switch statement in Step 3c can also be written as an if...else
statement as follows:
if (number % 2 == 0)
{
evens++;
if (number == 0)
zeros++;
}
else
odds++;
// Program: Classify Numbers
// This program counts the number of odd and even numbers.
// The program also counts the number of zeros.
// Filename: ClassifyNumbers.java
//********************************************************
import java.util.*;
public class ClassifyNumbers
{
static Scanner console = new Scanner(System.in);
static final int N = 20;
public static void main (String[] args)
{
//Declare the variables
int counter; //loop control variable
int number; //variable to store the new number
int zeros = 0; //Step 1
int odds = 0; //Step 1
int evens = 0; //Step 1
System.out.println("Please enter " + N + " integers, positive, "
+ "negative, or zeros."); //Step 2
for (counter = 1; counter <= N; counter++) //Step 3
{
number = console.nextInt(); //Step 3a
System.out.print(number + " "); //Step 3b
//Step 3c
switch (number % 2)
{
case 0:
evens++;
if (number == 0)
zeros++;
break;
case 1:
case -1:
odds++;
}//end switch
}//end for loop
System.out.println();
//Step 4
System.out.println("There are " + evens + " evens, "
+ "which also includes "
+ zeros + " zeros");
System.out.println("Total number of odds is: " + odds);
}
}
/*
Sample Output: (In this sample run, the user input is shaded.)
********************************************************
Please enter 20 integers, positive, negative, or zeros.
0 0 -2 -3 -5 6 7 8 0 3 0 -23 -8 0 2 9 0 12 67 54
0 0 -2 -3 -5 6 7 8 0 3 0 -23 -8 0 2 9 0 12 67 54
There are 13 evens, which also includes 6 zeros
Total number of odds is: 7
********************************************************
We recommend that you do a walk-through of this program using the above sample
input.
Note that the switch statement in Step 3c can also be written as an if...else
statement as follows:
if (number % 2 == 0)
{
evens++;
if (number == 0)
zeros++;
}
else
odds++;
Fibonacci - Java Sample Program
//*************************************************************
// Program: nth Fibonacci number
// Given the first two numbers of a Fibonacci sequence, this
// determines and outputs the desired number of the Fibonacci
// sequence.
// Filename: FibonacciNumber.java
//*************************************************************
import javax.swing.JOptionPane;
public class FibonacciNumber
{
public static void main (String[] args)
{
//Declare variables
String inputString;
String outputString;
int previous1;
int previous2;
int current = 0;
int counter;
int nthFibonacci;
inputString =JOptionPane.showInputDialog("Enter the first "
+ "Fibonacci number: "); //Step 1
previous1 = Integer.parseInt(inputString); //Step 2
inputString = JOptionPane.showInputDialog("Enter the second "
+ "Fibonacci number: "); //Step 3
previous2 = Integer.parseInt(inputString); //Step 4
outputString = "The first two numbers of the "
+ "Fibonacci sequence are: "
+ previous1 + " and " + previous2; //Step 5
inputString =JOptionPane.showInputDialog("Enter the position "
+ "of the desired number in "
+ "the Fibonacci sequence: "); //Step 6
nthFibonacci = Integer.parseInt(inputString); //Step 7
if (nthFibonacci == 1) //Step 8.a
current = previous1;
else if (nthFibonacci == 2) //Step 8.b
current = previous2;
else //Step 8.c
{
counter = 3; //Step 8.c.1
//Steps 8.c.2 - 8.c.5
while (counter <= nthFibonacci)
{
current = previous2 + previous1; //Step 8.c.2
previous1 = previous2; //Step 8.c.3
counter++; //Step 8.c.5
}
}
outputString ¼ outputString + "\nThe "
+ nthFibonacci
+ "th Fibonacci number of "
+ "the sequence is: "
+ current; //Step 9
JOptionPane.showMessageDialog(null, outputString,"Fibonacci Number",
JOptionPane.INFORMATION_MESSAGE); //Step 10
System.exit(0);
}
}
//Sample Output:
// Program: nth Fibonacci number
// Given the first two numbers of a Fibonacci sequence, this
// determines and outputs the desired number of the Fibonacci
// sequence.
// Filename: FibonacciNumber.java
//*************************************************************
import javax.swing.JOptionPane;
public class FibonacciNumber
{
public static void main (String[] args)
{
//Declare variables
String inputString;
String outputString;
int previous1;
int previous2;
int current = 0;
int counter;
int nthFibonacci;
inputString =JOptionPane.showInputDialog("Enter the first "
+ "Fibonacci number: "); //Step 1
previous1 = Integer.parseInt(inputString); //Step 2
inputString = JOptionPane.showInputDialog("Enter the second "
+ "Fibonacci number: "); //Step 3
previous2 = Integer.parseInt(inputString); //Step 4
outputString = "The first two numbers of the "
+ "Fibonacci sequence are: "
+ previous1 + " and " + previous2; //Step 5
inputString =JOptionPane.showInputDialog("Enter the position "
+ "of the desired number in "
+ "the Fibonacci sequence: "); //Step 6
nthFibonacci = Integer.parseInt(inputString); //Step 7
if (nthFibonacci == 1) //Step 8.a
current = previous1;
else if (nthFibonacci == 2) //Step 8.b
current = previous2;
else //Step 8.c
{
counter = 3; //Step 8.c.1
//Steps 8.c.2 - 8.c.5
while (counter <= nthFibonacci)
{
current = previous2 + previous1; //Step 8.c.2
previous1 = previous2; //Step 8.c.3
counter++; //Step 8.c.5
}
}
outputString ¼ outputString + "\nThe "
+ nthFibonacci
+ "th Fibonacci number of "
+ "the sequence is: "
+ current; //Step 9
JOptionPane.showMessageDialog(null, outputString,"Fibonacci Number",
JOptionPane.INFORMATION_MESSAGE); //Step 10
System.exit(0);
}
}
//Sample Output:
Class Average - Java 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.
// Filename: ClassAverage.java
import java.io.*; //Line 1
import java.util.*; //Line 2
public class ClassAverage //Line 3
{ //Line 4
public static void main(String[] args)
{ //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
*****************************************
*/
// ******Explanation******
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.
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.
// Filename: ClassAverage.java
import java.io.*; //Line 1
import java.util.*; //Line 2
public class ClassAverage //Line 3
{ //Line 4
public static void main(String[] args)
{ //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
*****************************************
*/
// ******Explanation******
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.
Counter-Controlled While Loop - Java Sample Program
//Counter-controlled while loop
//Filename: CounterControlledWhileLoop
import java.util.*;
public class CounterControlledWhileLoop
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
int limit; //store the number of items in the list
int number; //variable to store the number
int sum; //variable to store the sum
int counter; //loop control variable
System.out.print("Line 1: Enter the number of " + "integers in the list: "); //Line 1
limit = console.nextInt(); //Line 2
System.out.println(); //Line 3
sum = 0; //Line 4
counter = 0; //Line 5
System.out.println("Line 6: Enter " + limit + " integers."); //Line 6
while (counter < limit) //Line 7
{
number = console.nextInt(); //Line 8
sum = sum + number; //Line 9
counter++; //Line 10
}
System.out.printf("Line 11: The sum of the %d " + "numbers = %d%n", limit, sum); //Line 11
if (counter != 0) //Line 12
System.out.printf("Line 13: The average = %d%n",(sum / counter)); //Line 13
else //Line 14
System.out.println("Line 15: No input."); //Line 15
}
}
/*
Sample Output:
In this sample run, the user input is shaded.
*********************************************************
Line 1: Enter the number of integers in the list: 12
Line 6: Enter 12 integers.
8 9 2 3 90 38 56 8 23 89 7 2
Line 11: The sum of the 12 numbers = 335
Line 13: The average = 27
*********************************************************
Explanation:
The preceding program works as follows: The statement in Line 1 prompts the user to
input the data for processing. The statement in Line 2 reads the next input and stores it in
the variable limit. The value of limit indicates the number of items to be read. The
statements in Lines 4 and 5 initialize the variables sum and counter to 0. The while
statement in Line 7 checks the value of counter to determine how many items have
been read. If counter is less than limit, the while loop proceeds for the next iteration.
The statement in Line 8 stores the next number in the variable number. The statement in
Line 9 updates the value of sum by adding the value of number to the previous value. The
statement in Line 10 increments the value of counter by 1. The statement in Line 11
outputs the sum of the numbers. The statements in Lines 12 through 15 output either the
average or the text: Line 15: No input.
Note that in this program, in Line 4, sum is initialized to 0. In Line 9, after storing the
next number in number in Line 8, the program adds the next number to the sum of all
the numbers scanned before the current number. The first number read is added to zero
(because sum is initialized to 0), giving the correct sum of the first number. To find the
average, divide sum by counter. If counter is 0, then dividing by 0 terminates the
program and you get an error message. Therefore, before dividing sum by counter, you
must check whether or not counter is 0.
Notice that in this program, the statement in Line 5 initializes the LCV counter to 0.
The expression counter < limit in Line 7 evaluates whether counter is less than
limit. The statement in Line 8 updates the value of counter. Note that in this program,
the while loop can also be written without using the variable number as follows:
while (counter < limit)
{
sum = sum + console.nextInt();
counter++;
}
*/
//Filename: CounterControlledWhileLoop
import java.util.*;
public class CounterControlledWhileLoop
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
int limit; //store the number of items in the list
int number; //variable to store the number
int sum; //variable to store the sum
int counter; //loop control variable
System.out.print("Line 1: Enter the number of " + "integers in the list: "); //Line 1
limit = console.nextInt(); //Line 2
System.out.println(); //Line 3
sum = 0; //Line 4
counter = 0; //Line 5
System.out.println("Line 6: Enter " + limit + " integers."); //Line 6
while (counter < limit) //Line 7
{
number = console.nextInt(); //Line 8
sum = sum + number; //Line 9
counter++; //Line 10
}
System.out.printf("Line 11: The sum of the %d " + "numbers = %d%n", limit, sum); //Line 11
if (counter != 0) //Line 12
System.out.printf("Line 13: The average = %d%n",(sum / counter)); //Line 13
else //Line 14
System.out.println("Line 15: No input."); //Line 15
}
}
/*
Sample Output:
In this sample run, the user input is shaded.
*********************************************************
Line 1: Enter the number of integers in the list: 12
Line 6: Enter 12 integers.
8 9 2 3 90 38 56 8 23 89 7 2
Line 11: The sum of the 12 numbers = 335
Line 13: The average = 27
*********************************************************
Explanation:
The preceding program works as follows: The statement in Line 1 prompts the user to
input the data for processing. The statement in Line 2 reads the next input and stores it in
the variable limit. The value of limit indicates the number of items to be read. The
statements in Lines 4 and 5 initialize the variables sum and counter to 0. The while
statement in Line 7 checks the value of counter to determine how many items have
been read. If counter is less than limit, the while loop proceeds for the next iteration.
The statement in Line 8 stores the next number in the variable number. The statement in
Line 9 updates the value of sum by adding the value of number to the previous value. The
statement in Line 10 increments the value of counter by 1. The statement in Line 11
outputs the sum of the numbers. The statements in Lines 12 through 15 output either the
average or the text: Line 15: No input.
Note that in this program, in Line 4, sum is initialized to 0. In Line 9, after storing the
next number in number in Line 8, the program adds the next number to the sum of all
the numbers scanned before the current number. The first number read is added to zero
(because sum is initialized to 0), giving the correct sum of the first number. To find the
average, divide sum by counter. If counter is 0, then dividing by 0 terminates the
program and you get an error message. Therefore, before dividing sum by counter, you
must check whether or not counter is 0.
Notice that in this program, the statement in Line 5 initializes the LCV counter to 0.
The expression counter < limit in Line 7 evaluates whether counter is less than
limit. The statement in Line 8 updates the value of counter. Note that in this program,
the while loop can also be written without using the variable number as follows:
while (counter < limit)
{
sum = sum + console.nextInt();
counter++;
}
*/
Guessing The Number Game - Java Sample Program
The following program randomly generates an integer greater than or equal to 0 and less
than 100. The program then prompts the user to guess the number. If the user guesses the
number correctly, the program outputs an appropriate message.
Otherwise, the program checks whether the guessed number is less than the random number. If the guessed number is less than the random the number generated by the program, the program outputs the message, ‘‘Your guess is lower than the number’’; otherwise, the program
outputs the message, ‘‘Your guess is higher than the number’’. The program then
prompts the user to enter another number. The user is prompted to guess the random
number until the user enters the correct number.
The program uses the method random of the class Math to generate a random number.
To be specific, the expression:
Math.random()
returns a value of type double greater than or equal to 0.0 and less than 1.0. To convert
it to an integer greater than or equal to 0 and less than 100, the program uses the
following expression:
(int) (Math.random() * 100);
Furthermore, the program uses the boolean variable done to control the loop. The
boolean variable done is initialized to false. It is set to true when the user guesses the
correct number.
//Flag-controlled while loop.
//Guessing the number game.
//Filename: FlagControlledLoop.java
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: (In the following sample run, the user input is shaded.)
*********************************************************************
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
5
while Looping (Repetition) Structure | 241
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.
than 100. The program then prompts the user to guess the number. If the user guesses the
number correctly, the program outputs an appropriate message.
Otherwise, the program checks whether the guessed number is less than the random number. If the guessed number is less than the random the number generated by the program, the program outputs the message, ‘‘Your guess is lower than the number’’; otherwise, the program
outputs the message, ‘‘Your guess is higher than the number’’. The program then
prompts the user to enter another number. The user is prompted to guess the random
number until the user enters the correct number.
The program uses the method random of the class Math to generate a random number.
To be specific, the expression:
Math.random()
returns a value of type double greater than or equal to 0.0 and less than 1.0. To convert
it to an integer greater than or equal to 0 and less than 100, the program uses the
following expression:
(int) (Math.random() * 100);
Furthermore, the program uses the boolean variable done to control the loop. The
boolean variable done is initialized to false. It is set to true when the user guesses the
correct number.
//Flag-controlled while loop.
//Guessing the number game.
//Filename: FlagControlledLoop.java
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: (In the following sample run, the user input is shaded.)
*********************************************************************
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
5
while Looping (Repetition) Structure | 241
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.
Telephone Digits - Java Sample Program
/*
The following program reads the letter codes 'A' through 'Z' and prints the corresponding
telephone digit. This program uses a sentinel-controlled while loop. To stop
the program, the user is prompted for the sentinel, which is '#'. This is also an example
of a nested control structure, where if... else, switch, and the while loop are
nested.
*/
//********************************************************
// Program: Telephone Digits
// This is an example of a sentinel-controlled while loop.
// This program converts uppercase letters to their
// corresponding telephone digits.
// Filename: TelephoneDigitProgram.java
//********************************************************
import javax.swing.JOptionPane;
public class TelephoneDigitProgram
{
public static void main (String[] args)
{
char letter; //Line 1
String inputMessage; //Line 2
String inputString; //Line 3
String outputMessage; //Line 4
inputMessage = "Program to convert uppercase "
+ "letters to their corresponding "
+ "telephone digits.\n"
+ "To stop the program enter #.\n"
+ "Enter a letter:"; //Line 5
inputString = JOptionPane.showInputDialog(inputMessage); //Line 6
letter = inputString.charAt(0); //Line 7
while (letter != '#' ) //Line 8
{
outputMessage = "The letter you entered is: "
+ letter + "\n"
+ "The corresponding telephone "
+ "digit is: "; //Line 9
if (letter >= 'A' && letter <= 'Z') //Line 10
{
switch (letter) //Line 11
{
case 'A':
case 'B':
case 'C': outputMessage = outputMessage + "2"; //Line 12
break; //Line 13
case 'D':
case 'E':
case 'F': outputMessage = outputMessage + "3"; //Line 14
break; //Line 15
case 'G':
case 'H':
case 'I': outputMessage = outputMessage + "4"; //Line 16
break; //Line 17
case 'J':
case 'K':
case 'L': outputMessage = outputMessage + "5"; //Line 18
break; //Line 19
case 'M':
case 'N':
case 'O': outputMessage = outputMessage + "6"; //Line 20
break; //Line 21
case 'P':
case 'Q':
case 'R':
case 'S': outputMessage = outputMessage + "7"; //Line 22
break; //Line 23
case 'T':
case 'U':
case 'V': outputMessage = outputMessage + "8"; //Line 24
break; //Line 25
case 'W':
case 'X':
case 'Y':
case 'Z': outputMessage = outputMessage + "9"; //Line 26
}
}
else //Line 27
outputMessage = outputMessage + "Invalid input"; //Line 28
JOptionPane.showMessageDialog(null, outputMessage, "Telephone Digit",
JOptionPane.PLAIN_MESSAGE); //Line 29
inputMessage = "Enter another uppercase letter "
+ "to find its corresponding "
+ "telephone digit.\n"
+ "To stop the program enter #.\n"
+ "Enter a letter:"; //Line 30
inputString = JOptionPane.showInputDialog(inputMessage); //Line 31
letter = inputString.charAt(0); //Line 32
}//end while
System.exit(0); //Line 33
}
}
/*
Sample Output:
*/
The following program reads the letter codes 'A' through 'Z' and prints the corresponding
telephone digit. This program uses a sentinel-controlled while loop. To stop
the program, the user is prompted for the sentinel, which is '#'. This is also an example
of a nested control structure, where if... else, switch, and the while loop are
nested.
*/
//********************************************************
// Program: Telephone Digits
// This is an example of a sentinel-controlled while loop.
// This program converts uppercase letters to their
// corresponding telephone digits.
// Filename: TelephoneDigitProgram.java
//********************************************************
import javax.swing.JOptionPane;
public class TelephoneDigitProgram
{
public static void main (String[] args)
{
char letter; //Line 1
String inputMessage; //Line 2
String inputString; //Line 3
String outputMessage; //Line 4
inputMessage = "Program to convert uppercase "
+ "letters to their corresponding "
+ "telephone digits.\n"
+ "To stop the program enter #.\n"
+ "Enter a letter:"; //Line 5
inputString = JOptionPane.showInputDialog(inputMessage); //Line 6
letter = inputString.charAt(0); //Line 7
while (letter != '#' ) //Line 8
{
outputMessage = "The letter you entered is: "
+ letter + "\n"
+ "The corresponding telephone "
+ "digit is: "; //Line 9
if (letter >= 'A' && letter <= 'Z') //Line 10
{
switch (letter) //Line 11
{
case 'A':
case 'B':
case 'C': outputMessage = outputMessage + "2"; //Line 12
break; //Line 13
case 'D':
case 'E':
case 'F': outputMessage = outputMessage + "3"; //Line 14
break; //Line 15
case 'G':
case 'H':
case 'I': outputMessage = outputMessage + "4"; //Line 16
break; //Line 17
case 'J':
case 'K':
case 'L': outputMessage = outputMessage + "5"; //Line 18
break; //Line 19
case 'M':
case 'N':
case 'O': outputMessage = outputMessage + "6"; //Line 20
break; //Line 21
case 'P':
case 'Q':
case 'R':
case 'S': outputMessage = outputMessage + "7"; //Line 22
break; //Line 23
case 'T':
case 'U':
case 'V': outputMessage = outputMessage + "8"; //Line 24
break; //Line 25
case 'W':
case 'X':
case 'Y':
case 'Z': outputMessage = outputMessage + "9"; //Line 26
}
}
else //Line 27
outputMessage = outputMessage + "Invalid input"; //Line 28
JOptionPane.showMessageDialog(null, outputMessage, "Telephone Digit",
JOptionPane.PLAIN_MESSAGE); //Line 29
inputMessage = "Enter another uppercase letter "
+ "to find its corresponding "
+ "telephone digit.\n"
+ "To stop the program enter #.\n"
+ "Enter a letter:"; //Line 30
inputString = JOptionPane.showInputDialog(inputMessage); //Line 31
letter = inputString.charAt(0); //Line 32
}//end while
System.exit(0); //Line 33
}
}
/*
Sample Output:
*/
Subscribe to:
Posts (Atom)

