top of page

Writing Simple Programs          Reading Input from the Console        

THU JUN 14 2018 [SECOND PERIOD]

LECTURE 2

2.1   INTRODUCTION

We will attempt to solve practical problems programmatically in this section, to get to know the elementary programming using primitive data types, variables, constants, operators, expressions, and input and output.

2.2   WRITING A SIMPLE PROGRAM

Writing a program involves designing algorithms and translating algorithms into code.  An algorithm describes how a problem is solved in terms of the actions to be executed and the order of their execution.  Algorithms can help the programmer plan a program before writing it in a programming language.  Algorithms can be described in natural languages or in pseudocode (i.e., natural language mixed with programming code).  The algorithm for this program can be described as follows:

  1. Read in the radius.

  2. Compute the area using the following formula:

   3. Display the area.

Many of the problems you will encounter when taking an introductory course in programming can be described with simple, straightforward algorithms.  When you code, you translate an algorithm into a program.  You already know that every Java program begins with a class declaration in which the keyword class is followed by the class name.  Assume that you have chosen ComputeArea as the class name.  The outline of the program would look like this:

public class ComputeArea {
     // Details to be given later
}

Console 1.1 - Problem Algorithm Construction - Program Idea

As you know, every Java program must have a main method where program execution begins.  So the program is expanded as follows:

public class ComputeArea {
     public static void main(String[] args) {
          // Step 1: Read in radius
          // Step 2: Compute area
          // Step 3: Display the area
     }
}

Console 1.2 - Problem Algorithm Construction - Program Expansion

The program needs to read the radius entered by the user from the keyboard.  This raises two important issues:

  • Reading the radius

  • Storing the radius in the program

In order to store the radius, the program needs to declare a symbol called a variable.  A variable designates a location in memory for storing data and computational results in the program.  A variable has a name that can be used to access the memory location.

Rather than using x and y as variable names, choose descriptive names: in this case, radius for radius, and area for area.  To let the compiler know what radius and area are, specify their data types.  Java provides simple data types for representing integers, floatingpoint numbers (i.e., numbers with a decimal point), characters, and Boolean types.  These types are known as primitive data types or fundamental types.  Declare radius and area as double-precision floating-point numbers.  The program can be expanded as follows:

public class ComputeArea {
     public static void main(String[] args) {
          double radius;
          double area;
          // Step 1: Read in radius
          // Step 2: Compute area
          // Step 3: Display the area
     }
}

Console 1.3 - Problem Algorithm Construction - Program Further Expansion

The program declares radius and area as variables.  The reserved word double indicates that radius and area are double-precision floating-point values stored in the computer.  The first step is to read in radius.  We would learn how to read in data from the keyboard later.  For the time being, let us assign a fixed value to radius in the program.  The second step is to compute area by assigning the result of the expression radius * radius * 3.14159 to area.
In the final step, display area on the console by using the System.out.println method.  The complete program is shown in Listing 2.1.

Variables such as radius and area correspond to memory locations.  Every variable has a name, a type, a size, and a value.  Line 3 declares that radius can store a double value.  The value is not defined until you assign a value.  Line 7 assigns 20 into radius.  Similarly, line 4 declares variable area, and line 10 assigns a value into area.

The plus sign (+) has two meanings: one for addition and the other for concatenating strings.  The plus sign (+) in lines 13–14 is called a string concatenation operator.  It combines two strings if two operands are strings.  If one of the operands is a nonstring (e.g., a number), the nonstring value is converted into a string and concatenated with the other string.  So the plus signs (+) in lines 13–14 concatenate strings into a longer string, which is then displayed in the output.

2.3   READING INPUT FROM THE CONSOLE

We will use the Scanner class for console input.  Java uses System.out to refer to the standard output device and System.in to the standard input device.  By default the output device is the display monitor, and the input device is the keyboard.  To perform console output, you simply use the println method to display a primitive value or a string to the console.  Console input is not directly supported in Java, but you can use the Scanner class to create an object to read input from System.in, as follows:

 

            Scanner input = new Scanner(System.in);


The syntax new Scanner(System.in) creates an object of the Scanner type.  The syntax Scanner input declares that input is a variable whose type is Scanner.  The whole line Scanner input = new Scanner(System.in) creates a Scanner object and assigns its reference to the variable input.  An object may invoke its methods.  To invoke a method on an object is to ask the object to perform a task.  You can invoke the methods in Table 2.1 to read various types of input.

For now, we will see how to read a number that includes a decimal point by invoking the nextDouble() method.  Other methods will be covered when they are used.  Listing 2.2 rewrites Listing 2.1 to prompt the user to enter a radius.

The Scanner class is in the java.util package.  It is imported in line 1. Line 6 creates a Scanner object.  The statement in line 9 displays a message to prompt the user for input.  System.out. ("Enter a number for radius: ");  The print method is identical to the println method except that println moves the cursor to the next line after displaying the string, but print does not advance the cursor to the next line when completed.  The statement in line 10 reads an input from the keyboard.  double radius = input.nextDouble();  After the user enters a number and presses the Enter key, the number is read and assigned to radius.  Use the next listing as an example for finding the average of three numbers that are entered by the user.

The code for importing the Scanner class (line 1) and creating a Scanner object (line 6) are the same as in the preceding example as well as in all new programs you will write.  Line 9 prompts the user to enter three numbers.  The numbers are read in lines 10–12.  You may enter three numbers separated by spaces, then press the Enter key, or enter each number followed by a press of the Enter key.

2.4     IDENTIFIERS
As you see in Listing 2.3, ComputeAverage, main, input, number1, number2, number3, and so on are the names of things that appear in the program.  Such names are called identifiers.  All identifiers must obey the following rules:

  • An identifier is a sequence of characters that consists of letters, digits, underscores (_), and dollar signs ($).

  • An identifier must start with a letter, an underscore (_), or a dollar sign ($).  It cannot start with a digit.

  • An identifier cannot be a reserved word.  (See list of Reserved Words).

  • An identifier cannot be true, false, or null.

  • An identifier can be of any length.

For example, $2, ComputeArea, area, radius, and showMessageDialog are legal identifiers, whereas 2A and d+4 are not because they do not follow the rules.  The Java compiler detects illegal identifiers and reports syntax errors.  Since Java is case sensitive, area, Area, and AREA are all different identifiers.  Identifiers are for naming variables, constants, methods, classes, and packages.  Descriptive identifiers make programs easy to read.  Do not name identifiers with the $ character.  By convention, the $ character should be used only in mechanically generated source code.

2.5     VARIABLES

As you see from the programs in the preceding sections, variables are used to store values to be used later in a program.  They are called variables because their values can be changed.  In the program in Listing 2.2, radius and area are variables of double-precision, floatingpoint type.  You can assign any numerical value to radius and area, and the values of radius and area can be reassigned.  For example, you can write the code shown below to compute the area for different radii:

Variables are for representing data of a certain type.  To use a variable, you declare it by telling the compiler its name as well as what type of data it can store.  The variable declaration tells the compiler to allocate appropriate memory space for the variable based on its data type.  The syntax for declaring a variable is datatype variableName;  Here are some examples of variable declarations:

The examples use the data types int, double, and char.  Later you will be introduced to additional data types, such as byte, short, long, float, char, and boolean.  If variables are of the same type, they can be declared together, as follows:

datatype variable1, variable2, ..., variablen;  The variables are separated by commas.  For example,

Lesson 3
bottom of page