• No results found

Programming exercises

Chapter 3 Expressions

3.5 Programming idioms and patterns

Before the invention of writing, history and religion passed from generation to generation as part of an oral tradition. The Iliad and The Odyssey of Homer, the Vedic literature of India, the Old Norse mythologies, the sermons and songs that kept African traditions alive through centuries of slavery—all are examples of an oral tradition. These works are characterized by the patterned repetition of phrases, which make it easier for singers, preachers, and storytellers to remember them. These repeated patterns, called formulas, provide the memory cues that make it possible to remember and make variations on a long and detailed story.

In its entirety, Java is itself a long and detailed story with many rules and techniques to remember. Even so, as you write your programs, you will notice that many formulaic structures come up repeatedly, just like the formulas in oral tradition. If you learn to recognize these formulas and think of them as conceptual units, you will soon discover that there is less to remember about programming in Java than you might have thought. In programming, such formulas are called programming idioms or programming patterns. To write programs effectively, you must learn how to apply these programming patterns to the task at hand. Eventually, you should be able to do so without devoting any conscious attention to the process. A general idea will come into your mind as part of a solution strategy, and you will automatically translate that idea into the appropriate pattern as you compose the program.

One of the most common patterns in Java consists of shorthand forms for certain frequently occurring assignment statements. In Java, you will find that you often change a variable by adding something to its current value, subtracting something from it, or some similar operation. For example, if you were writing a program to balance your checkbook, you might expect to use following assignment statement:

balance = balance + deposit;

This statement adds the value in the variable deposit to the current value of the variable balance, leaving the result in balance. In more colloquial English, the effect of this statement can be summarized as “add deposit to balance.”

Although the statement

balance = balance + deposit;

has the desired effect, it is not the statement that a Java programmer would usually write. Statements that perform some operation on a variable and then store the result back in that same variable occur so frequently in programming that the designers of C—from

which Java’s expression structure is derived—included an idiomatic shorthand for it. For any binary operator op, the statement

variable = variable op expression;

can be replaced by

variable op= expression;

The combination of an operator with the = used for assignment form is called a shorthand assignment operator.

Using the shorthand assignment operator for addition, the more common form of the statement

balance = balance + deposit; is therefore

balance += deposit;

which means, in English, “add deposit to balance.”

Because this same shorthand applies to any binary operator in Java, you can subtract the value of surcharge from balance by writing

balance -= surcharge; divide the value of x by 10 using

x /= 10;

or double the value of salary by using salary *= 2;

Beyond the shorthand assignment operators, Java offers a further level of abbreviation for two particularly common programming operations—adding or subtracting 1 from a variable. Adding 1 to a variable is called incrementing that variable; subtracting 1 is called decrementing that variable. To indicate these operations in an extremely compact form, Java provides the operators ++ and --. For example, the statement

x++;

has the same ultimate effect as x += 1;

which is itself short for x = x + 1;

Similarly, y--;

has the same effect as y -= 1; or

y = y - 1;

The ++ and -- operators occur all the time in Java programs and are actually more complex in their operation than this presentation suggests. The form shown here, however, is sufficient for you to understand how these operators are used in the standard statement forms introduced in Chapter 4.

Summary

In this chapter, you have had the opportunity to learn about expressions in Java programs and how they work. Important points introduced in the chapter include:

• Data values come in many different types, each of which is defined by a domain and a

set of operations.

Constants are used to specify values that do not change within a program.

Variables have three attributes: a name, a value, and a type. All variables used in a Java program must be declared, which establishes the name and type of the variable. • You can use class variables to associate names with constants. Such declarations are

written outside of any method and include the keywords static and final.

• Expressions are composed of individual terms connected by operators. The subexpressions to which an operator applies are called its operands.

• When an operator is applied to two operands of type int, the result is also of type int. If either or both operands are of type double, so is the result.

• If the / operator is applied to two integers, the result is the integer obtained by dividing the first operand by the second and then throwing the remainder away. The remainder can be obtained by using the % operator.

• The order of operations in an expression is determined by rules of precedence. The operators introduced so far fall into three precedence classes:

unary - (type cast) (highest)

* / %

+ - (lowest)

For the binary operators introduced so far, whenever two operators from the same precedence class compete for the same operand, those operators are applied in left-to- right order.

• Automatic conversion between numeric types occurs when values of different types are combined in an expression or when an assignment is performed to a variable of a more general type.

• Variables are given values through the use of assignment statements. Each variable can hold only one value at a time; when a variable is assigned a new value, any previous value is lost.

• Java includes a shorthand form of the assignment statement in which the statement

variable = variable op expression; can be replaced by

variable op= expression;

• Java includes special operators ++ and --, which specify adding and subtracting 1 from a variable, respectively.

Review questions

1. What are the two attributes that define a data type?

2. Identify which of the following are legal constants in Java. For the ones that are legal, indicate whether they are integers or floating-point constants.

a) 42 g) 1,000,000 b) -17 h) 3.1415926 c) 2+3 i) 123456789 d) -2.3 j) 0.000001 e) 20 k) 1.1E+11 f) 2.0 l) 1.1X+11

3. Rewrite the following floating-point constants in Java’s form for scientific notation: a) 6.02252x1023

b) 29979250000.0 c) 0.00000000529167 d) 3.1415926535

(By the way, each of these constants represents an approximation of an important value from chemistry, physics, or mathematics: (a) Avogadro’s number, (b) the speed of light in centimeters per second, (c) the Bohr radius in centimeters, and (d) the mathematical constant π. In the case of π, there is no advantage in using the scientific notation form, but it is nonetheless possible and you should know how to do so.)

4. Indicate which of the following are legal variable names in Java:

a) x g) total output b) formula1 h) aReasonablyLongVariableName c) average_rainfall i) 12MonthTotal d) %correct j) marginal-cost e) short k) b4hand f) tiny l) _stk_depth

5. Indicate the values and types of the following expressions:

a) 2 + 3 d) 3 * 6.0

b) 19 / 5 e) 19 % 5

c) 19.0 / 5 f) 2 % 7

6. What is the difference between the unary minus operator and the binary subtraction operator?

7. By applying the appropriate precedence rules, calculate the result of each of the following expressions:

a) 6 + 5 / 4 - 3

b) 2 + 2 * (2 * 2 - 2) % 2 / 2

c) 10 + 9 * ((8 + 7) % 6) + 5 * 4 % 3 * 2 + 1 d) 1 + 2 + (3 + 4) * ((5 * 6 % 7 * 8) - 9) - 10

8. If the variable k is declared to be of type int, what value does k contain after the program executes the assignment statement

k = (int) 3.14159;

What value would k contain after the assignment statement k = (int) 2.71828;

9. In Java, how do you specify conversion between numeric types?

10. What idiom would you use to multiply the value of the variable cellCount by 2? 11. What is the most common way in Java to write a statement that has the same effect

as the statement x = x + 1;

Programming exercises

1. Extend the InchesToCentimeters program given in Figure 3-2 so that it reads in two input values: the number of feet, followed on a separate line by the number of inches. Here is a sample run of the program:

FeetAndInchesToCentimeters

This program converts feet and inches to centimeters. Enter number of feet: 5

Enter number of inches: 11

2. Write a program that reads in two numbers: an account balance and an annual interest rate expressed as a percentage. Your program should then display the new balance after a year. There are no deposits or withdrawals—just the interest payment. Your program should be able to reproduce the following sample run:

Interest

Interest calculation program Enter starting balance: 6000

Enter annual interest rate: 4.25

Balance after one year = 6255.0

3. Extend the program you wrote in Exercise 2 so that it also displays the balance after two years have elapsed, as shown in the following sample run:

Interest2

Interest calculation program Enter starting balance: 6000

Enter annual interest rate: 4.25

Balance after one year = 6255.0 Balance after two years = 6520.84

Note that the interest used in this example is compounded annually, which means the interest from the first year is added back to the bank balance and is therefore itself subject to interest in the second year. In the first year, the $6,000 earns 4.25% interest, or $255. In the second year, the account earns 4.25% interest on the entire $6,255.

4. Write a program that asks the user for the radius of a circle and then computes the area of that circle (A) using the formula

A = πr 2

Note that there is no “raise to a power” operator in Java. Given the arithmetic operators you know Java has, how can you write an expression that achieves the desired result?

5. Write a program that reads in a temperature in degrees Fahrenheit and returns the corresponding temperature in degrees Celsius. The conversion formula is

C = 5

9 (F – 32)

FahrenheitToCelsius

This program converts Fahrenheit to Celsius. Enter Fahrenheit temperature: 212

Celsius equivalent = 100.0

If you write this program carelessly, the answer always comes out 0. What bug causes this behavior?

6. In Norton Juster’s children’s story The Phantom Tollbooth, the Mathemagician gives Milo the following problem to solve:

4 + 9 - 2 * 16 + 1 / 3 * 6 - 67 + 8 * 2 - 3 + 26 - 1 / 34 + 3 / 7 + 2 - 5 According to Milo’s calculations, which are corroborated by the Mathemagician, this expression “all works out to zero.” If you do the calculation, however, the expression comes out to zero only if you start at the beginning and apply all the operators in strict left-to-right order. What would the answer be if the Mathemagician’s expression were evaluated using Java’s precedence rules? Write a program to verify your calculation.

7. Write a program that converts a metric weight in kilograms to the corresponding English weight in pounds and ounces. The conversion factors you need are

1 kilogram= 2.2 pounds 1 pound = 16 ounces

8. Write a program that computes the average of four integers. 9. There’s an old nursery rhyme that goes like this:

As I was going to St. Ives, I met a man with seven wives, Each wife had seven sacks, Each sack had seven cats, Each cat had seven kits: Kits, cats, sacks, and wives, How many were going to St. Ives?

The last line turns out to be a trick question: only the speaker is going to St. Ives; everyone else is presumably heading in the opposite direction. Suppose, however, that you want to find out how many representatives of the assembled multitude— kits, cats, sacks, and wives—were coming from St. Ives. Write a Java program to calculate and display this result. Try to make your program follow the structure of the problem so that anyone reading your program would understand what value it is calculating.

Chapter 4