Java Lecture Chapter 3

Marvic

Member
Using Controls with Input / Output Functions

The ParseInt( ) and valueOf( ) Methods

In calculating and displaying data in our applet, we need to know how they can be manipulated using the most important methods : ParseInt( ) and valueOf( ).

These two methods simply convert our data from numeric to string data or vise versa. The ParseInt( ) method converts the displayed data into numeric, while the valueOf( ) method converts the displayed data into string data.

The ParseInt( ) method is under the Java Integer class that takes text string and returns a numeric integer value. For example, we can get the text string in the text field txtText1 this way:

txtText1.getText( )

And we can convert that text string to a numeric integer value this way:

Integer.parseInt(txtText1.getText( ))

Now to convert a numeric value into a text string so that we can display it in the text field, we need to apply the valueOf( ) method under the Java String class too. For example, we can display the numeric value from the variable varArea this way:

varArea = 3.1416 * (varRadius*varRadius);
txtArea.setText(String.valueOf(varArea));

To explain it further, the parseInt ( ) method is applied when we want to calculate the numeric integer data displayed in text field. Now if we want to display the computed data into the text field, we need to convert it into a string using the valueOf( ) method. We need to apply the parseInt ( ) method so that the numbers that are being entered in the text field can be converted to numeric integer data for computation purposes in our equation or formula, otherwise these numbers are treated as text string which cannot be calculated or processed in the equation. We need also to convert the numeric data into its equivalent text string data representation using the valueOf( ) method for the proper display of the numbers into the text field control. Without doing so, it will result to an undesired output. Let us have an example for this application, sooner.

Label control
In this chapter, I will introduce another useful and handy control which we will use extensively in our upcoming programs. It is the Label control that displays read-only text which main function is to provide information to the user. This can be in the form of a message shown on the applet or a prompt. A message such as labeling an output data of what it is, or telling the user what kind of data to input.

This Label application is usually with the conjunction of a text field that holds the input or output data. Like for example, that the numeric output in the text box is the Area of a circle or a Fahrenheit degree. Or simply telling the user to enter a numeric data for calculation or a character to process.

The Label as a prompt is usually combined with a a text field, scrolling list, choice control, or other controls. It provides the user an idea of that nature of the referenced control. For instance, if we had a scrolling list that contains the abbreviated different states in America. We can put a label at the top of the scrolling list that tells about the abbreviations.

Basic Data Types of Java
I’m also introducing here another important elements of our program. And it is how to use variables and assigned a data type on it. A data type simply defines what type of data a particular variable should hold or contain. Each piece of data is assigned a data type. When we are designing and developing programs, we think about the name of variables to use and decide what data type to assign to them. To explain it further, a data type is a category of data. Each variable can only hold one type of data at a time.

So what is a variable? Variables are memory location (address) which we can assign a specific name. For example we can name our variables as varNo, varSum or varArea. We can assign or store a value(data) to the variable. Here are the basic data types of Java programming language:

Data Type Meaning
int An integer data type is a whole number. This number could be positive or negative.
Examples: 9 -67 +978 3008
long Just a long integer data type that can accommodate more digits of data.

float A floating point data type is a number with fractional part or a number with decimal point.
Examples: 1.0 99.99 +2.54 -100
Double A double precision floating point value and can accommodate more digits of data.

char A character data type is a single letter, a special symbol or digit that is enclosed within a single quotation marks. Examples: ‘a’ ‘Z’ ‘*’ ‘%’ ‘5’, ‘1’

String A string data type is a sequence of two or more characters that are enclosed within a double quotation marks. Examples: “Ms” “I love you, Bianca!” “PS”

Boolean A Boolean data type takes a true or false values. Examples: Obj.setState(true)
new Obj(“Label 1”, GroupA, false)
byte Can only hold a byte of data or a tiny data.


Example 1:
Design and develop a Java program that calculates the sum of two input numbers. 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 sum1 extends Applet implements ActionListener {
  TextField txtNum1, txtNum2, txtSum;
  Label lblPlus;
  Button cmdEqual;
  public void init() {
    txtNum1 = new TextField(7);
       add(txtNum1);
       lblPlus = new Label("+");
       add(lblPlus);
        txtNum2 = new TextField(7);
       add(txtNum2);
        cmdEqual= new Button("=");
       add(cmdEqual);
       cmdEqual.addActionListener(this);
       txtSum = new TextField(7);
       add(txtSum);
  }
  public void actionPerformed(ActionEvent objEvent) {
  int varSum=0;
    if (objEvent.getSource() == cmdEqual) {
     varSum = Integer.parseInt(txtNum1.getText()) +
           Integer.parseInt(txtNum2.getText());
     txtSum.setText(String.valueOf(varSum));
    }
  }
}

2. Then save the Java program with the filename: sum1.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>sum1</title>
</head>
<body>
<hr>
<applet
code=sum1.class
width=200
height=200>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: sum1.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 sum1.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\sum1.htm

Explanation:
We place the plus sign (+) on the applet using the Label control as you can see in our code below:
Code:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class sum1 extends Applet implements ActionListener {
  TextField txtNum1, txtNum2, txtSum;
  Label lblPlus;
  Button cmdEqual;

The next thing we do is to initialize this label control in the init ( ) method, like the way we do with other controls as you can observe in our code below:
Code:
  public void init() {
    txtNum1 = new TextField(7);
       add(txtNum1);
       lblPlus = new Label("+");
       add(lblPlus);
        txtNum2 = new TextField(7);
       add(txtNum2);
        cmdEqual= new Button("=");
       add(cmdEqual);
       cmdEqual.addActionListener(this);
       txtSum = new TextField(7);
       add(txtSum);
  }

The label control will simply display text on the applet and nothing else. We can set the text string of a label control the same way we do with the text field. And it is by using the setText( ) method.

We can make the program to compute the sum of two input numbers by implementing the ActionListener interface, and connect our command button (cmdEqual) to it. Then finally add the actionPerformed ( ) method to complete the process:
Code:
  public void actionPerformed(ActionEvent objEvent) {
  int varSum=0;
    if (objEvent.getSource() == cmdEqual) {
     varSum = Integer.parseInt(txtNum1.getText( )) +
           Integer.parseInt(txtNum2.getText( ));
     txtSum.setText(String.valueOf(varSum));
    }
  }
}

When the command button (cmdEqual) is clicked, we instruct the computer to read the numeric data entered by the user in the two text fields, txtNum1 and txtNum2. To read the numeric data from the text field, we apply the getText( ) method such as the following syntax:

txtNum1.getText( )

This syntax returns the text string in the text field, txtNum1. For example, if the user inputs the data “5” in txtNum1 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(txtNum1.getText( ))

In this way, we can now add the two numeric data entered by the user from text field 1 txtNum1 and text field txtNum2 and store the result to variable varSum. Now we need to convert back the numeric value stored in the varSum into text string so that we can display it to the text field

txtSum, using the valueOf( ) method under the String class of the Java language such as the following syntax:

txtSum.setText(String.valueOf(varSum));

I think we have already gone too far for what we have learned. This is the right time to learn more about these input/output functions of Java language to feel more comfortable working with them.


Example 2:
Design and develop a Java program that computes the area of a circle. Use the formula: A = r2 where Pi () is approximately equivalent to 3.1416. Follow the design specification below:

Figure 3.2 An applet that computes the area of a circle

Solution:
1. At the Microsoft NotePad, write the following code:
Code:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class area1 extends Applet implements ActionListener {
  TextField txtRadius, txtArea;
  Label lblRadius, lblArea;
  Button cmdCompute;
    public void init() {
      lblRadius = new Label("Enter the radius:");
      add(lblRadius);
      txtRadius = new TextField(4);
      add(txtRadius);
      cmdCompute= new Button("Compute");
      add(cmdCompute);
      lblArea = new Label("Area of a circle:");
      add(lblArea);
      txtArea = new TextField(7);
      add(txtArea);
      cmdCompute.addActionListener(this);
  }
  public void actionPerformed(ActionEvent objEvent) {
  int varRadius=0;
  double varArea = 0;
    if (objEvent.getSource() == cmdCompute) {
     varRadius = Integer.parseInt(txtRadius.getText());
     varArea = 3.1416 * (varRadius*varRadius);       
     txtArea.setText(String.valueOf(varArea));
    }
  }
}

2. Then save the Java program with the filename: area1.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>area1</title>
</head>
<body>
<hr>
<applet
code=area1.class
width=250
height=150>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: area1.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 area1.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\area1.htm

Explanation:
We place the label “Enter the radius:” and “Area of a circle:” on the applet using the Label control as you can see in our code below:
Code:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class area1 extends Applet implements ActionListener {
  TextField txtRadius, txtArea;
  Label lblRadius, lblArea;
  Button cmdCompute;

The next thing we do is to initialize these label controls in the init ( ) method, like the way we do with other controls as you can observe in our code below:
Code:
    public void init( ) {
         lblRadius = new Label("Enter the radius:");
       add(lblRadius);
        txtRadius = new TextField(4);
       add(txtRadius);
       cmdCompute= new Button("Compute");
       add(cmdCompute);
       lblArea = new Label("Area of a circle:");
       add(lblArea);
       txtArea = new TextField(7);
       add(txtArea);
       cmdCompute.addActionListener(this);
  }

The label control will simply display text on the applet and nothing else. We can set the text string of a label control the same way we do with text field by using the setText( ) method.
We can make the program to compute the sum of two input numbers by implementing the ActionListener interface, and connect our command button (cmdCompute) to it. Then finally add the actionPerformed ( ) method to complete the process:
Code:
  public void actionPerformed(ActionEvent objEvent) {
  int varRadius=0;
  double varArea = 0;
    if (objEvent.getSource( )  == cmdCompute) {
     varRadius = Integer.parseInt(txtRadius.getText( ));
     varArea = 3.1416 * (varRadius*varRadius);       
     txtArea.setText(String.valueOf(varArea));
    }
  }
}

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

txtRadius.getText( )

This syntax returns the text string in the text field, txtRadius. For example, if the user inputs the data “3” in txtRadius 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(txtRadius.getText( ))

In this way, we can now calculate the numeric data of the radius entered by the user from text field txtRadius and store it to variable varRadius. We can now use the stored value of the variable varRadius in our equation since it is already a numeric data using the following equation:

varArea = 3.1416 * (varRadius*varRadius);

Now we need to convert back the numeric value stored in the varArea into text string so that we can display it to the text field txtArea, using the valueOf( ) method under the String class of the Java language such as the following syntax:

txtArea.setText(String.valueOf(varArea));

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 radius:” , the text field used for entering the data and command button Compute (cmdCompute) 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=area1.class
width=250
height=150>
</applet>


Example 3:
Design and develop a Java program that computes the average of three input quizzes. Then display the result. 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 average1 extends Applet implements ActionListener {
  TextField txtQuiz1, txtQuiz2, txtQuiz3, txtAve;
  Label lblQuiz, lblAve;
  Button cmdCompute;
   public void init() {
      lblQuiz = new Label("Enter three quizzes:");
       add(lblQuiz);
       txtQuiz1 = new TextField(3);
       add(txtQuiz1);
       txtQuiz2 = new TextField(3);
       add(txtQuiz2);
       txtQuiz3 = new TextField(3);
       add(txtQuiz3);
       cmdCompute= new Button("Compute");
       add(cmdCompute);
       lblAve = new Label("The average quiz is:");
       add(lblAve);
       txtAve = new TextField(7);
       add(txtAve);
       cmdCompute.addActionListener(this);
  }
  public void actionPerformed(ActionEvent objEvent) {
  int varQuiz1, varQuiz2, varQuiz3;
  double varAve = 0;
    if (objEvent.getSource() == cmdCompute) {
     varQuiz1 = Integer.parseInt(txtQuiz1.getText());
     varQuiz2 = Integer.parseInt(txtQuiz2.getText());
     varQuiz3 = Integer.parseInt(txtQuiz3.getText());
     varAve = (varQuiz1+varQuiz2+varQuiz3)/3;       
     txtAve.setText(String.valueOf(varAve));
    }
  }
}

2. Then save the Java program with the filename: average1.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>average1</title>
</head>
<body>
<hr>
<applet
code=average1.class
width=150
height=150>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: average1.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 average1.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\average1.htm

Explanation:
We place the label “Enter the radius:” and “Area of a circle:” on the applet using the Label control as you can see in our code below:
Code:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class average1 extends Applet implements ActionListener {
  TextField txtQuiz1, txtQuiz2, txtQuiz3, txtAve;
  Label lblQuiz, lblAve;
  Button cmdCompute;

The next thing we do is to initialize these label controls in the init ( ) method, like the way we do with other controls as you can observe in our code below:
Code:
   public void init( ) {
      lblQuiz = new Label("Enter three quizzes:");
       add(lblQuiz);
       txtQuiz1 = new TextField(3);
       add(txtQuiz1);
       txtQuiz2 = new TextField(3);
       add(txtQuiz2);
       txtQuiz3 = new TextField(3);
       add(txtQuiz3);
       cmdCompute= new Button("Compute");
       add(cmdCompute);
       lblAve = new Label("The average quiz is:");
       add(lblAve);
       txtAve = new TextField(7);
       add(txtAve);
       cmdCompute.addActionListener(this);
  }

The label control will simply display text on the applet and nothing else. We can set the text string of a label control the same way we do with text field by using the setText( ) method.
We can make the program to compute the sum of two input numbers by implementing the ActionListener interface, and connect our command button (cmdCompute) to it. Then finally add the actionPerformed ( ) method to complete the process:
Code:
  public void actionPerformed(ActionEvent objEvent) {
  int varQuiz1, varQuiz2, varQuiz3;
  double varAve = 0;
    if (objEvent.getSource() == cmdCompute) {
     varQuiz1 = Integer.parseInt(txtQuiz1.getText( ));
     varQuiz2 = Integer.parseInt(txtQuiz2.getText( ));
     varQuiz3 = Integer.parseInt(txtQuiz3.getText( ));
     varAve = (varQuiz1+varQuiz2+varQuiz3)/3;       
     txtAve.setText(String.valueOf(varAve));
    }
  }
}

When the command button Compute (cmdCompute) is clicked, we instruct the computer to read the numeric data entered by the user in the three text fields, txtQuiz1, txtQuiz2, and txtQuiz3. To read the numeric data from the text field, we apply the getText( ) method such as the following syntax:

txtQuiz1.getText( )

This syntax returns the text string in the text field, txtQuiz1. For example, if the user inputs the data “91” in txtQuiz1 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(txtQuiz1.getText( ))

In this way, we can now calculate the numeric data of the quiz 1 entered by the user from text field txtQuiz1 and store it to variable varQuiz1. We can now use the stored value of the variable varQuiz1 (as well as varQuiz2 and varQuiz3) in our equation since it is already a numeric data using the following equation:

varAve = (varQuiz1+varQuiz2+varQuiz3)/3;

Now we need to convert back the numeric value stored in the varAve into text string so that we can display it to the text field txtAve, using the valueOf( ) method under the String class of the Java language such as the following syntax:

txtAve.setText(String.valueOf(varAve));

You will notice here that we decrease the applet’s width to 150 and decrease the height to 150 (as you can see in the HTML script below), because we want to accommodate the label “Enter three quizzes:”, to be displayed at the top portion in the applet then followed by the text fields used for entering the three quizzes in the second line and command button Compute (cmdCompute) to be displayed right below the three text fields, then followed by the next label, “The average is:” and finally the last text field which is used to display the computed average quiz. With this adjustment, these controls will be displayed in the applet properly.
Code:
<applet
code=average1.class
width=150
height=150>
</applet>

Example 4:
Design and develop a Java program that converts the input value of Celsius into its equivalent Fahrenheit degree. Use the formula: F = (9/5) * C + 32. Then display the result. 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 degree1 extends Applet implements ActionListener {
  TextField txtCelsius, txtFahrenheit;
  Label lblCelsius, lblFahrenheit;
  Button cmdCompute;
  public void init() {
     lblCelsius = new Label("Enter the Celsius:");
     add(lblCelsius);
     txtCelsius = new TextField(4);
     add(txtCelsius);
     cmdCompute= new Button("Compute");
     add(cmdCompute);
     cmdCompute.addActionListener(this);
     lblFahrenheit = new Label("Fahrenheit conversion is:");
     add(lblFahrenheit);
     txtFahrenheit = new TextField(8);
     add(txtFahrenheit);
   }
  public void actionPerformed(ActionEvent objEvent) {
  int varCelsius=0;
  double varFahrenheit = 0;
    if (objEvent.getSource() == cmdCompute) {
     varCelsius = Integer.parseInt(txtCelsius.getText());
     varFahrenheit = (9.0/5.0) * (varCelsius + 32.0);       
     txtFahrenheit.setText(String.valueOf(varFahrenheit));
    }
  }
}

2. Then save the Java program with the filename: degree1.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>degree1</title>
</head>
<body>
<hr>
<applet
code=degree1.class
width=250
height=150>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: degree1.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 degree1.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\degree1.htm
Explanation:
We place the label “Enter the Celsius:” and “The Fahrenheit conversion is:” on the applet using the Label control as you can see in our code below:
Code:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class degree1 extends Applet implements ActionListener {
  TextField txtCelsius, txtFahrenheit;
  Label lblCelsius, lblFahrenheit;
  Button cmdCompute;

The next thing we do is to initialize these label controls in the init ( ) method, like the way we do with other controls as you can observe in our code below:
Code:
  public void init( ) {
       lblCelsius = new Label("Enter the Celsius:");
       add(lblCelsius);
       txtCelsius = new TextField(4);
       add(txtCelsius);
        cmdCompute= new Button("Compute");
       add(cmdCompute);
       cmdCompute.addActionListener(this);
        lblFahrenheit = new Label("Fahrenheit conversion is:");
       add(lblFahrenheit);
       txtFahrenheit = new TextField(8);
       add(txtFahrenheit);
   }

The label control will simply display text on the applet and nothing else. We can set the text string of a label control the same way we do with text field by using the setText( ) method.
We can make the program to compute the sum of two input numbers by implementing the ActionListener interface, and connect our command button (cmdCompute) to it. Then finally add the actionPerformed ( ) method to complete the process:
Code:
  public void actionPerformed(ActionEvent objEvent) {
  int varCelsius=0;
  double varFahrenheit = 0;
    if (objEvent.getSource( ) == cmdCompute) {
     varCelsius = Integer.parseInt(txtCelsius.getText( ));
     varFahrenheit = (9.0/5.0) * (varCelsius + 32.0);       
       txtFahrenheit.setText(String.valueOf(varFahrenheit));
      }
  }
}

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

txtCelsius.getText( )

This syntax returns the text string in the text field, txtCelsius. For example, if the user inputs the data “19” in txtCelsius 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(txtCelsius.getText( ))
In this way, we can now calculate the numeric data of the radius entered by the user from text field txtCelsius and store it to variable varCelsius. We can now use the stored value of the variable varCelsius in our equation since it is already a numeric data using the following equation:

varFahrenheit = (9.0/5.0) * (varCelsius + 32.0);

Now we need to convert back the numeric value stored in the varFahrenheit into text string so that we can display it to the text field txtFahrenheit, using the valueOf( ) method under the String class of the Java language such as the following syntax:

txtFahrenheit.setText(String.valueOf(varFahrenheit)

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 Celsius:” , the text field used for entering the data and command button Compute (cmdCompute) 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=degree1.class
width=250
height=150>
</applet>



Java Lecture Pages
 

Similar threads


Latest posts

Top Bottom