Java Reference
In-Depth Information
2.1 Introduction
The focus of this chapter is on learning elementary programming techniques to solve
problems.
Key
Point
In Chapter 1 you learned how to create, compile, and run very basic Java programs. Now you
will learn how to solve problems by writing programs. Through these problems, you will learn
elementary programming using primitive data types, variables, constants, operators, expres-
sions, and input and output.
Suppose, for example, that you need to take out a student loan. Given the loan amount, loan
term, and annual interest rate, can you write a program to compute the monthly payment and
total payment? This chapter shows you how to write programs like this. Along the way, you
learn the basic steps that go into analyzing a problem, designing a solution, and implementing
the solution by creating a program.
2.2 Writing a Simple Program
Writing a program involves designing a strategy for solving the problem and then
using a programming language to implement that strategy.
Key
Point
Let's first consider the simple problem of computing the area of a circle. How do we write a
program for solving this problem?
Writing a program involves designing algorithms and translating algorithms into pro-
gramming instructions, or code. An algorithm describes how a problem is solved by listing
the actions that need to be taken 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 (natural language mixed with some program-
ming code). The algorithm for calculating the area of a circle can be described as follows:
problem
algorithm
pseudocode
1. Read in the circle's radius.
2. Compute the area using the following formula:
=
*
* p
area
radius
radius
3. Display the result.
Tip
It's always good practice to outline your program (or its underlying problem) in the form
of an algorithm before you begin coding.
When you code —that is, when you write a program—you translate an algorithm into a pro-
gram. You already know that every Java program begins with a class definition 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
}
As you know, every Java program must have a main method where program execution
begins. The program is then expanded as follows:
public class ComputeArea {
public static void main(String[] args) {
// Step 1: Read in radius
// Step 2: Compute area
 
 
 
 
Search WWH ::




Custom Search