Showing posts with label Switch Statement. Show all posts
Showing posts with label Switch Statement. Show all posts

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.

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.

Cable Company Billing - Combination of If and Switch Condition - Java Sample Program

// Program: Cable Company Billing
// This program calculates and prints a customer's bill for
// a local cable company. The program processes two types of
// customers: residential and business.

import java.util.*;
public class CableCompanyBilling
{
static Scanner console = new Scanner(System.in);

//Named constants - residential customers
static final double R_BILL_PROC_FEE = 4.50;
static final double R_BASIC_SERV_COST = 20.50;
static final double R_COST_PREM_CHANNEL = 7.50;

//Named constants - business customers
static final double B_BILL_PROC_FEE = 15.00;
static final double B_BASIC_SERV_COST = 75.00;
static final double B_BASIC_CONN_COST = 5.00;
static final double B_COST_PREM_CHANNEL = 50.00;

public static void main(String[] args)
{
//Variable declaration
int accountNumber;
char customerType;
int noOfPremChannels;
int noOfBasicServConn;
double amountDue;

System.out.println("This program computes " + "a cable bill.");
System.out.print("Enter the account "+ "number: "); //Step 1
accountNumber = console.nextInt(); //Step 2
System.out.println();
System.out.print("Enter the customer type: "+ "R or r (Residential), " + "B or b(Business): "); //Step 3
customerType = console.next().charAt(0); //Step 4
System.out.println();

switch (customerType)
{
case 'r': //Step 5
case 'R':
System.out.print("Enter the number of " + "premium channels: "); //Step 5a
noOfPremChannels = console.nextInt(); //Step 5b
System.out.println();
amountDue = R_BILL_PROC_FEE + R_BASIC_SERV_COST + noOfPremChannels * R_COST_PREM_CHANNEL; //Step 5c
System.out.println("Account number = " + accountNumber); //Step 5d
System.out.printf("Amount due = $%.2f %n", amountDue); //Step 5e
break;
case 'b': //Step 6
case 'B':
System.out.print("Enter the number of " + "basic service " + "connections: "); //Step 6a
noOfBasicServConn = console.nextInt(); //Step 6b
System.out.println();
Programming Example: Cable Company Billing | 205
System.out.print("Enter the number of " + "premium channels: "); //Step 6c
noOfPremChannels = console.nextInt(); //Step 6d
System.out.println();

if (noOfBasicServConn <= 10) //Step 6e
amountDue = B_BILL_PROC_FEE + B_BASIC_SERV_COST + noOfPremChannels * B_COST_PREM_CHANNEL;
else

amountDue = B_BILL_PROC_FEE +B_BASIC_SERV_COST +(noOfBasicServConn - 10) * B_BASIC_CONN_COST +
noOfPremChannels * B_COST_PREM_CHANNEL;
System.out.println("Account number = " + accountNumber); //Step 6f
System.out.printf("Amount due = $%.2f %n", amountDue); //Step 6g
break;
default: //Step 7
System.out.println("Invalid customer type.");
}//end switch
}
}

/*
Sample Output: (In this sample run, the user input is shaded.)

This program computes a cable bill.
Enter the account number: 12345
Enter the customer type: R or r (Residential), B or b (Business): b
Enter the number of basic service connections: 16
Enter the number of premium channels: 8
Account number = 12345
Amount due = $520.00
*/

Effect of Break Statements In a Switch Structure

//Effect of break statements in a switch structure
//Filename: BreakStatementsInSwitch.java

import java.util.*;
public class BreakStatementsInSwitch
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
int num;

System.out.print("Enter an integer between "+ "0 and 10: "); //Line 1
num = console.nextInt(); //Line 2
System.out.println(); //Line 3
System.out.println("The number you entered "+ "is " + num); //Line 4

switch (num) //Line 5
{
case 0: //Line 6
case 1: //Line 7
System.out.print("Hello "); //Line 8
case 2: //Line 9
System.out.print("there. "); //Line 10
case 3: //Line 11
System.out.print("I am "); //Line 12
case 4: //Line 13
System.out.println("Mickey."); //Line 14
break; //Line 15
case 5: //Line 16
System.out.print("How "); //Line 17
case 6: //Line 18
case 7: //Line 19
case 8: //Line 20
System.out.println("are you?"); //Line 21
break; //Line 22
case 9: //Line 23
break; //Line 24
case 10: //Line 25
System.out.println("Have a nice day."); //Line 26
break; //Line 27
default: //Line 28
System.out.println("Sorry the number is "+ "out of range."); //Line 29
}

System.out.println("Out of switch " + "structure."); //Line 30
}
}

/*
Sample Output
These outputs were obtained by executing the preceding program several times. In each
of these outputs, the user input is shaded.

Sample Run 1:
Enter an integer between 0 and 10: 0
The number you entered is 0
Hello there. I am Mickey.
Out of switch structure.

Sample Run 2:
Enter an integer between 0 and 10: 3
The number you entered is 3
I am Mickey.
Out of switch structure.

Sample Run 3:
Enter an integer between 0 and 10: 4
The number you entered is 4
Mickey.
Out of switch structure.

Sample Run 4:
Enter an integer between 0 and 10: 7
The number you entered is 7
are you?
Out of switch structure.

Sample Run 5:
Enter an integer between 0 and 10: 9
The number you entered is 9
Out of switch structure.

Explanation

 A walk-through of this program, using certain values of the switch expression num, can
help you understand how the break statement functions. If the value of num is 0,
the value of the switch expression matches the case value 0. All statements following
case 0: execute until a break statement appears.

 The first break statement appears at Line 15, just before the case value of 5. Even
though the value of the switch expression does not match any of the case values (1, 2,
3, or 4), the statements following these values execute.
When the value of the switch expression matches a case value, all statements execute until
a break is encountered, and the program skips all case labels in between. Similarly, if the
value of num is 3, it matches the case value of 3 and the statements following this label
execute until the break statement is encountered at Line 15. If the value of num is 9, it
matches the case value of 9. In this situation, the action is empty, because only the break
statement, at Line 24, follows the case value of 9.

*/