5.2 The while Loop
while (loop-continuation-condition) {
// loop-body;
Statement(s);
}
5.2.1 Case Study: Guessing Numbers
LISTING 5.3 GuessNumber.java
import java.util.Scanner;
public class GuessNumber {
public static void main(String[] args) {
// Generate a random number to be guessed
int number = (int)(Math.random() * 101);
Scanner input = new Scanner(System.in);
System.out.println("Guess a magic number between 0 and 100");
int guess = -1;
while (guess != number) {
// Prompt the user to guess the number
System.out.print("\nEnter your guess: ");
guess = input.nextInt();
if (guess == number)
System.out.println("Yes, the number is " + number);
else if (guess > number)
System.out.println("Your guess is too high");
else
System.out.println("Your guess is too low");
} // End of loop
}
}
5.2.5 Input and Output Redirections
In the preceding example, if you have a large number of data to enter, it would be cumbersome to type from the keyboard. You can store the data separated by whitespaces in a text file, say input.txt, and run the program using the following command:
java SentinelValue < input.txt
This command is called input redirection.The program takes the input from the fileinput.txtrather than having the user type the data from the keyboard at runtime. Suppose the contents of the file are
2 3 4 5 6 7 8 9 12 23 32
23 45 67 89 92 12 34 35 3 1 2 4 0
The program should get sum to be518.
Similarly, there is output redirection,which sends the output to a file rather than displaying it on the console. The command for output redirection is:
java ClassName > output.txt
Input and output redirection can be used in the same command. For example, the following command gets input frominput.txtand sends output tooutput.txt:
java SentinelValue output.txt
Try running the program to see what contents are inoutput.txt.
5.3 The do-while Loop
do {
// Loop body;
Statement(s);
} while (loop-continuation-condition);
5.4 The for Loop
for (initial-action; loop-continuation-condition; action-after-each-iteration) {
// loop body;
Statement(s);
}
说明:for循环的表达式1和表达式3可以是任何语句,不一定和循环相关。如果有多个语句,可以使用逗号分隔。所以下面两个for语句都是正确的,尽管不太常见:
for (int i = 1; i < 100; System.out.println(i++));
for (int i = 0, j = 0; (i + j < 10); i++, j++) {
// Do something
}
for语句的表达式二是循环是否继续的条件,如果放空则表示true,相当于一个无限循环。所以下面两个写法都是无限循环。不过(b)的写法更加容易理解。
注意:不要在for的后面加分号,否则会导致for语句的循环体为空。不过对于do…while循环来说,while后的分号是一定要加的,注意和while循环的区别。例:
int i=0;
do {
System.out.println("i is " + i);
i++;
} while (i<10);
5.8.1 Find the Greatest Common Divisor
int gcd = 1; // Initial gcd is 1
int k = 2; // Possible gcd
while (k <= n1 && k <= n2) {
if (n1 % k == 0 && n2 % k == 0)
gcd = k; // Update gcd
k++; // Next possible gcd
}
LISTING 5.9GreatestCommonDivisor.java
import java.util.Scanner;
public class GreatestCommonDivisor {
/** Main method */
public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);
// Prompt the user to enter two integers
System.out.print("Enter first integer: ");
int n1 = input.nextInt();
System.out.print("Enter second integer: ");
int n2 = input.nextInt();
int gcd = 1; // Initial gcd is 1
int k = 2; // Possible gcd
while (k <= n1 && k <= n2) {
if (n1 % k == 0 && n2 % k == 0)
gcd = k; // Update gcd
k++;
}
System.out.println("The greatest common divisor for " + n1 + " and " + n2 + " is " + gcd);
}
}
5.8.3 Case Study: Converting Decimals to Hexadecimals
Hexadecimals are often used in computer systems programming (see Appendix F for an introduction to number systems). How do you convert a decimal number to a hexadecimal number? To convert a decimal numberdto a hexadecimal number is to find the hexadecimal digitshn,hn- 1, hn- 2,……,h2, h1, andh0 such that
d = hn * 16n + hn - 1 * 16n - 1 +hn-2 * 16n -2 + …… +h2 * 162 +h1 * 161 +h0 * 160
These hexadecimal digits can be found by successively dividing d by 16 until the quotient is 0. The remainders areh0,h1,h2, ……, hn- 2, hn - 1, andhn. The hexadecimal digits include the decimal digits 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9, plus A, which is the decimal value 10; B, which is the decimal value 11; C, which is 12; D, which is 13; E, which is 14; and F, which is 15.
For example, the decimal number 123 is7Bin hexadecimal. The conversion is done as follows. Divide 123by16. The remainder is11(B in hexadecimal) and the quotient is7. Continue divide 7by 16. The remainder is 7and the quotient is0. Therefore7B is the hexadecimal number for123.
LISTING5.11Dec2Hex.java
import java.util.Scanner;
public class Dec2Hex {
/** Main method */
public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);
// Prompt the user to enter a decimal integer
System.out.print("Enter a decimal number: ");
int decimal = input.nextInt();
// Convert decimal to hex
String hex = "";
while (decimal != 0) {
int hexValue = decimal % 16;
// Convert a decimal value to a hex digit
char hexDigit = (hexValue <= 9 && hexValue >= 0) ?
(char)(hexValue + '0') : (char)(hexValue - 10 + 'A');
hex = hexDigit + hex;
decimal = decimal / 16;
}
System.out.println("The hex number is " + hex);
}
}
5.8.4问题:Monte Carlo模拟
Monte Carlo模拟是随机数和概率相结合的一种技术。这里我们试着用这个技术来估算pi的近似值。
假设我们往正方形区域中扔一个点,那么这个点落在圆中(称为击中)的概率=圆面积/正方形面积。显然概率对于大样本才有意义,因此我们模拟扔1000000个点,统计一下击中次数,然后估算pi的近似值。
由于 圆面积/正方形面积 =pi/4,因此 pi的近似值就是:4*击中次数/1000000
public class MonteCarloSimulation {
public static void main(String[] args) {
final int NUMBER_OF_TRIALS = 10000000;
int numberOfHits = 0;
for (int i = 0; i < NUMBER_OF_TRIALS; i++) {
double x = Math.random() * 2.0 - 1;
double y = Math.random() * 2.0 - 1;
if (x * x + y * y <= 1)
numberOfHits++;
}
double pi = 4.0 * numberOfHits / NUMBER_OF_TRIALS;
System.out.println("PI is " + pi);
}
}
5.9 Keywords break and continue
break的作用是跳出循环;continue的作用是结束一次循环.
5.11 Case Study: Displaying Prime Numbers
编程求出前50个素数,并且按照每行10个输出到屏幕上。
解题思路:整个问题可以分为四个大步骤:
1、 穷举,从2, 3, 4, 5, 6, ...挨个往上找,直到求满50个为止;⑤
2、 测试给定的数是否素数;①
3、 计算当前的素数个数;③
4、 打印素数② ,如果已经满10个,还要输出一个换行。
LISTING 5.15PrimeNumber.java
public class PrimeNumber {
public static void main(String[] args) {
final int NUMBER_OF_PRIMES = 50; // Number of primes to display
final int NUMBER_OF_PRIMES_PER_LINE = 10; // Display 10 per line
int count = 0; // Count the number of prime numbers
int number = 2; // A number to be tested for primeness
System.out.println("The first 50 prime numbers are \n");
// Repeatedly find prime numbers
while (count < NUMBER_OF_PRIMES) {
// Assume the number is prime
boolean isPrime = true; // Is the current number prime?
// Test whether number is prime
for (int divisor = 2; divisor <= number / 2; divisor++) {
if (number % divisor == 0) { // If true, number is not prime
isPrime = false; // Set isPrime to false
break; // Exit the for loop
}
}
// Display the prime number and increase the count
if (isPrime) {
count++; // Increase the count
if (count % NUMBER_OF_PRIMES_PER_LINE == 0) {
// Display the number and advance to the new line
System.out.println(number);
}
else
System.out.print(number + " ");
}
// Check if the next number is prime
number++;
}
}
}
CHAPTER 5 SUMMARY
1. There are three types of repetition statements: the while loop, the do-while loop, and the for loop.
2. The part of the loop that contains the statements to be repeated is called the loop body.
3. A one-time execution of a loop body is referred to as aniteration of the loop.
4. An infinite loopis a loop statement that executes infinitely.
5. In designing loops, you need to consider both theloop control structureand the loop body.
6. The while loop checks the loop-continuation-condition first. If the condition is tru e, the loop body is executed; if it is false , the loop terminates.
7. The do-while loop is similar to the while loop, except that the do-while loop executes the loop body first and then checks the loop-continuation-condition to decide whether to continue or to terminate.
8. The while loop and the do-while loop often are used when the number of repetitions is not predetermined.
9. A sentinel valueis a special value that signifies the end of the loop.
10. The for loop generally is used to execute a loop body a fixed number of times.
11. The for loop control has three parts. The first part is an initial action that often initializes a control variable. The second part, the loop-continuation-condition , determines whether the loop body is to be executed. The third part is executed after each iteration and is often used to adjust the control variable. Usually, the loop control variables are initialized and changed in the control structure.
12. The while loop and for loop are calledpretest loopsbecause the continuation condition is checked before the loop body is executed.
13. The do-while loop is called aposttest loopbecause the condition is checked after the loop body is executed.
14. Two keywords, break and continue , can be used in a loop.
15. The break keyword immediately ends the innermost loop, which contains the break.
16. The continue keyword only ends the current iteration.