Java Lecture Chapter 5

Marvic

Member
Using Controls with Conditional Statements
Computers can make decisions based on given condition. This condition can be evaluated whether true or false. The computer will act appropriately based on the result of the evaluation. In most cases, the conditions are conditional expressions with the application of relational operators and logical operators.

if-else if Syntax

The if-else if control construct allows the computer to evaluate three or more conditional statements, but to execute only one associated statement which is the statement of the first conditional expression that is evaluated to True. In other words, use the if-else if control structure to define several blocks of statements, one of which will execute. Its general syntax is:
Code:
if condition1 {
    Statement1          associated statement
}
else if condition2 {
    Statement2
}
else if condition3 {
    Statement3
}
.
.
.
else  {
    Statementn
}

The Java language will evaluate first the condition1. If it is False, the Java language’s invisible program pointer will proceed to evaluate condition2, and so on, until it finds a True condition. When True condition is found, only then that its associated statement will be executed. We can also add the else conditional statement as the option to choose in the if-else if conditional statement. This will provide a way to catch some impossible to meet conditions or the “none of the above” situation. We may use the else statement for error-checking, sometimes.

switch/case Syntax

The switch/case conditional statement is an alternative to if-else if conditional statement. With the use of switch/case statement, we can simplify some of the code that are tedious, long, and cumbersome when we use the if-else if statement. In other words, the switch/case can be the best substitute conditional statement to write a clearer and concise multi-way decision program compared to the messy if-else if statement. Here is the switch/case general syntax:
Code:
switch   (var_expression) {
    case  value_expression1:
        Statement1           associated statement
    case value_expression2:
        Statement2
    case  value_expression3:
        Statement3
    default:
        Statementn
}

Like in the rules of if-else if statement, if more than one case matches the var_expression, only the statement associated with the first matching case will be executed. The default statement will be executed if none of the values in the above expression list matches the var_expression.

It acts like else statement in if-else if conditional statement. It is an optional statement too.

We have to take note also that although the switch/case statement is the best substitute for the if/else if statement, it has an inherent limitations. For example, we cannot apply the relational operators that are mixed with logical operators such as less than (<), greater than (>), less than or equal to (<=), greater than or equal to (>=), not equal (<>) logical || (or) and logical && (and) operators. We cannot say:

case >0 || case <100
Or
case >0 && case <100

This is a syntax error. Instead, we have to rewrite the code in switch/case format which in many cases look so very different from the if/else if syntax and yet produce the same result.

It takes you to learn deeply the switch/case syntax and its limitations and capabilities before you can successfully convert your if-else if code into its switch/case equivalent. Otherwise, you would have a hard time converting an if- else if code into switch/case code. Let us now have our examples for these conditional statements.

Example 1:
Design and develop a Java program that determines if the input number at Text field 1 is equivalent to the magic words: “I love you” or not. Display the result “I love you!” at the Text field 2 if the input number is 143, and “Wrong guess!” if it is not. Follow the design specification below:

Solution:
1. At the Microsoft NotePad, write the following code:
Code:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class magicno1 extends Applet implements ActionListener {
  TextField txtMNumber, txtMessage;
  Label lblMNumber;
  Button cmdExecute;
  public void init() {
       lblMNumber = new Label("Enter the magic number:");
       add(lblMNumber);
       txtMNumber = new TextField(4);
       add(txtMNumber);
       cmdExecute = new Button("Execute");
       add(cmdExecute);
       cmdExecute.addActionListener(this);
       txtMessage = new TextField(19);
       add(txtMessage);
   }
 public void actionPerformed(ActionEvent objE) {
 int varMNumber=0;
 if (objE.getSource() == cmdExecute) {
   varMNumber= Integer.parseInt(txtMNumber.getText());
   if (varMNumber==143)
      txtMessage.setText("I love you!");
   else
      txtMessage.setText("Wrong guess!");
 }
 }
}

2. Then save the Java program with the filename: magicno1.java.
3. This time, open a new file at the NotePad to write the HTML script needed for the applet and type the following code:
Code:
<html>
<!- Web page written with Java Applet>
<head>
<title>magicno1</title>
</head>
<body>
<hr>
<applet
code=magicno1.class
width=250
height=150>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: magicno1.htm.
5. This time, activate the Java compiler batch file with the following steps:
Type the word command at the Run menu of Windows operating system, then at the C:\> prompt, type:
C:\>cd javaprog (then press the Enter key)
C:\JAVAPROG>javap (then press the Enter key)
6. Finally, you can now compile your program with the following MS-DOS command:
C:\JAVAPROG>javac magicno1.java (then press the Enter key)
7. When no error is encountered during the compilation process, you can now type the following
at your Web browser:
C:\javaprog\magicno1.htm
Explanation:

We created a new class named magicno1 here in our program. Then we declared the two text fields which we named txtMNumber and txtMessage. We used the txtMNumber object to get the number entered by the user, while the txtMessage object is used to display the message in the second text field. The label lblMNumber is declared using Java Label class and the command button cmdExecute is declared using the Button class as you can see in our code below:
Code:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class magicno1 extends Applet implements ActionListener {
  TextField txtMNumber, txtMessage;
  Label lblMNumber;
  Button cmdExecute;

You will notice that we actually created and add the objects we had declared at the top of our program here in the init( ) method:
Code:
  public void init( ) {
       lblMNumber = new Label("Enter the magic number:");
       add(lblMNumber);
        txtMNumber = new TextField(4);
       add(txtMNumber);
       cmdExecute = new Button("Execute");
       add(cmdExecute);
       cmdExecute.addActionListener(this);
       txtMessage = new TextField(19);
       add(txtMessage);
   }

We can make the program to determine if the input number of the user at text field 1 (txtMNumber) is a magic number by implementing the ActionListener interface, and connect our command button cmdExecute to it. Then finally add the actionPerformed ( ) method to complete the process:
Code:
public void actionPerformed(ActionEvent objE) {
 int varMNumber=0;
 if (objE.getSource( ) == cmdExecute) {
   varMNumber= Integer.parseInt(txtMNumber.getText( ));
   if (varMNumber==143)
      txtMessage.setText("I love you!");
   else
      txtMessage.setText("Wrong guess!");
 }
 }
}

When the command button cmdExecute is clicked, we instruct the computer to read the numeric data entered by the user in text field 1, txtMNumber. To read the numeric data from the text field, we apply the getText( ) method such as the following syntax:

txtMNumber.getText( )

This syntax returns the text string in the text field, txtMNumber. For example, if the user inputs the data “143” in txtMNumber text field, this is actually a text string value. We need to convert it to its equivalent numeric value using the parseInt( ) method under the Integer class of the Java language such as the following syntax:

Integer.parseInt(txtMNumber.getText( ))

In this way, we can now store the entered numeric data from txtMNumber and store the result to variable varMNumber. This time we can use the numeric data of varMNumber to be evaluated if it is equal to 143 which is the equivalent of the magic number, using the following syntax:
Code:
   if (varMNumber==143)
      txtMessage.setText("I love you!");
   else
      txtMessage.setText("Wrong guess!");
Now if the conditional expression is evaluated to true, then its associated statement

txtMessage.setText("I love you!")

will be executed. Otherwise, the associated statement of the else conditional statement:

txtMessage.setText("Wrong guess!")

will be executed instead.

Remember that here in our program, we use an outer if statement and inner if statement.

The outer if statement:

if (objE.getSource( ) == cmdExecute)

simply tests if the cmdExecute button was clicked by the user. And if it is indeed clicked, its associated statements will be executed. It happened that its associated statements contain an inner if:

if (varMNumber==143)

which is also being tested. This further means that the inner if conditional statement can have a chance to be executed only if and only if the outer if conditional statement is evaluated or tested as true first.

Otherwise, there is no way for it to be executed. This is how the outer and inner ifs work technically.

You will notice here that we increase the applet’s width to 250 and decrease the height to 150 (as you can see in the HTML script below), because we want to accommodate the label “Enter the magic number:” , the text field used for entering the data and command button Execute (cmdExecute) to be displayed in the applet within the same line. With this adjustment, these three controls will be displayed in the applet properly, as well as the controls that follow.
Code:
<applet
code=magicno1.class
width=250
height=150>
</applet>

Example 2:
Design and develop a Java program that determines if the input number at Text field 1 is a positive or negative. Consider 0 as positive number. Follow the design specification below:

Solution:
1. At the Microsoft NotePad, write the following code:
Code:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class positive1 extends Applet implements ActionListener {
  TextField txtNumber, txtMessage;
  Label lblNumber;
  Button cmdExecute;
  public void init() {
     lblNumber = new Label("Enter a number:");
     add(lblNumber);
     txtNumber = new TextField(6);
     add(txtNumber);
     cmdExecute = new Button("Execute");
     add(cmdExecute);
     cmdExecute.addActionListener(this);
     txtMessage = new TextField(19);
     add(txtMessage);
    }
 public void actionPerformed(ActionEvent objE) {
 int varNumber=0;
 if (objE.getSource() == cmdExecute) {
   varNumber= Integer.parseInt(txtNumber.getText());
   if (varNumber>=0)
      txtMessage.setText("It is a Positive number!");
   else
      txtMessage.setText("It is a Negative number!");
 }
 }
}

2. Then save the Java program with the filename: positive1.java.
3. This time, open a new file at the NotePad to write the HTML script needed for the applet and type the following code:
Code:
<html>
<!- Web page written with Java Applet>
<head>
<title>positive1</title>
</head>
<body>
<hr>
<applet
code=positive1.class
width=200
height=150>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: positive1.htm.
5. This time, activate the Java compiler batch file with the following steps:
Type the word command at the Run menu of Windows operating system, then at the C:\> prompt, type:
C:\>cd javaprog (then press the Enter key)
C:\JAVAPROG>javap (then press the Enter key)
6. Finally, you can now compile your program with the following MS-DOS command:
C:\JAVAPROG>javac positive1.java (then press the Enter key)
7. When no error is encountered during the compilation process, you can now type the following
at your Web browser:
C:\javaprog\positive1.htm

Explanation:
We created a new class named positive1 here in our program. Then we declared the two text fields which we named txtNumber and txtMessage. We used the txtNumber object to get the number entered by the user, while the txtMessage object is used to display the message in the second text field. The label lblNumber is declared using Java Label class and the command button cmdExecute is declared using the Button class as you can see in our code below:
Code:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class positive1 extends Applet implements ActionListener {
  TextField txtNumber, txtMessage;
  Label lblNumber;
  Button cmdExecute;

You will notice that we actually created and add the objects we had declared at the top of our program here in the init( ) method:
Code:
  public void init( ) {
      lblNumber = new Label("Enter a number:");
     add(lblNumber);
     txtNumber = new TextField(6);
      add(txtNumber);
       cmdExecute = new Button("Execute");
       add(cmdExecute);
       cmdExecute.addActionListener(this);
       txtMessage = new TextField(19);
       add(txtMessage);
    }

We can make the program to determine if the input number of the user at text field 1 (txtNumber) is positive or negative number by implementing the ActionListener interface, and connect our command button cmdExecute to it. Then finally add the actionPerformed ( ) method to complete the process:
Code:
public void actionPerformed(ActionEvent objE) {
 int varNumber=0;
 if (objE.getSource( ) == cmdExecute) {
   varNumber= Integer.parseInt(txtNumber.getText( ));
   if (varNumber>=0)
      txtMessage.setText("It is a Positive number!");
   else
      txtMessage.setText("It is a Negative number!");
 }
 }
}

When the command button cmdExecute is clicked, we instruct the computer to read the numeric data entered by the user in text field 1, txtNumber. To read the numeric data from the text field, we apply the getText( ) method such as the following syntax:

txNumber.getText( )

This syntax returns the text string in the text field, txtNumber. For example, if the user inputs the data “-5” in txtNumber text field, this is actually a text string value. We need to convert it to its equivalent numeric value using the parseInt( ) method under the Integer class of the Java language such as the following syntax:

Integer.parseInt(txtNumber.getText( ))

In this way, we can now store the entered numeric data from txtNumber and store the result to variable varNumber. This time we can use the numeric data of varNumber to be evaluated if it is equal to or greater than zero (varNumber>=0) which is our process to determine a positive number, using the following syntax:
Code:
   if (varNumber>=0)
      txtMessage.setText("It is a Positive number!");
   else
      txtMessage.setText("It is a Negative number!");
Now if the conditional expression is evaluated to true, then its associated statement

txtMessage.setText("It is a Positive number!")

will be executed. Otherwise, the associated statement of the else conditional statement:

txtMessage.setText("It is a Negative number!")

will be executed instead.
Remember that here in our program, we use an outer if statement and inner if statement.

The outer if statement:

if (objE.getSource( ) == cmdExecute)

simply tests if the cmdExecute button was clicked by the user. And if it is indeed clicked, its associated statements will be executed. It happened that its associated statements contain an inner if:

if (varNumber>=0)

which is also being tested. This further means that the inner if conditional statement can have a chance to be executed only if and only if the outer if conditional statement is evaluated or tested as true first.

Otherwise, there is no way for it to be executed. This is how the outer and inner ifs work technically.
You will notice here that we decrease the height to 150 (as you can see in the HTML script below), because we want to position the label “Enter a number:” and the text field used for entering the data at the top of our applet, then position the command button Execute (cmdExecute) below it. With this adjustment, the controls will be displayed in the applet properly, in accordance to the required design specification.
Code:
<applet
code=positive1.class
width=200
height=150>
</applet>

Example 3:
Design and develop a Java program to display the high school level of a student, based on its year-entry number. For example, the year-entry 1 means the student is freshman, 2 for sophomore, and so on. Here is the given criteria:
Year-entry number High-School Level
1 Freshman
2 Sophomore
3 Junior
4 Senior
5 Out-Of-Range
Follow the design specification below:

1st Solution: (using if - else if conditional statements)
1. At the Microsoft NotePad, write the following code:
Code:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class school1 extends Applet implements ActionListener {
   TextField txtYear, txtMessage;
  Label lblYear,lblMessage;
  Button cmdExecute;
  public void init() {
      lblYear = new Label("Enter the Year-entry number:");
      add(lblYear);
       txtYear = new TextField(3);
       add(txtYear);
       cmdExecute = new Button("Execute");
       add(cmdExecute);
       cmdExecute.addActionListener(this);
       lblMessage = new Label("The High-School Level is:");
       add(lblMessage);
       txtMessage = new TextField(17);
       add(txtMessage);
 }
 public void actionPerformed(ActionEvent objE) {
 int varYear;
 if (objE.getSource() == cmdExecute) {
   varYear = Integer.parseInt(txtYear.getText());
   if (varYear==1)
      txtMessage.setText("Freshman");
   else if (varYear==2)
      txtMessage.setText("Sophomore");
   else if (varYear==3)
      txtMessage.setText("Junior");
   else if (varYear==4)
      txtMessage.setText("Senior");
   else
       txtMessage.setText("Out-Of-Range");
 }
 }
}

2. Then save the Java program with the filename: school1.java.
3. This time, open a new file at the NotePad to write the HTML script needed for the applet and type the following code:
Code:
<html>
<!- Web page written with Java Applet>
<head>
<title>school1</title>
</head>
<body>
<hr>
<applet
code=school1.class
width=300
height=150>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: school1.htm.
5. This time, activate the Java compiler batch file with the following steps:
Type the word command at the Run menu of Windows operating system, then at the C:\> prompt, type:
C:\>cd javaprog (then press the Enter key)
C:\JAVAPROG>javap (then press the Enter key)
6. Finally, you can now compile your program with the following MS-DOS command:
C:\JAVAPROG>javac school1.java (then press the Enter key)
7. When no error is encountered during the compilation process, you can now type the following
at your Web browser:
C:\javaprog\school1.htm

Explanation:
We created a new class named school1 here in our program. Then we declared the two text fields which we named txtYear and txtMessage. We used the txtYear object to get the year-entry number entered by the user, while the txtMessage object is used to display the message in the second text field. The label lblYear and lblMessage are declared using Java Label class and the command button cmdExecute is declared using the Button class as you can see in our code below:
Code:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class school1 extends Applet implements ActionListener {
  TextField txtYear, txtMessage;
  Label lblYear,lblMessage;
  Button cmdExecute;

You will notice that we actually created and add the objects we had declared at the top of our program here in the init( ) method:
Code:
  public void init( ) {
       lblYear = new Label("Enter the Year-entry number:");
       add(lblYear);
       txtYear = new TextField(3);
       add(txtYear);
       cmdExecute = new Button("Execute");
       add(cmdExecute);
       cmdExecute.addActionListener(this);
       lblMessage = new Label("The High-School Level is:");
       add(lblMessage);
       txtMessage = new TextField(17);
       add(txtMessage);
      }

We can make our program to determine the year-entry level of the student at text field 1 (txtYear) by implementing the ActionListener interface, and connect our command button cmdExecute to it. Then finally add the actionPerformed ( ) method to complete the process:
Code:
public void actionPerformed(ActionEvent objE) {
 int varYear;
 if (objE.getSource( ) == cmdExecute) {
   varYear = Integer.parseInt(txtYear.getText( ));
   if (varYear==1)
      txtMessage.setText("Freshman");
   else if (varYear==2)
      txtMessage.setText("Sophomore");
   else if (varYear==3)
      txtMessage.setText("Junior");
   else if (varYear==4)
      txtMessage.setText("Senior");
   else
       txtMessage.setText("Out-Of-Range");
 }
 }
}

When the command button cmdExecute is clicked, we instruct the computer to read the numeric data entered by the user in text field 1, txtYear. To read the numeric data from the text field, we apply the getText( ) method such as the following syntax:

txtYear.getText( )

This syntax returns the text string in the text field, txtYear. For example, if the user inputs the data “2” in txtYear text field, this is actually a text string value. We need to convert it to its equivalent numeric value using the parseInt( ) method under the Integer class of the Java language such as the following syntax:

Integer.parseInt(txtYear.getText( ))

In this way, we can now store the entered numeric data from txtYear and store the result to variable varYear:

varYear = Integer.parseInt(txtYear.getText( ))

This time we can use the numeric data of varYear to be evaluated if it is equal to 1 (varYear==1) which is our process to determine the year-entry level of the student, using the following syntax:
if (varYear==1)

txtMessage.setText("Freshman");

Now if the conditional expression is evaluated to true, then its associated statement
txtMessage.setText("Freshman")

will be executed. Otherwise, the other else if conditional statements:
Code:
   else if (varYear==2)
      txtMessage.setText("Sophomore");
   else if (varYear==3)
      txtMessage.setText("Junior");
   else if (varYear==4)
      txtMessage.setText("Senior");
   else
       txtMessage.setText("Out-Of-Range");

will be the next to be evaluated or tested. Now if one of them are evaluated to True, then its corresponding associated statement will be executed. For example, the year-entry number entered by the user is 2, then the following else if conditional statement is evaluated to True:
Code:
      else if (varYear==2)
          txtMessage.setText("Sophomore");

thus, the output to be displayed is “Sophomore”.
In the if-else if syntax, after finding a True evaluation for a particular conditional statement, the Java program compiler will jump right to the end of the if statement, thus ending the evaluation or testing process. In other words, the remaining conditions below it will no longer be evaluated or tested ( or simply ignored). Technically, this will save much microprocessor’s processing power compared to using all ifs conditional statements in our program. Meaning, using the if statement all throughout instead of else if statement. With the if statement, all conditional statements will be evaluated or tested, regardless of how many True evaluations found at the upper part of the conditional block. This makes very taxing to the microprocessor’s processing power. In other words, the following code is not advisable to use (since there is only one option to be selected by our Java program to comply with the given requirement):
Code:
  if (varYear==1) 
      txtMessage.setText("Freshman");
   if  (varYear==2)
         txtMessage.setText("Sophomore");
   if  (varYear==3)
       txtMessage.setText("Junior");
   if (varYear==4)
       txtMessage.setText("Senior");

Notice all the conditional statements pointed by the arrows. It contained all ifs. It’s bad in programming. There are cases or situations in real-world application that we have no other choice but to use all the ifs statements throughout in our program (like the one you see above), however such cases or situations rarely occur. So use all ifs statements with utmost care, okay?

2nd Solution: (using the switch/case conditional statement)
1. At the Microsoft NotePad, write the following code:
Code:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class school2 extends Applet implements ActionListener {
  TextField txtYear, txtMessage;
  Label lblYear,lblMessage;
  Button cmdExecute;
  public void init() {
       lblYear = new Label("Enter the Year-entry number:");
       add(lblYear);
       txtYear = new TextField(3);
       add(txtYear);
       cmdExecute = new Button("Execute");
       add(cmdExecute);
       cmdExecute.addActionListener(this);
       lblMessage = new Label("The High-School Level is:");
       add(lblMessage);
       txtMessage = new TextField(17);
       add(txtMessage);
 }
 public void actionPerformed(ActionEvent objE) {
 int varYear;
 if (objE.getSource() == cmdExecute) {
    varYear = Integer.parseInt(txtYear.getText());
  switch(varYear) {
    case 1:
      txtMessage.setText("Freshman");
      break;
    case 2:
      txtMessage.setText("Sophomore");
      break;
    case 3:
      txtMessage.setText("Junior");
      break;
    case 4:
      txtMessage.setText("Senior");
      break;
    default:
       txtMessage.setText("Out-Of-Range");
    }
  }
}
}

2. Then save the Java program with the filename: school2.java.
3. This time, open a new file at the NotePad to write the HTML script needed for the applet and type the following code:
Code:
<html>
<!- Web page written with Java Applet>
<head>
<title>school2</title>
</head>
<body>
<hr>
<applet
code=school2.class
width=300
height=150>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: school2.htm.
5. This time, activate the Java compiler batch file with the following steps:
Type the word command at the Run menu of Windows operating system, then at the C:\> prompt, type:
C:\>cd javaprog (then press the Enter key)
C:\JAVAPROG>javap (then press the Enter key)
6. Finally, you can now compile your program with the following MS-DOS command:
C:\JAVAPROG>javac school2.java (then press the Enter key)
7. When no error is encountered during the compilation process, you can now type the following
at your Web browser:
C:\javaprog\school2.htm

Explanation:
We created a new class named school2 here in our program. Then we declared the two text fields which we named txtYear and txtMessage. We used the txtYear object to get the year-entry entered by the user, while the txtMessage object is used to display the message in the second text field. The label lblYear and lblMessage are declared using Java Label class and the command button cmdExecute is declared using the Button class as you can see in our code below:
Code:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class school2 extends Applet implements ActionListener {
  TextField txtYear, txtMessage;
  Label lblYear,lblMessage;
  Button cmdExecute;

You will notice that we actually created and add the objects we had declared at the top of our program here in the init( ) method:
Code:
  public void init( ) {
       lblYear = new Label("Enter the Year-entry number:");
       add(lblYear);
       txtYear = new TextField(3);
       add(txtYear);
       cmdExecute = new Button("Execute");
       add(cmdExecute);
       cmdExecute.addActionListener(this);
       lblMessage = new Label("The High-School Level is:");
       add(lblMessage);
       txtMessage = new TextField(17);
       add(txtMessage);
 }

We can make our program to determine the year-entry level of the student at text field 1 (txtYear) by implementing the ActionListener interface, and connect our command button cmdExecute to it. Then finally add the actionPerformed ( ) method to complete the process:
Code:
public void actionPerformed(ActionEvent objE) {
 int varYear;
 if (objE.getSource( ) == cmdExecute) {
    varYear = Integer.parseInt(txtYear.getText( ));
  switch(varYear) {
    case 1:
      txtMessage.setText("Freshman");
      break;
    case 2:
      txtMessage.setText("Sophomore");
      break;
    case 3:
      txtMessage.setText("Junior");
      break;
    case 4:
      txtMessage.setText("Senior");
      break;
    default:
       txtMessage.setText("Out-Of-Range");
    }
  }
}
}

When the command button cmdExecute is clicked, we instruct the computer to read the numeric data entered by the user in text field 1, txtYear. To read the numeric data from the text field, we apply the getText( ) method such as the following syntax:

txtYear.getText( )

This syntax returns the text string in the text field, txtYear. For example, if the user inputs the data “2” in txtYear text field, this is actually a text string value. We need to convert it to its equivalent numeric value using the parseInt( ) method under the Integer class of the Java language such as the following syntax:

Integer.parseInt(txtYear.getText( ))

In this way, we can now store the entered numeric data from txtYear and store the result to variable varYear:

varYear = Integer.parseInt(txtYear.getText( ))

In switch/case conditional statement, we have to pass varGrade variable to switch statement using the following syntax:

switch (varYear)

The switch (varYear) command holds the value of the variable varYear for testing, evaluation, or comparison with the given value_expression of each case or group of cases.

Once the match is found (means the value of variable varYear is the same with the value_expression found) then the program pointer will search the associated statement and execute it. For example, if we enter the value of 2 at the text field txtYear, the program pointer will execute the associated statement:
txtMessage.setText("Sophomore");

since this value_expression can be found at the second case label. When the value entered does not match to any value_expression listed, the associated statement of default is executed instead. If the default is not included (since it is optional), then nothing will be executed.

You will observe that all the associated statements are followed by the break command.

This break command will trigger the program pointer to break out from the whole switch/case (statement) block. Meaning, it jumps to the statement that follows the end ( } ) symbol of switch/case statement. This makes our switch/case solution to act and execute like the way if / else if / else do. It’s like ignoring all the remaining conditional statements and expressions below when there is already a true-evaluation at the top. In short, the break statement causes an immediate exit from the switch/case (statement) block.

Example 4:
Design and develop a Java program that will assist a teacher in converting a range of numerical grade into its equivalent letter form grade, based on the given scale.
Range Grade
90 - 100 A
80 - 89 B
70 - 79 C
60 - 69 D
50 - 59 F
other grades I (for Invalid)
Follow the design specification below:

1st Solution: (using if - else if conditional statements)
1. At the Microsoft NotePad, write the following code:
Code:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class grade1 extends Applet implements ActionListener {
  TextField txtGrade, txtMessage;
  Label lblGrade,lblMessage;
  Button cmdExecute;
  public void init() {
      lblGrade = new Label("Enter a grade:");
      add(lblGrade);
      txtGrade = new TextField(3);
      add(txtGrade);
      cmdExecute = new Button("Execute");
      add(cmdExecute);
      cmdExecute.addActionListener(this);
      lblMessage = new Label("Your grade in letter for is:");
      add(lblMessage);
      txtMessage = new TextField(4);
      add(txtMessage);
    }
 public void actionPerformed(ActionEvent objE) {
 int varGrade=0;
 if (objE.getSource() == cmdExecute) {
   varGrade = Integer.parseInt(txtGrade.getText());
   if ((varGrade>=90) && (varGrade<=100))
      txtMessage.setText("A");
   else if ((varGrade>=80) && (varGrade<=89))
       txtMessage.setText("B");
   else if ((varGrade>=70) && (varGrade<=79))
      txtMessage.setText("C");
   else if ((varGrade>=60) && (varGrade<=69))
      txtMessage.setText("D");
   else if ((varGrade>=50) && (varGrade<=59))
     txtMessage.setText("F");
   else
       txtMessage.setText(“I”); 
   }
 }
}

2. Then save the Java program with the filename: grade1.java.
3. This time, open a new file at the NotePad to write the HTML script needed for the applet and type the following code:
Code:
<html>
<!- Web page written with Java Applet>
<head>
<title>grade1</title>
</head>
<body>
<hr>
<applet
code=grade1.class
width=250
height=150>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: grade1.htm.
5. This time, activate the Java compiler batch file with the following steps:
Type the word command at the Run menu of Windows operating system, then at the C:\> prompt, type:
C:\>cd javaprog (then press the Enter key)
C:\JAVAPROG>javap (then press the Enter key)
6. Finally, you can now compile your program with the following MS-DOS command:
C:\JAVAPROG>javac grade1.java (then press the Enter key)
7. When no error is encountered during the compilation process, you can now type the following
at your Web browser:
C:\javaprog\grade1.htm

Explanation:
We created a new class named grade1 here in our program. Then we declared the two text fields which we named txtGrade and txtMessage. We used the txtGrade object to get the grade entered by the user, while the txtMessage object is used to display the message in the second text field. The label lblGrade is declared using Java Label class and the command button cmdExecute is declared using the Button class as you can see in our code below:
Code:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class grade1 extends Applet implements ActionListener {
  TextField txtGrade, txtMessage;
  Label lblGrade,lblMessage;
  Button cmdExecute;

You will notice that we actually created and add the objects we had declared at the top of our program here in the init( ) method:
Code:
  public void init( ) {
      lblGrade = new Label("Enter a grade:");
      add(lblGrade);
      txtGrade = new TextField(3);
      add(txtGrade);
     cmdExecute = new Button("Execute");
     add(cmdExecute);
     cmdExecute.addActionListener(this);
     lblMessage = new Label("Your grade in letter for is:");
     add(lblMessage);
     txtMessage = new TextField(4);
     add(txtMessage);
    }

We can make our program to determine the equivalent letter form grade of the input numeric grade of the user at text field 1 (txtGrade) by implementing the ActionListener interface, and connect our command button cmdExecute to it. Then finally add the actionPerformed ( ) method to complete the process:
Code:
public void actionPerformed(ActionEvent objE) {
 int varGrade=0;
 if (objE.getSource( ) == cmdExecute) {
   varGrade = Integer.parseInt(txtGrade.getText( ));
   if ((varGrade>=90) && (varGrade<=100))
      txtMessage.setText("A");
   else if ((varGrade>=80) && (varGrade<=89))
       txtMessage.setText("B");
   else if ((varGrade>=70) && (varGrade<=79))
      txtMessage.setText("C");
   else if ((varGrade>=60) && (varGrade<=69))
      txtMessage.setText("D");
   else if (varGrade>=50) && (varGrade<=59))
      txtMessage.setText("F");
   else
    txtMessage.setText(“I”);
   }
 }
}

When the command button cmdExecute is clicked, we instruct the computer to read the numeric data entered by the user in text field 1, txtGrade. To read the numeric data from the text field, we apply the getText( ) method such as the following syntax:

txGrade.getText( )

This syntax returns the text string in the text field, txtGrade. For example, if the user inputs the data “94” in txtGrade text field, this is actually a text string value. We need to convert it to its equivalent numeric value using the parseInt( ) method under the Integer class of the Java language such as the following syntax:

Integer.parseInt(txtGrade.getText( ))

In this way, we can now store the entered numeric data from txtGrade and store the result to variable varGrade. This time we can use the numeric data of varGrade to be evaluated if it is equal to or greater than 90 (varGrade>=90) which is our process to determine what is its equivalent in letter form grade, using the following syntax:
Code:
   if  ((varGrade>=90) && (varGrade<=100))
       txtMessage.setText("A");
Now if the conditional expression is evaluated to true, then its associated statement
      txtMessage.setText("A")
will be executed. Otherwise, the other else if conditional statements:
  else if ((varGrade>=80) && (varGrade<=89))
       txtMessage.setText("B");
   else if ((varGrade>=70) && (varGrade<=79))
      txtMessage.setText("C");
   else if ((varGrade>=60) && (varGrade<=69))
      txtMessage.setText("D");
   else if (varGrade>=50) && (varGrade<=59))
     txtMessage.setText("F");
else
   txtMessage.setText(“I”);

will be the next to be evaluated or tested. Now if one of them are evaluated to True, then its corresponding associated statement will be executed. For example, the grade entered by the user is 78, and since this grade falls between the range of 70 to 79, therefore the following else if conditional statement is evaluated to True:

else if ((varGrade>=70) && (varGrade<=79))
txtMessage.setText("C");

thus, the output to be displayed is “C”. To explain it further how the above code works (as well as the others), let us learn how the logical && (and) operates in this situation. Using the logical && (and), we can trap the numeric range of the grade entered. In doing so, we can ensure that the grade entered falls within a specific range, and our program will respond appropriately based on it. Remember that in logical && (and), both or all conditional expressions must be evaluated to True so that its associated statement(s) will be executed. In our case, the entered grade is 78 which is greater than 70 and less than 79 (so both conditional expressions are tested true).

In the if-else if syntax, after finding a True evaluation for a particular conditional statement, the Java program compiler will jump right to the end of the if statement, thus ending the evaluation or testing process. In other words, the remaining conditions below it will no longer be evaluated or tested ( or simply ignored). Technically, this will save much microprocessor’s processing power compared to using all ifs conditional statements in our program. Meaning, using the if statement all throughout instead of else if statement. With the if statement, all conditional statements will be evaluated or tested, regardless of how many True evaluations found at the upper part of the conditional block. This makes very taxing to the microprocessor’s processing energy. In other words, the following code is not advisable to use (since there is only one option to be selected by our Java program to comply with the given requirement):
Code:
   if (varGrade>=90) && (varGrade<=100))
       txtMessage.setText("A");
   if   ((varGrade>=80) && (varGrade<=89))
         txtMessage.setText("B");
    if  ((varGrade>=70) && (varGrade<=79))
          txtMessage.setText("C");
   if   ((varGrade>=60) && (varGrade<=69))
         txtMessage.setText("D");
  if (varGrade>=50) && (varGrade<=59))
       txtMessage.setText("F");
if (varGrade>100) || (varGrade<50)
    txtMessage.setText(“I”);

Notice all the conditional statements pointed by the arrows. It contained all ifs. It’s bad in programming. There are cases or situations in real-world application that we have no other choice but to use all the ifs statements throughout in our program (like the one you see above), however such cases or situations rarely occur. So use all ifs statements with utmost care, okay?

2nd Solution: (using the switch/case conditional statement)
1. At the Microsoft NotePad, write the following code:
Code:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class grade2 extends Applet implements ActionListener {
  TextField txtGrade, txtMessage;
  Label lblGrade,lblMessage;
  Button cmdExecute;
  public void init() {
       lblGrade = new Label("Enter a grade:");
       add(lblGrade);
       txtGrade = new TextField(3);
       add(txtGrade);
       cmdExecute = new Button("Execute");
       add(cmdExecute);
       cmdExecute.addActionListener(this);
       lblMessage = new Label("Your grade in letter for is:");
       add(lblMessage);
       txtMessage = new TextField(4);
       add(txtMessage);
  }
 public void actionPerformed(ActionEvent objE) {
 int varGrade=0;
 if (objE.getSource() == cmdExecute) {
   varGrade = Integer.parseInt(txtGrade.getText());
   switch (varGrade) {
   case 90: case 91: case 92: case 93: case 94:
   case 95: case 96: case 97: case 98: case 99: case 100:
    txtMessage.setText("A");break;
   case 80: case 81: case 82: case 83: case 84:
   case 85: case 86: case 87: case 88: case 89:
     txtMessage.setText("B");break;
   case 70: case 71: case 72: case 73: case 74:
   case 75: case 76: case 77: case 78: case 79:
      txtMessage.setText("C");break;
   case 60: case 61: case 62: case 63: case 64:
   case 65: case 66: case 67: case 68: case 69:
      txtMessage.setText("D");break;
   case 50: case 51: case 52: case 53: case 54:
   case 55: case 56: case 57: case 58: case 59:
     txtMessage.setText("F");break;
   default:
      txtMessage.setText("I");
   }
 }
 }
}

2. Then save the Java program with the filename: grade2.java.
3. This time, open a new file at the NotePad to write the HTML script needed for the applet and type the following code:
Code:
<html>
<!- Web page written with Java Applet>
<head>
<title>grade2</title>
</head>
<body>
<hr>
<applet
code=grade2.class
width=250
height=150>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: grade2.htm.
5. This time, activate the Java compiler batch file with the following steps:
Type the word command at the Run menu of Windows operating system, then at the C:\> prompt, type:
C:\>cd javaprog (then press the Enter key)
C:\JAVAPROG>javap (then press the Enter key)
6. Finally, you can now compile your program with the following MS-DOS command:
C:\JAVAPROG>javac grade2.java (then press the Enter key)
7. When no error is encountered during the compilation process, you can now type the following
at your Web browser:
C:\javaprog\grade2.htm

Explanation:
We created a new class named grade2 here in our program. Then we declared the two text fields which we named txtGrade and txtMessage. We used the txtGrade object to get the grade entered by the user, while the txtMessage object is used to display the message in the second text field. The label lblGrade is declared using Java Label class and the command button cmdExecute is declared using the Button class as you can see in our code below:
Code:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class grade2  extends Applet implements ActionListener {
  TextField txtGrade, txtMessage;
  Label lblGrade,lblMessage;
  Button cmdExecute;

You will notice that we actually created and add the objects we had declared at the top of our program here in the init( ) method:
Code:
  public void init( ) {
      lblGrade = new Label("Enter a grade:");
      add(lblGrade);
      txtGrade = new TextField(3);
      add(txtGrade);
      cmdExecute = new Button("Execute");
      add(cmdExecute);
      cmdExecute.addActionListener(this);
      lblMessage = new Label("Your grade in letter for is:");
      add(lblMessage);
      txtMessage = new TextField(4);
      add(txtMessage);
    }

We can make our program to determine the equivalent letter form grade of the input numeric grade of the user at text field 1 (txtGrade) by implementing the ActionListener interface, and connect our command button cmdExecute to it. Then finally add the actionPerformed ( ) method to complete the process:
Code:
public void actionPerformed(ActionEvent objE) {
 int varGrade=0;
 if (objE.getSource( ) == cmdExecute) {
   varGrade = Integer.parseInt(txtGrade.getText( ));
   switch (varGrade) {
   case 90: case 91: case 92: case 93: case 94:
   case 95: case 96: case 97: case 98: case 99: case 100:
    txtMessage.setText("A");break;
   case 80: case 81: case 82: case 83: case 84:
   case 85: case 86: case 87: case 88: case 89:
     txtMessage.setText("B");break;
   case 70: case 71: case 72: case 73: case 74:
   case 75: case 76: case 77: case 78: case 79:
      txtMessage.setText("C");break;
   case 60: case 61: case 62: case 63: case 64:
   case 65: case 66: case 67: case 68: case 69:
      txtMessage.setText("D");break;
   case 50: case 51: case 52: case 53: case 54:
   case 55: case 56: case 57: case 58: case 59:
     txtMessage.setText("F");break;
   default:
      txtMessage.setText("I");
   }
 }
 }
}

When the command button cmdExecute is clicked, we instruct the computer to read the numeric data entered by the user in text field 1, txtGrade. To read the numeric data from the text field, we apply the getText( ) method such as the following syntax:

txGrade.getText( )

This syntax returns the text string in the text field, txtGrade. For example, if the user inputs the data “94” in txtGrade text field, this is actually a text string value. We need to convert it to its equivalent numeric value using the parseInt( ) method under the Integer class of the Java language such as the following syntax:

Integer.parseInt(txtGrade.getText( ))
In this way, we can now store the entered numeric data from txtGrade and store the result to variable varGrade. In switch/case conditional statement, we have to pass varGrade variable to switch statement using the following syntax:

switch (varGrade)

The switch (varGrade) command holds the value of the variable varGrade for testing, evaluation, or comparison with the given value_expression of each case or group of cases.

Once the match is found (means the value of variable varGrade is the same with the value_expression found) then the program pointer will search the associated statement and execute it. For example, if we enter the value of 94 at the text field txtGrade, the program pointer will execute the associated statement:

txtMessage.setText("A")

since this value_expression can be found at the first group of case labels. When the value entered does not match to any value_expression listed, the associated statement of default is executed instead. If the default is not included (since it is optional), then nothing will be executed.

You will observe that all the associated statements are followed by the break command. This break command will trigger the program pointer to break out from the whole switch/case (statement) block. Meaning, it jumps to the statement that follows the end ( } ) symbol of switch/case statement. This makes our switch/case solution to act and execute like the way if / else if / else do. It’s like ignoring all the remaining conditional statements and expressions below when there is already a true-evaluation at the top. In short, the break statement causes an immediate exit from the switch/case (statement) block.

What is noticeable also in our program is that it seems our equivalent switch/case conditional statement does not improve the readability of our program. Nor it shortens our program listing. Yes, we can say that why it is not like in Visual Basic programming language, where in we can write the range of 90 to 100 with the simple syntax:

Case 90 To 100
txtMessage.Text = “A”

Well, we can consider this case as one of the weaknesses of switch/case statement compared to if/else if conditional statement.

Example 5:
Design and develop a Java program that determines if the input number at Text field 1 is a positive or negative. Consider 0 as positive number. This time, develop your program without the use of command button control, instead we have to use the TextListener interface and addTextListener method. Follow the design specification below:

Solution:
1. At the Microsoft NotePad, write the following code:
Code:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class positive2 extends Applet implements TextListener {
  TextField txtNumber, txtMessage;
  Label lblNumber;
  public void init() {
    lblNumber = new Label("Enter a number:");
    add(lblNumber);
    txtNumber = new TextField(6);
    add(txtNumber);
    txtNumber.addTextListener(this);
    txtMessage = new TextField(19);
    add(txtMessage);
   }
  public void textValueChanged(TextEvent objE) {
  int varNumber=0;
  varNumber= Integer.parseInt(txtNumber.getText());
  if (varNumber>=0)
     txtMessage.setText("It is a Positive number!");
  else
     txtMessage.setText("It is a Negative number!");
  repaint();
 } }

2. Then save the Java program with the filename: positive2.java.
3. This time, open a new file at the NotePad to write the HTML script needed for the applet and type the following code:
Code:
<html>
<!- Web page written with Java Applet>
<head>
<title>positive2</title>
</head>
<body>
<hr>
<applet
code=positive2.class
width=200
height=150>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: positive2.htm.
5. This time, activate the Java compiler batch file with the following steps:
Type the word command at the Run menu of Windows operating system, then at the C:\> prompt, type:
C:\>cd javaprog (then press the Enter key)
C:\JAVAPROG>javap (then press the Enter key)
6. Finally, you can now compile your program with the following MS-DOS command:
C:\JAVAPROG>javac positive2.java (then press the Enter key)
7. When no error is encountered during the compilation process, you can now type the following
at your Web browser:
C:\javaprog\positive2.htm

Explanation:
We created a new class named positive2 here in our program. Then we declared the two text fields which we named txtNumber and txtMessage. We used the txtNumber object to get the number entered by the user, while the txtMessage object is used to display the message in the second text field. The label lblNumber is declared using Java Label class. You can observe that we are using here the TextListener interface instead of the ActionListener as you can see in our code below:
Code:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class positive2 extends Applet implements TextListener {
  TextField txtNumber, txtMessage;
  Label lblNumber;

You will notice that we actually created and add the objects we had declared at the top of our program in the init( ) method. You will notice that this time we are using here the addTextListener method instead of the addActionListener as follows:
Code:
  public void init( ) {
    lblNumber = new Label("Enter a number:");
    add(lblNumber);
    txtNumber = new TextField(6);
    add(txtNumber);
    txtNumber.addTextListener(this);
    txtMessage = new TextField(19);
    add(txtMessage);
   }

We can make the program to determine if the input number of the user at text field 1 (txtNumber) is positive or negative number by implementing the ItemListener interface, and connect our text field txtNumber to it. Then finally add the textValueChanged ( ) method to complete the process:
Code:
  public void textValueChanged(TextEvent objE) {
  int varNumber=0;
  varNumber= Integer.parseInt(txtNumber.getText( ));
  if (varNumber>=0)
     txtMessage.setText("It is a Positive number!");
  else
     txtMessage.setText("It is a Negative number!");
  repaint( );
 }
}

When the the value of the text field 1 has changed (meaning, the user is entering another value) , we instruct the computer to read the numeric data entered by the user. To read the numeric data from the text field, we apply the getText( ) method such as the following syntax:

txNumber.getText( )

This syntax returns the text string in the text field, txtNumber. For example, if the user inputs the data “-7” in txtNumber text field, this is actually a text string value. We need to convert it to its equivalent numeric value using the parseInt( ) method under the Integer class of the Java language such as the following syntax:

Integer.parseInt(txtNumber.getText( ))

In this way, we can now store the entered numeric data from txtNumber and store the result to variable varNumber. This time we can use the numeric data of varNumber to be evaluated if it is equal to or greater than zero (varNumber>=0) which is our process to determine a positive number, using the following syntax:
Code:
   if (varNumber>=0)
      txtMessage.setText("It is a Positive number!");
   else
      txtMessage.setText("It is a Negative number!");

Now if the conditional expression is evaluated to true, then its associated statement

txtMessage.setText("It is a Positive number!")

will be executed. Otherwise, the associated statement of the else conditional statement:

txtMessage.setText("It is a Negative number!")

will be executed instead.

Example 6:
Design and develop a Java program that will assist a teacher in converting a range of numerical grade into its equivalent letter form grade, based on the given scale. This time, develop your program without the use of command button control, instead we have to use the TextListener interface and addTextListener method.

Range Grade
90 - 100 A
80 - 89 B
70 - 79 C
60 - 69 D
50 - 59 F
other grades I (for Invalid)

Follow the design specification below:

Solution:
1. At the Microsoft NotePad, write the following code:
Code:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class grade3 extends Applet implements TextListener {
  TextField txtGrade, txtMessage;
  Label lblGrade,lblMessage;
  public void init() {
       lblGrade = new Label("Enter a grade:");
       add(lblGrade);
       txtGrade = new TextField(3);
       add(txtGrade);
       txtGrade.addTextListener(this);
       lblMessage = new Label("Your grade in letter form is:");
       add(lblMessage);
       txtMessage = new TextField(4);
       add(txtMessage);
   }
 public void textValueChanged(TextEvent objE) {
 int varGrade=0;
   varGrade = Integer.parseInt(txtGrade.getText());
   switch (varGrade) {
   case 90: case 91: case 92: case 93: case 94:
   case 95: case 96: case 97: case 98: case 99: case 100:
    txtMessage.setText("A");break;
   case 80: case 81: case 82: case 83: case 84:
   case 85: case 86: case 87: case 88: case 89:
     txtMessage.setText("B");break;
   case 70: case 71: case 72: case 73: case 74:
   case 75: case 76: case 77: case 78: case 79:
      txtMessage.setText("C");break;
   case 60: case 61: case 62: case 63: case 64:
   case 65: case 66: case 67: case 68: case 69:
      txtMessage.setText("D");break;
   case 50: case 51: case 52: case 53: case 54:
   case 55: case 56: case 57: case 58: case 59:
     txtMessage.setText("F");break;
   default:
      txtMessage.setText("I");
   }
   repaint();
 }
}

2. Then save the Java program with the filename: grade3.java.
3. This time, open a new file at the NotePad to write the HTML script needed for the applet and type the following code:
Code:
<html>
<!- Web page written with Java Applet>
<head>
<title>grade3</title>
</head>
<body>
<hr>
<applet
code=grade3.class
width=250
height=150>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: grade3.htm.
5. This time, activate the Java compiler batch file with the following steps:
Type the word command at the Run menu of Windows operating system, then at the C:\> prompt, type:
C:\>cd javaprog (then press the Enter key)
C:\JAVAPROG>javap (then press the Enter key)
6. Finally, you can now compile your program with the following MS-DOS command:
C:\JAVAPROG>javac grade3.java (then press the Enter key)
7. When no error is encountered during the compilation process, you can now type the following
at your Web browser:
C:\javaprog\grade3.htm

Explanation:
We created a new class named grade3 here in our program. Then we declared the two text fields which we named txtNumber and txtMessage. We used the txtNumber object to get the number entered by the user, while the txtMessage object is used to display the message in the second text field. The label lblNumber is declared using Java Label class. You can observe that we are using here the TextListener interface instead of the ActionListener as you can see in our code below:
Code:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class grade3 extends Applet implements TextListener {
   TextField txtGrade, txtMessage;
  Label lblGrade,lblMessage;

You will notice that we actually created and add the objects we had declared at the top of our program in the init( ) method. You will notice that this time we are using here the addTextListener method instead of the addActionListener as follows:
Code:
  public void init( ) {
        lblGrade = new Label("Enter a grade:");
       add(lblGrade);
       txtGrade = new TextField(3);
       add(txtGrade);
       txtGrade.addTextListener(this);
       lblMessage = new Label("Your grade in letter form is:");
       add(lblMessage);
       txtMessage = new TextField(4);
       add(txtMessage);
   }

We can make our program to determine the equivalent letter form grade of the input numeric grade of the user at text field 1 (txtGrade) by implementing the ItemListener interface, and connect our text field txtNumber to it. Then finally add the textValueChanged ( ) method to complete the process:
Code:
public void textValueChanged(TextEvent objE) {
 int varGrade=0;
 varGrade = Integer.parseInt(txtGrade.getText( ));
   switch (varGrade) {
   case 90: case 91: case 92: case 93: case 94:
   case 95: case 96: case 97: case 98: case 99: case 100:
    txtMessage.setText("A");break;
   case 80: case 81: case 82: case 83: case 84:
   case 85: case 86: case 87: case 88: case 89:
     txtMessage.setText("B");break;
   case 70: case 71: case 72: case 73: case 74:
   case 75: case 76: case 77: case 78: case 79:
      txtMessage.setText("C");break;
   case 60: case 61: case 62: case 63: case 64:
   case 65: case 66: case 67: case 68: case 69:
      txtMessage.setText("D");break;
   case 50: case 51: case 52: case 53: case 54:
   case 55: case 56: case 57: case 58: case 59:
     txtMessage.setText("F");break;
   default:
      txtMessage.setText("I");
   }
   repaint( );
 }
}

When the the value of the text field 1 has changed (meaning, the user is entering another value) , we instruct the computer to read the numeric data entered by the user. To read the numeric data, we instruct the computer to read the numeric data entered by the user in text field 1, txtGrade. To read the numeric data from the text field, we apply the getText( ) method such as the following syntax:

txGrade.getText( )

This syntax returns the text string in the text field, txtGrade. For example, if the user inputs the data “94” in txtGrade text field, this is actually a text string value. We need to convert it to its equivalent numeric value using the parseInt( ) method under the Integer class of the Java language such as the following syntax:

Integer.parseInt(txtGrade.getText( ))

In this way, we can now store the entered numeric data from txtGrade and store the result to variable varGrade. In switch/case conditional statement, we have to pass varGrade variable to switch statement using the following syntax:

switch (varGrade)

The switch (varGrade) command holds the value of the variable varGrade for testing, evaluation, or comparison with the given value_expression of each case or group of cases.

Once the match is found (means the value of variable varGrade is the same with the value_expression found) then the program pointer will search the associated statement and execute it. For example, if we enter the value of 94 at the text field txtGrade, the program pointer will execute the associated statement:

txtMessage.setText("A")

since this value_expression can be found at the first group of case labels. When the value entered does not match to any value_expression listed, the associated statement of default is executed instead. If the default is not included (since it is optional), then nothing will be executed.

You will observe that all the associated statements are followed by the break command. This break command will trigger the program pointer to break out from the whole switch/case (statement) block. Meaning, it jumps to the statement that follows the end ( } ) symbol of switch/case statement. This makes our switch/case solution to act and execute like the way if / else if / else do. It’s like ignoring all the remaining conditional statements and expressions below when there is already a true-evaluation at the top. In short, the break

statement causes an immediate exit from the switch/case (statement) block.

Using Option Buttons and Check Boxes Together

Here in our example,we will use the Option buttons together with Check boxes in a hypothetical application system. Let us learn how to manipulate them together. Well, we will apply other popular controls too, such as Text fields. Okay, let us see it in action!

Example 7:
Design and develop a Java program that when the user chooses the Hamburger option, the ingredients to be marked with a check are: Beef and Spices; its corresponding price is 49.25 (to be displayed at the text field). If the user chooses the Cheeseburger option, the ingredients to be checked are: Beef, Spices, and Cheese; its corresponding price is 69.50. Now if the user chooses the Baconburger option, all the ingredients are marked with a check and its corresponding price is 89.75.
Follow the design specification below:

Solution:
1. At the Microsoft NotePad, write the following code:
Code:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class burger1 extends Applet implements ItemListener {
Menu Panel1;
Ingredients Panel2;
public void init() {
  setLayout(new GridLayout(1,2));
  Panel1 = new Menu();
  Panel2 = new Ingredients();
  add(Panel1);
  Panel1.Hamburger.addItemListener(this);
  Panel1.Cheeseburger.addItemListener(this);
  Panel1.Baconburger.addItemListener(this);
  add(Panel2);
}
public void itemStateChanged(ItemEvent objEvent) {
if (objEvent.getItemSelectable()==Panel1.Hamburger) {
    Panel2.Ingredient1.setState(true);
    Panel2.Ingredient2.setState(true);
    Panel2.Ingredient3.setState(false);
    Panel2.Ingredient4.setState(false);
    Panel1.txtPrice.setText("Price:49.25");
}
if (objEvent.getItemSelectable()==Panel1.Cheeseburger) {
    Panel2.Ingredient1.setState(true);
    Panel2.Ingredient2.setState(true);
    Panel2.Ingredient3.setState(true);
    Panel2.Ingredient4.setState(false);
    Panel1.txtPrice.setText("Price:69.50");
}
if (objEvent.getItemSelectable()==Panel1.Baconburger) {
    Panel2.Ingredient1.setState(true);
    Panel2.Ingredient2.setState(true);
    Panel2.Ingredient3.setState(true);
    Panel2.Ingredient4.setState(true);
    Panel1.txtPrice.setText("Price:89.75");
}
}
}
class Menu extends Panel {
CheckboxGroup CGroup;
Checkbox Hamburger,Cheeseburger,Baconburger;
TextField txtPrice;
Label lblMenu;
Menu() {
   CGroup = new CheckboxGroup();
   lblMenu = new Label("-Burger Choices:-");
   add(lblMenu);
   add(Hamburger=new Checkbox("Hamburger",CGroup, false));
   add(Cheeseburger=new Checkbox("Cheeseburger",CGroup,false));
   add(Baconburger=new Checkbox("Baconburger",CGroup,false));
   txtPrice=new TextField(10);
   add(txtPrice);
}
}
class Ingredients extends Panel {
Checkbox Ingredient1, Ingredient2, Ingredient3, Ingredient4;
Label lblIngredient;
Ingredients() {
   lblIngredient= new Label("-Ingredients Included:-");
   add(lblIngredient);
   add(Ingredient1 = new Checkbox("Beef"));
   add(Ingredient2 = new Checkbox("Spices"));
   add(Ingredient3 = new Checkbox("Cheese"));
   add(Ingredient4 = new Checkbox("Bacon"));
}
}

2. Then save the Java program with the filename: burger1.java.
3. This time, open a new file at the NotePad to write the HTML script needed for the applet and type the following code:
Code:
<html>
<!- Web page written with Java Applet>
<head>
<title>burger1</title>
</head>
<body>
<hr>
<applet
code=burger1.class
width=220
height=150>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: burger1.htm.
5. This time, activate the Java compiler batch file with the following steps:
Type the word command at the Run menu of Windows operating system, then at the C:\> prompt, type:
C:\>cd javaprog (then press the Enter key)
C:\JAVAPROG>javap (then press the Enter key)
6. Finally, you can now compile your program with the following MS-DOS command:
C:\JAVAPROG>javac burger1.java (then press the Enter key)
7. When no error is encountered during the compilation process, you can now type the following
at your Web browser:
C:\javaprog\burger1.htm

Explanation:
Here in our example, we set up a burger e-business on the Internet. In particular, we want to embed an applet in a Web page giving potential customers the price of various burgers that we offer. In our applet, the customer selects from one of the three burger options, and we let the applet to indicate the ingredients in each burger and inform the customer a price for what they have selected. For example, if the customer clicks the Hamburger option button, we set the corresponding check boxes of ingredients to indicate what’s in this burger, then indicate the price in the text field. If the customer clicks another option button, the other check boxes are checked to indicate a new set of burger ingredients, and a new price appears in the text field. We can put the controls in our applet into two panels. Panel1 will be the Burger Choices and the text field for the Price and Panel2 will be the set of ingredient list.

We design the new panels as we did in our previous examples (about the Panel control application), by deriving a new class named, for example, Menu or Ingredients, from the Java language Panel class.First we have to declare a panel for each of the new panel classes as follows:
Code:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class burger1 extends Applet implements ItemListener {
Menu Panel1;
Ingredients Panel2;

Now, w e can create and add those panels by initializing them at the init( ) method. To make it sure that the two panels will appear side by side in our applet, we will apply the GridLayout manager to arrange them (1,2 parameter values here means we will set up two panels) as we can see in our code below:
Code:
public void init( ) {
  setLayout(new GridLayout(1,2));
  Panel1 = new Menu( );
  Panel2 = new Ingredients( );
  add(Panel1);


  Panel1.Hamburger.addItemListener(this);
  Panel1.Cheeseburger.addItemListener(this);
  Panel1.Baconburger.addItemListener(this);
  add(Panel2);
}

To make this applet functional, we need to connect it up the option buttons. We start the process by adding the ItemListener interface to our applet: We can reach the option buttons Hamburger, Cheeseburger, and Baconburger through the Panel1 object using the Java dot operator (.) as what we can see above.
Then we have to add the itemStateChange( ) method in our program to handle the option-button clicks. We need to hadle the situation in which the customer clicks the specific option button using the if condional statement. Now if a specific option button was indeed clicked, we want the check boxes to indicate what is in the burger. In this situation, we will set the check boxes appropriately in Panel2.

The check boxes are actually objects internal or belong to the Panel2 object that we have named Ingredient1 to Ingredient4. So we can reach the check boxes through Panel2 using the dot operator too. Then we can use the check box method setState( ) to set the check boxes as we want them, passing a value of true makes them appear checked, and a value of false makes them appear unchecked. Lastly, we have also place the corresponding price in the text field as you can observe in our code below:
Code:
public void itemStateChanged(ItemEvent objEvent) {
if (objEvent.getItemSelectable( )==Panel1.Hamburger) {
    Panel2.Ingredient1.setState(true);
    Panel2.Ingredient2.setState(true);
    Panel2.Ingredient3.setState(false);
    Panel2.Ingredient4.setState(false);
    Panel1.txtPrice.setText("Price:49.25");
}
if (objEvent.getItemSelectable( )==Panel1.Cheeseburger) {
    Panel2.Ingredient1.setState(true);
    Panel2.Ingredient2.setState(true);
    Panel2.Ingredient3.setState(true);
    Panel2.Ingredient4.setState(false);
    Panel1.txtPrice.setText("Price:69.50");
}
if (objEvent.getItemSelectable( )==Panel1.Baconburger) {
    Panel2.Ingredient1.setState(true);
    Panel2.Ingredient2.setState(true);
    Panel2.Ingredient3.setState(true);
    Panel2.Ingredient4.setState(true);
    Panel1.txtPrice.setText("Price:89.75");
}
}
}
We will now add the controls we need, and since this panel holds option buttons, we will need a check box group object. Finally, we will add our controls to the constructor of the new Panel class:
Code:
class Menu extends Panel {
CheckboxGroup CGroup;
Checkbox Hamburger,Cheeseburger,Baconburger;
TextField txtPrice;
Label lblMenu;
Menu( ) {            Warning! Must be unique from the previous program
   CGroup = new CheckboxGroup( );
   lblMenu = new Label("-Burger Choices:-");
   add(lblMenu);
   add(Hamburger=new Checkbox("Hamburger",CGroup, false));
   add(Cheeseburger=new Checkbox("Cheeseburger",CGroup,false));
   add(Baconburger=new Checkbox("Baconburger",CGroup,false));
   txtPrice=new TextField(10);
   add(txtPrice);
}
}
class Ingredients extends Panel {
Checkbox Ingredient1, Ingredient2, Ingredient3, Ingredient4;
Label lblIngredient;
Ingredients( ) {
   lblIngredient= new Label("-Ingredients Included:-");
   add(lblIngredient);
   add(Ingredient1 = new Checkbox("Beef"));
   add(Ingredient2 = new Checkbox("Spices"));
   add(Ingredient3 = new Checkbox("Cheese"));
   add(Ingredient4 = new Checkbox("Bacon"));
}

Example 8:
Design and develop a Java program that when the user chooses the Deluxe pizza option, the ingredients to be marked with a check are: Beef, Spices, and Cheese; its corresponding price is 149.25 (to be displayed at the text field). If the user inputs 2 in the Quantity text field, the Amount to be displayed should be 298.5, because 149 * 2 is equal to 298.5. If the quantity is 3 then the amount to be displayed is 447.75, and so on. When the user chooses the Special pizza option, the ingredients to be checked are: Beef, Spices, Cheese and Bacon; its corresponding price is 169.50. If the user inputs 2 at the Quantity text field, the Amount to be displayed is 339.0. If the input quantity is 3 then the amount to be displayed is 508.5, and so on. When the user chooses the Hawaiian pizza option, all ingredients should be marked with a check; its corresponding price is 189.75. If the user inputs 2 at the Quantity text field, the Amount to be displayed is 379.5. If the input quantity is 3 then the amount to be displayed is 569.25, and so on.
Follow the design specification below:


Solution:
1. At the Microsoft NotePad, write the following code:
Code:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class pizza1 extends Applet implements ItemListener {
Menu1 Panel1;
Ingred Panel2;
public void init() {
  setLayout(new GridLayout(1,2));
  Panel1 = new Menu1();
  Panel2 = new Ingred();
  add(Panel1);
  Panel1.chkDeluxe.addItemListener(this);
  Panel1.chkSpecial.addItemListener(this);
  Panel1.chkHawaiian.addItemListener(this);
  add(Panel2);
}
public void itemStateChanged(ItemEvent objEvent) {
int varQty;
double varAmount;
if (objEvent.getItemSelectable()==Panel1.chkDeluxe) {
    Panel2.Ingredient1.setState(true);
    Panel2.Ingredient2.setState(true);
    Panel2.Ingredient3.setState(true);
    Panel2.Ingredient4.setState(false);
    Panel2.Ingredient5.setState(false);
    Panel1.txtPrice.setText("149.25");
    varQty = Integer.parseInt(Panel1.txtQty.getText());
    varAmount = varQty * 149.25;
    Panel1.txtAmount.setText(String.valueOf(varAmount));
}
else if (objEvent.getItemSelectable()==Panel1.chkSpecial) {
    Panel2.Ingredient1.setState(true);
    Panel2.Ingredient2.setState(true);
    Panel2.Ingredient3.setState(true);
    Panel2.Ingredient4.setState(true);
    Panel2.Ingredient5.setState(false);
    Panel1.txtPrice.setText("169.50");
    varQty = Integer.parseInt(Panel1.txtQty.getText());
    varAmount = varQty * 169.50;
    Panel1.txtAmount.setText(String.valueOf(varAmount));
}
else if (objEvent.getItemSelectable()==Panel1.chkHawaiian) {
    Panel2.Ingredient1.setState(true);
    Panel2.Ingredient2.setState(true);
    Panel2.Ingredient3.setState(true);
    Panel2.Ingredient4.setState(true);
    Panel2.Ingredient5.setState(true);
    Panel1.txtPrice.setText("189.75");
    varQty = Integer.parseInt(Panel1.txtQty.getText());
    varAmount = varQty * 189.75;
    Panel1.txtAmount.setText(String.valueOf(varAmount));
}
}
}
class Menu1 extends Panel {
CheckboxGroup CGroup;
Checkbox chkDeluxe,chkSpecial, chkHawaiian;
TextField txtPrice, txtQty, txtAmount;
Label lblMenu, lblPrice,lblQty,lblAmount;
Menu1() {
   lblMenu = new Label("-Pizza Fiesta:-");
   add(lblMenu);
   CGroup = new CheckboxGroup();
   add(chkDeluxe=new Checkbox("Deluxe",CGroup, false));
   add(chkSpecial=new Checkbox("Special",CGroup,false));
   add(chkHawaiian=new Checkbox("Hawaiian",CGroup,false));
   lblPrice= new Label("Price:");
   add(lblPrice);
   txtPrice=new TextField(7);
   add(txtPrice);
   lblQty = new Label("Quantity:");
   add(lblQty);
   txtQty = new TextField(7);
   add(txtQty);
   lblAmount = new Label("Amount:");
   add(lblAmount);
   txtAmount = new TextField(7);
   add(txtAmount);
}
}
class Ingred extends Panel {
Checkbox Ingredient1, Ingredient2, Ingredient3, Ingredient4,
    Ingredient5;
Label lblIngredient;
Ingred() {
   lblIngredient = new Label("-Ingredients Included:-");
   add(lblIngredient);
   add(Ingredient1 = new Checkbox("Beef"));
   add(Ingredient2 = new Checkbox("Spices"));
   add(Ingredient3 = new Checkbox("Cheese"));
   add(Ingredient4 = new Checkbox("Bacon"));
   add(Ingredient5 = new Checkbox("Pine-apple"));
}
}

2. Then save the Java program with the filename: pizza1.java.
3. This time, open a new file at the NotePad to write the HTML script needed for the applet and type the following code:
Code:
<html>
<!- Web page written with Java Applet>
<head>
<title>pizza1</title>
</head>
<body>
<hr>
<applet
code=pizza1.class
width=220
height=300>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: pizza1.htm.
5. This time, activate the Java compiler batch file with the following steps:
Type the word command at the Run menu of Windows operating system, then at the C:\> prompt, type:
C:\>cd javaprog (then press the Enter key)
C:\JAVAPROG>javap (then press the Enter key)
6. Finally, you can now compile your program with the following MS-DOS command:
C:\JAVAPROG>javac pizza1.java (then press the Enter key)
7. When no error is encountered during the compilation process, you can now type the following
at your Web browser:
C:\javaprog\pizza1.htm

Explanation:
Try to run this program now by inputting data on the Quantity text field. Then reclick the option buttons at the Pizza Fiesta options and see what happens. You will notice that the value at the Amount text field is changing constantly.

Here in our example, we set up a pizza e-business on the Internet. In particular, we want to embed an applet in a Web page giving potential customers the price of various pizza that we offer. In our applet, the customer selects from one of the three pizza options, and we let the applet to indicate the ingredients in each pizza and inform the customer a price for what they have selected. For example, if the customer clicks the Deluxe pizza option button, we set the corresponding check boxes of ingredients to indicate what’s in this Deluxe pizza, then indicate the price in the text field. If the customer clicks another option button, the other check boxes are checked to indicate a new set of pizza ingredients, and a new price appears in the text field. Unlike in our previous example about the burger e-business, we include here in our program the option where the customers can enter how many pizza they can order and how much is the total amount to pay. In this way, they can weigh if their money is enough to pay the bills. This pizza assessment program is more flexible than the previous burger assessment program.

We can put the controls in our applet into two panels. Panel1 will be the Pizza Fiesta choices and the text field for the Price, Quantity, and Amount, then the Panel2 will be the set of ingredient list.

We design the new panels as we did in our previous examples (about the Panel control application), by deriving a new class named, for example, Menu or Ingredients, from the Java language Panel class.First we have to declare a panel for each of the new panel classes as follows:
Code:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class pizza1 extends Applet implements ItemListener {
Menu1 Panel1;
Ingred Panel2;

Now we can create and add those panels by initializing them at the init( ) method. To make it sure that the two panels will appear side by side in our applet, we will apply the GridLayout manager to arrange them (1,2 parameter values here means we will set up two panels) as we can see in our code below:
Code:
public void init( ) {
  setLayout(new GridLayout(1,2));
  Panel1 = new Menu1( );
  Panel2 = new Ingred( );
  add(Panel1);
  Panel1.chkDeluxe.addItemListener(this);
  Panel1.chkSpecial.addItemListener(this);
  Panel1.chkHawaiian.addItemListener(this);
  add(Panel2);
}

To make this applet functional, we need to connect it up the option buttons. We start the process by adding the ItemListener interface to our applet: We can reach the option buttons Deluxe, Special, and Hawaiian through the Panel1 object using the Java dot operator (.) as what we can see above.

Then we have to add the itemStateChange( ) method in our program to handle the option-button clicks. We need to hadle the situation in which the customer clicks the specific option button using the if/else if condional statements. Now if a specific option button was indeed clicked, we want the check boxes to indicate what is in the pizza, then compute the corresponding amount. In this situation, we will set the check boxes appropriately in Panel2.

The check boxes are actually objects internal or belong to the Panel2 object that we have named Ingredient1 to Ingredient4. So we can reach the check boxes through Panel2 using the dot operator too. Then we can use the check box method setState( ) to set the check boxes as we want them, passing a value of true makes them appear checked, and a value of false makes them appear unchecked. Lastly, we have to place also the corresponding price in the text field as you can observe in our code below:
Code:
public void itemStateChanged(ItemEvent objEvent) {
int varQty;
double varAmount;
if (objEvent.getItemSelectable( )==Panel1.chkDeluxe) {
    Panel2.Ingredient1.setState(true);
    Panel2.Ingredient2.setState(true);
    Panel2.Ingredient3.setState(true);
    Panel2.Ingredient4.setState(false);
    Panel2.Ingredient5.setState(false);
    Panel1.txtPrice.setText("149.25");
    varQty = Integer.parseInt(Panel1.txtQty.getText( ));
    varAmount = varQty * 149.25;
    Panel1.txtAmount.setText(String.valueOf(varAmount));
}
else if (objEvent.getItemSelectable( )==Panel1.chkSpecial) {
    Panel2.Ingredient1.setState(true);
    Panel2.Ingredient2.setState(true);
    Panel2.Ingredient3.setState(true);
    Panel2.Ingredient4.setState(true);
    Panel2.Ingredient5.setState(false);
    Panel1.txtPrice.setText("169.50");
    varQty = Integer.parseInt(Panel1.txtQty.getText());
    varAmount = varQty * 169.50;
    Panel1.txtAmount.setText(String.valueOf(varAmount));
}
else if (objEvent.getItemSelectable( )==Panel1.chkHawaiian) {
    Panel2.Ingredient1.setState(true);
    Panel2.Ingredient2.setState(true);
    Panel2.Ingredient3.setState(true);
    Panel2.Ingredient4.setState(true);
    Panel2.Ingredient5.setState(true);
    Panel1.txtPrice.setText("189.75");
    varQty = Integer.parseInt(Panel1.txtQty.getText( ));
    varAmount = varQty * 189.75;
    Panel1.txtAmount.setText(String.valueOf(varAmount));
}
}
}

Now, we will go to the details on how our program calculates the amount of pizza choosen by the customer. We have this discussion. To read the numeric data from the Quantity text field (txtQty), we apply the getText( ) method such as the following syntax:

Panel1.txtQty.getText( )

This syntax returns the text string in the text field, txtQty. For example, if the user inputs the data “2” in txtQty text field, this is actually a text string value. We need to convert it to its equivalent numeric value using the parseInt( ) method under the Integer class of the Java language such as the following syntax:

Integer.parseInt(Panel1.txtQty.getText( )

In this way, we can now store the entered numeric data from txtQty and store the result to variable varQty. This time, we can use the numeric data from varQty variable for our equation to compute the Amount of pizza with the following syntax:

varAmount = varQty * 149.25;

Now we need to convert back the numeric value stored in the varAmount into its equivalent text string so that we can display it to the text field txtAmount using the valueOf( ) method under the String class of the Java language. Here is its command syntax below:

Panel1.txtAmount.setText(String.valueOf(varAmount))

We will now add the controls we needed, and since this panel holds option buttons, we will need a check box group object. Finally, we will add our controls to the constructor of the new Panel class:
Code:
class Menu1 extends Panel {
CheckboxGroup CGroup;
Checkbox chkDeluxe,chkSpecial, chkHawaiian;
TextField txtPrice, txtQty, txtAmount;
Label lblMenu, lblPrice,lblQty,lblAmount;
Menu1( ) {            Warning! Must be unique from the previous program
   lblMenu = new Label("-Pizza Fiesta:-");
   add(lblMenu);
   CGroup = new CheckboxGroup( );
   add(chkDeluxe=new Checkbox("Deluxe",CGroup, false));
   add(chkSpecial=new Checkbox("Special",CGroup,false));
   add(chkHawaiian=new Checkbox("Hawaiian",CGroup,false));
   lblPrice= new Label("Price:");
   add(lblPrice);
   txtPrice=new TextField(7);
   add(txtPrice);
   lblQty = new Label("Quantity:");
   add(lblQty);
   txtQty = new TextField(7);
   add(txtQty);
   lblAmount = new Label("Amount:");
   add(lblAmount);
   txtAmount = new TextField(7);
   add(txtAmount);
}
}
class Ingred extends Panel {
Checkbox Ingredient1, Ingredient2, Ingredient3, Ingredient4,
    Ingredient5;
Label lblIngredient;
Ingred( ) {
   lblIngredient = new Label("-Ingredients Included:-");
   add(lblIngredient);
   add(Ingredient1 = new Checkbox("Beef"));
   add(Ingredient2 = new Checkbox("Spices"));
   add(Ingredient3 = new Checkbox("Cheese"));
   add(Ingredient4 = new Checkbox("Bacon"));
   add(Ingredient5 = new Checkbox("Pine-apple"));
}
}

That’s the end of our discussion in this chapter. And I’m sure, you are now ready to answer the Lab Activity Test that will follow. Good luck!

Warning!
We have to rename the class name of our Menu to Menu1 in pizza e-business program to prevent a conflict in our previous burger e-business program which already contain the Menu class. With the Panel class application, we have to take note that the Menu class name must be unique for each program that we make, so that the previous class name cannot be used by the second program This is the main reason why our second program is a “look-a-like” in our previous program because of the similar class name that we accidentally and repeatedly used.

QagqXaT.png


Java Lecture Pages
 
Last edited by a moderator:

Similar threads


Top Bottom