Thinking in Java - 4th Edition
1079 pág.

Thinking in Java - 4th Edition

DisciplinaProgramação Orientada A Objetos5.149 materiais78.192 seguidores
Pré-visualização50 páginas
} /* Output: 
In the middle of test( ), you\u2019ll also see an \u201celse if,\u201d which is not a new keyword but just an 
else followed by a new if statement. 
Although Java, like C and C++ before it, is a \u201cfree-form\u201d language, it is conventional to indent 
the body of a control flow statement so the reader can easily determine where it begins and 
Looping is controlled by while, do-while and for, which are sometimes classified as 
iteration statements. A statement repeats until the controlling Boolean-expression evaluates 
to false. The form for a while loop is: 
The Boolean-expression is evaluated once at the beginning of the loop and again before each 
further iteration of the statement. 
Here\u2019s a simple example that generates random numbers until a particular condition is met: 
//: control/ 
// Demonstrates the while loop. 
public class WhileTest { 
 static boolean condition() { 
 boolean result = Math.random() < 0.99; 
 System.out.print(result + &quot;, &quot;); 
 return result; 
 public static void main(String[] args) { 
 System.out.println(&quot;Inside \u2018while\u2019&quot;); 
 System.out.println(&quot;Exited \u2018while\u2019&quot;); 
} /* (Execute to see output) *///:~ 
94 Thinking in Java Bruce Eckel 
The condition( ) method uses the static method random( ) in the Math library, which 
generates a double value between 0 and 1. (It includes 0, but not 1.) The result value comes 
from the comparison operator <, which produces a boolean result. If you print a boolean 
value, you automatically get the appropriate string \u201ctrue\u201d or \u201cfalse.\u201d The conditional 
expression for the while says: \u201crepeat the statements in the body as long as condition( ) 
returns true.\u201d 
The form for do-while is 
The sole difference between while and do-while is that the statement of the do-while 
always executes at least once, even if the expression evaluates to false the first time. In a 
while, if the conditional is false the first time the statement never executes. In practice, do-
while is less common than while. 
A for loop is perhaps the most commonly used form of iteration. This loop performs 
initialization before the first iteration. Then it performs conditional testing and, at the end of 
each iteration, some form of \u201cstepping.\u201d The form of the for loop is: 
for(initialization; Boolean-expression; step) 
Any of the expressions initialization, Boolean-expression or step can be empty. The 
expression is tested before each iteration, and as soon as it evaluates to false, execution will 
continue at the line following the for statement. At the end of each loop, the step executes. 
for loops are usually used for \u201ccounting\u201d tasks: 
//: control/ 
// Demonstrates &quot;for&quot; loop by listing 
// all the lowercase ASCII letters. 
public class ListCharacters { 
 public static void main(String[] args) { 
 for(char c = 0; c < 128; c++) 
 System.out.println(&quot;value: &quot; + (int)c + 
 &quot; character: &quot; + c); 
} /* Output: 
value: 97 character: a 
value: 98 character: b 
value: 99 character: c 
value: 100 character: d 
value: 101 character: e 
value: 102 character: f 
value: 103 character: g 
value: 104 character: h 
value: 105 character: i 
value: 106 character: j 
Controlling Execution 95 
Note that the variable c is defined at the point where it is used, inside the control expression 
of the for loop, rather than at the beginning of main( ). The scope of c is the statement 
controlled by the for. 
This program also uses the java.lang.Character \u201cwrapper\u201d class, which not only wraps the 
primitive char type in an object, but also provides other utilities. Here, the static 
isLowerCase( ) method is used to detect whether the character in question is a lowercase 
Traditional procedural languages like C require that all variables be defined at the beginning 
of a block so that when the compiler creates a block, it can allocate space for those variables. 
In Java and C++, you can spread your variable declarations throughout the block, defining 
them at the point that you need them. This allows a more natural coding style and makes 
code easier to understand. 
Exercise 1: (1) Write a program that prints values from 1 to 100. 
Exercise 2: (2) Write a program that generates 25 random int values. For each value, 
use an if-else statement to classify it as greater than, less than, or equal to a second 
randomly generated value. 
Exercise 3: (1) Modify Exercise 2 so that your code is surrounded by an \u201cinfinite\u201d while 
loop. It will then run until you interrupt it from the keyboard (typically by pressing Control-
Exercise 4: (3) Write a program that uses two nested for loops and the modulus 
operator (%) to detect and print prime numbers (integral numbers that are not evenly 
divisible by any other numbers except for themselves and 1). 
Exercise 5: (4) Repeat Exercise 10 from the previous chapter, using the ternary operator 
and a bitwise test to display the ones and zeroes, instead of Integer.toBinaryString( ). 
The comma operator 
Earlier in this chapter I stated that the comma operator (not the comma separator, which is 
used to separate definitions and method arguments) has only one use in Java: in the control 
expression of a for loop. In both the initialization and step portions of the control 
expression, you can have a number of statements separated by commas, and those 
statements will be evaluated sequentially. 
Using the comma operator, you can define multiple variables within a for statement, but 
they must be of the same type: 
//: control/ 
public class CommaOperator { 
 public static void main(String[] args) { 
 for(int i = 1, j = i + 10; i < 5; i++, j = i * 2) { 
 System.out.println(&quot;i = &quot; + i + &quot; j = &quot; + j); 
} /* Output: 
i = 1 j = 11 
i = 2 j = 4 
96 Thinking in Java Bruce Eckel 
i = 3 j = 6 
i = 4 j = 8 
The int definition in the for statement covers both i and j. The initialization portion can 
have any number of definitions of one type. The ability to define variables in a control 
expression is limited to the for loop. You cannot use this approach with any of the other 
selection or iteration statements. 
You can see that in both the initialization and step portions, the statements are evaluated in 
sequential order. 
Foreach syntax 
Java SE5 introduces a new and more succinct for syntax, for use with arrays and containers 
(you\u2019ll learn more about these in the Arrays and Containers in Depth chapter). This is often 
called the foreach syntax, and it means that you don\u2019t have to create an int to count through 
a sequence of items\u2014the foreach produces each item for you, automatically. 
For example, suppose you have an array of float and you\u2019d like to select each element in that 
//: control/ 
import java.util.*; 
public class ForEachFloat { 
 public static void main(String[] args) { 
 Random rand = new Random(47); 
 float f[] = new float[10]; 
 for(int i = 0; i < 10; i++) 
 f[i] = rand.nextFloat(); 
 for(float x : f) 
} /* Output: 
The array is populated using the old for loop, because it must be accessed with an index. You 
can see the foreach syntax in the line: 
for(float x : f) { 
This defines a variable x of type float and sequentially assigns each element of f to x. 
Any method that returns an array is a candidate for use with foreach. For example, the 
String class has a method toCharArray( ) that returns an array of char, so you can easily 
iterate through the characters